Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set JavaFX Alert dialog position before it is shown?

Tags:

java

javafx

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?

like image 464
Grolisc Avatar asked Oct 29 '22 22:10

Grolisc


1 Answers

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;
    }
like image 126
aKilleR Avatar answered Nov 01 '22 08:11

aKilleR