How to set the Alert dialog box of a JavaFX dialog box before showing it?

I want to set the position of the warning dialog in the lower right after it displays.

Here is the code:

package alert; import javafx.application.Application; import javafx.geometry.Rectangle2D; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.layout.StackPane; import javafx.stage.Screen; import javafx.stage.Stage; public class MainAlert extends Application { @Override public void start(Stage stage) throws Exception { Scene scene = new Scene(createContent()); stage.setScene(scene); stage.setMaximized(true); stage.show(); } private Parent createContent() { StackPane stackPane = new StackPane(); Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error Dialog"); alert.setHeaderText("Something went wrong"); alert.setContentText("There is an error!"); Button alertButton = new Button("Alert test"); alertButton.setOnAction(event -> { Rectangle2D bounds = Screen.getPrimary().getVisualBounds(); System.out.println("alert.getWidth() = " + alert.getWidth()); System.out.println("alert.getHeight() = " + alert.getHeight()); alert.setX(bounds.getMaxX() - alert.getWidth()); alert.setY(bounds.getMaxY() - alert.getHeight()); alert.showAndWait(); }); stackPane.getChildren().add(alertButton); return stackPane; } } 

But his position is in the upper left corner. The reason is that alert.getWidth() and alert.getHeight() always return NaN . I already tried Platform.runLater() , unfortunately, did not use it.

How to fix it?

+5
source share
2 answers

Use the hardcoded width and height of the alert to set alert.setX() and alert.setY() and create an Alert instance inside the Action event

 private Parent createContent() { StackPane stackPane = new StackPane(); Button alertButton = new Button("Alert test"); alertButton.setOnAction(event -> { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error Dialog"); alert.setHeaderText("Something went wrong"); alert.setContentText("There is an error!"); Rectangle2D bounds = Screen.getPrimary().getVisualBounds(); alert.setX(bounds.getMaxX() - 366); alert.setY(bounds.getMaxY() - 185); alert.showAndWait(); }); stackPane.getChildren().add(alertButton); return stackPane; } 
+1
source

Try

 Alert alert = new Alert(Alert.AlertType.ERROR); DialogPane pane = alert.getDialogPane(); pane.setPrefHeight(150.0); alert.setWidth(pane.getWidth()); Rectangle2D bounds = Screen.getPrimary().getBounds(); alert.setX(bounds.getMaxX() - alert.getWidth()); alert.setY(bounds.getMaxY() - pane.getPrefHeight() - 25); 

The-25 is required if you have a designed warning window. This is pretty ugly, but so far the best solution I can come up with. You can also consider the OS taskbar.

+1
source

Source: https://habr.com/ru/post/1273520/


All Articles