我正在编写一个显示Alert的程序,并且试图调用initOwner,以便它将使用应用程序图标,但是我正在获取NullPointerException

这是一个最小的示例:

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);
    }
}

以及相关的堆栈跟踪:
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)

我究竟做错了什么?

我在Linux中使用Oracle的JDK 1.8.0_51。

最佳答案

因为没有将NullPointerException设置为主阶段,所以您获得了Scene

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);
    }

}

07-26 09:14