JavaFX如何将对话框/警报带到屏幕的前面

时间:2016-08-05 23:53:34

标签: java javafx javafx-8

我想强制警报在其他应用程序之上。警报似乎缺少setAlwaysOnTop函数。

我看过这篇文章:JavaFX 2.2 Stage always on top

我试过了:

  1. 创建一个新舞台和stage.setAlwaysOnTop(true),然后是alert.initOwner(舞台)。
  2. 创建一个新阶段和stage.initModality(Modality.APPLICATION_MODAL),然后是alert.initOwner(阶段)。
  3. 有谁知道如何实现这个目标?

    编辑: 我使用的是Java 8。

    让我说我已经开启了野生动物园,它正在集中注意力。当我调用它的showAndWait()函数时,我想在Safari的前面将Alert发送到屏幕的顶部。

4 个答案:

答案 0 :(得分:15)

 Alert alert = new Alert(Alert.AlertType.WARNING, "I Warn You!", ButtonType.OK, ButtonType.CANCEL);

 Stage stage = (Stage) alert.getDialogPane().getScene().getWindow();
 stage.setAlwaysOnTop(true);
 stage.toFront(); // not sure if necessary

答案 1 :(得分:7)

您可以从DialogPane“窃取”Alert并将其显示在实用程序Stage中。对于此窗口,您可以通常的方式设置alwaysOnTop属性:

Alert alert = new Alert(Alert.AlertType.WARNING, "I Warn You!", ButtonType.OK, ButtonType.CANCEL);
DialogPane root = alert.getDialogPane();

Stage dialogStage = new Stage(StageStyle.UTILITY);

for (ButtonType buttonType : root.getButtonTypes()) {
    ButtonBase button = (ButtonBase) root.lookupButton(buttonType);
    button.setOnAction(evt -> {
        root.setUserData(buttonType);
        dialogStage.close();
    });
}

// replace old scene root with placeholder to allow using root in other Scene
root.getScene().setRoot(new Group());

root.setPadding(new Insets(10, 0, 10, 0));
Scene scene = new Scene(root);

dialogStage.setScene(scene);
dialogStage.initModality(Modality.APPLICATION_MODAL);
dialogStage.setAlwaysOnTop(true);
dialogStage.setResizable(false);
dialogStage.showAndWait();
Optional<ButtonType> result = Optional.ofNullable((ButtonType) root.getUserData());
System.out.println("result: "+result.orElse(null));

答案 2 :(得分:5)

我尝试过fabians和claimoars解决方案,并简化为:

Update-Database

这适用于我的Eclipse / JavaFX应用程序。

答案 3 :(得分:-1)

试试这个

 Alert a = new Alert(AlertType.ERROR);
        a.setTitle("Title of alert");
        a.initStyle(StageStyle.UNDECORATED);
        a.setContentText("details of message");
        a.showAndWait();

如果发生某些错误,您可以使用此强制警告消息显示给用户,例如当用户以字符串形式输入数据并接受数据为整数时。 我希望能帮助你。

请注意: 我认为警报适用于javafx(jdk 1.8)。

相关问题