如何在显示之前设置JavaFX Alert对话框位置?

时间:2017-11-20 07:59:12

标签: java javafx

我希望在显示后在右下角设置警告对话框位置。

以下是代码:

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;
    }
}

但它的位置在左上角。原因是alert.getWidth()alert.getHeight()始终返回NaN。我已经尝试了Platform.runLater(),但遗憾的是没有用。

如何解决?

2 个答案:

答案 0 :(得分:1)

使用硬编码警报宽度和高度来设置alert.setX()alert.setY()并在Action事件中实例化Alert

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 :(得分:1)

尝试

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);

如果您有装饰的警报窗口,则需要 - 25。这很丑陋但是现在我能提出最好的解决方案。您也可以考虑操作系统'任务栏。