I want to set alert dialog position at right bottom corner after it is shown.
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 its position is at left-top corner. The reason is alert.getWidth()
and alert.getHeight()
are always returning NaN
. I already tried Platform.runLater()
, unfortunately no use.
How to fix it?