我想在显示警报对话框后在右下角设置警报对话框位置。
这是代码:
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()
了,不幸的是没有用。
如何解决?
使用硬编码的警报宽度和高度来设置alert.setX()
和alert.setY()
,并在操作事件中实例化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;
}
尝试
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。这很丑陋,但目前是我能想到的最好的解决方案。此外,您可能还需要考虑操作系统的任务栏。