Reputation: 147
I want to force an Alert to be on top of other applications. Alerts seems to be lacking a setAlwaysOnTop function.
I have seen this post: JavaFX 2.2 Stage always on top.
I have tried:
Does anyone know how to achieve this?
Edit: I am using Java 8.
Let say I have safari opened, and it is being focused. I want to bring the Alert to the top of the screen, in front of safari, when I call its showAndWait() function.
Upvotes: 6
Views: 15505
Reputation: 1298
I have tried fabians and claimoars solutions and simplified them to:
((Stage) dialog.getDialogPane().getScene().getWindow()).setAlwaysOnTop(true);
This works in my Eclipse / JavaFX app.
Upvotes: 10
Reputation: 271
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
Upvotes: 24
Reputation: 82461
You could "steal" the DialogPane
from a Alert
and show it in a utility Stage
. For this window you can set the alwaysOnTop
property the usual way:
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));
Upvotes: 10
Reputation: 89
try this
Alert a = new Alert(AlertType.ERROR);
a.setTitle("Title of alert");
a.initStyle(StageStyle.UNDECORATED);
a.setContentText("details of message");
a.showAndWait();
you can use this to force alert message to appear to the user if some thing wrong happen,for example when user enter the data as string and you accept data as integer. i hope that helps you.
note: i think Alert is available for javafx (jdk 1.8).
Upvotes: -1