I am writing a program that shows an Alert, and I'm trying to call initOwner so that it will use the application icon, but I'm getting a NullPointerException.
Here's a minimal example:
import javafx.application.Application;
import javafx.scene.control.Alert;
import javafx.stage.Stage;
public class AlertTest extends Application {
    @Override
    public void start(final Stage primaryStage) throws Exception {
        final Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.initOwner(primaryStage); // line 9
        alert.showAndWait();
    }
    public static void main(final String... args) {
        launch(args);
    }
}
and the relevant stack trace:
Caused by: java.lang.NullPointerException
    at javafx.scene.control.HeavyweightDialog.updateStageBindings(HeavyweightDialog.java:319)
    at javafx.scene.control.HeavyweightDialog.initOwner(HeavyweightDialog.java:120)
    at javafx.scene.control.Dialog.initOwner(Dialog.java:451)
    at AlertTest.start(AlertTest.java:9)
What am I doing wrong?
I'm using Oracle's JDK 1.8.0_51 in Linux.
You are getting a NullPointerException because you did not set a Scene to the primary stage.
public class Main extends Application {
    @Override
    public void start(final Stage primaryStage) throws Exception {
        final Alert alert = new Alert(Alert.AlertType.INFORMATION);
        primaryStage.setScene(new Scene(new Group(), 300, 300, Color.BLACK));
        alert.initOwner(primaryStage);
        alert.showAndWait();
    }
    public static void main(final String... args) {
        launch(args);
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With