我相信问题在于窗口的显示顺序.使用以下命令进行测试,重现了Windows 10(使用JavaFX 12.0.1)上的问题:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
var alert = new Alert(AlertType.INFORMATION);
alert.initModality(Modality.APPLICATION_MODAL);
alert.setHeaderText(null);
alert.setContentText("This is a test of application modality.");
alert.show();
primaryStage.setScene(new Scene(new StackPane(new Label("Hello, World!")), 500, 300));
primaryStage.show();
}
}
上面的结果导致对话框窗口的模式不正确.但是,如果将alert.show()移到primaryStage.show()之后,则一切正常.
由于您是在FXML控制器的initialize()方法中显示Alert的,因此在显示主窗口之前,代码可能正在执行.如果要在应用程序开始时立即显示警报,则至少有两个选项:
>在Platform.runLater调用中调用show(),就像在your answer中一样.
>这样做的缺点是它使您的代码高度依赖看似无关的代码.例如,如果出于任何原因更改了显示主窗口的方式和时间,则此选项可能会中断.
>将方法添加到Controller类,并在显示其他窗口后调用它.
@Override
public void start(Stage primaryStage) throws IOException {
FXMLLoader loader = new FXMLLoader(/*location*/);
primaryStage.setScene(new Scene(loader.load()));
primaryStage.show();
loader.getController().showMyAwesomeAlert();
}