我想在显示后将警告对话框位置设置在右下角。
代码如下:
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()
并在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;
}
关于java - 如何在显示之前设置 JavaFX 警报对话框位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47387392/