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

问题描述 投票:4回答:4

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

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

我试过了:

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

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

编辑:我使用的是Java 8。

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

java javafx javafx-8
4个回答
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));

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

5
投票

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

((Stage) dialog.getDialogPane().getScene().getWindow()).setAlwaysOnTop(true);

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


-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)。

© www.soinside.com 2019 - 2024. All rights reserved.