java fx alert_无法更改JavaFX中的Alert窗口的initModality

我相信问题在于窗口的显示顺序.使用以下命令进行测试,重现了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();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值