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?
Use hard-coded alert width and height to set alert.setX()
and alert.setY()
and instantiate Alert
inside 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With