I have a problem with my "Do you want to quit" interface.
As of today I can move the alert box where I want, which I would like to change - preferably fixating the alert in a set position (in the middle of the screen).
The problem with this alert being able to move around is that on setups with more than one screen you could move it wherever you would like (out of the game interface fe).
Button btExit = new Button("Exit Game");
btExit.setMinWidth(100);
buttonGrid.add(btExit, 0, 5);
btExit.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("");
alert.initModality(Modality.APPLICATION_MODAL);
alert.initOwner(primaryStage);
alert.setHeaderText("Quit Game");
alert.setContentText("Are you sure?");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK){
System.exit(1);
}else
{
alert.close();
}
}
});
If you want to prevent the user from moving the dialog, simply set the style to UNDECORATED
which removes the window border the user could use to move around the alert (as well as the x-button, but the user has a alternative way of closing the dialog):
@Override
public void start(Stage primaryStage) {
Button btn = new Button("Show alert");
btn.setOnAction((ActionEvent event) -> {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.getDialogPane().setStyle("-fx-border-color: black;");
alert.initModality(Modality.APPLICATION_MODAL);
alert.initStyle(StageStyle.UNDECORATED);
alert.initOwner(primaryStage);
alert.setHeaderText("Quit Game");
alert.setContentText("Are you sure?");
Optional<ButtonType> result = alert.showAndWait();
if (result.orElse(null) == ButtonType.OK) {
Platform.exit();
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 600, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
Some other modifications I did here:
Replace
System.exit(1);
with
Platform.exit();
To shut down the application more gracefully. After all a status code of 1
indicates abnormal termination .
Remove
else { alert.close(); }
this is never necessary, since showAndWait
only returns after the Alert
is closed anyways...
Used
result.orElse(null)
to retrieve the value without an error, even if the Optional
is empty (not 100% sure this can happen in this case, but it does not hurt to do it like this).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.