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

Xia*_* Li 4 java javafx javafx-8

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

我看过这篇文章:JavaFX 2.2 Stage始终排在最前面.

我试过了:

  1. 创建一个新的舞台和stage.setAlwaysOnTop(true),然后是alert.initOwner(舞台).
  2. 创建一个新阶段和stage.initModality(Modality.APPLICATION_MODAL),然后是alert.initOwner(阶段).

有谁知道如何实现这一目标?

编辑:我使用的是Java 8.

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

小智 18

 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
Run Code Online (Sandbox Code Playgroud)

  • 即使没有`stage.toFront();`也能正常工作。 (2认同)

fab*_*ian 8

你可以DialogPaneAlert一个实用程序中"窃取" 并显示它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));
Run Code Online (Sandbox Code Playgroud)


Rob*_*rov 6

我尝试了fabians和Claimoars解决方案,并将其简化为:

((Stage) dialog.getDialogPane().getScene().getWindow()).setAlwaysOnTop(true);
Run Code Online (Sandbox Code Playgroud)

这可以在我的Eclipse / JavaFX应用程序中使用。