2 回答
TA贡献1821条经验 获得超4个赞
使用 showAndWait 时警报上的 onShown 处理程序的(对我来说出乎意料的)问题是,在调用处理程序时,警报尚未显示且尚未确定大小/位置 - 这有点疯狂,可能被视为错误.
一种解决方法是侦听警报的显示属性并在该侦听器中进行任何大小/位置调整。类似的东西(显然只是一个 poc)
alert.showingProperty().addListener((src, ov, nv) -> {
double x = alert.getX();
double y = alert.getY();
double w = alert.getWidth();
double h = alert.getHeight();
// as example just adjust if location top/left is off
// production must cope with bottom/right off as well, obviously
if (x < 0) {
alert.setWidth(w + x);
alert.setY(0);
}
if (y <0) {
alert.setHeight(h + y);
alert.setY(0);
}
});
alert.showAndWait();
仅供参考:我真的认为这是一个错误,所以提交了一个问题让我们看看会发生什么
TA贡献1934条经验 获得超2个赞
当您将对话框定位在舞台中央时.. 如果舞台也(至少部分)在您的屏幕之外,则该对话框只能在屏幕之外。
请看下面的代码示例..
@Override
public void start(Stage stage) {
Pane pane = new Pane();
Scene scene = new Scene(pane, 800, 500);
Button button = new Button("Alert");
button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setHeaderText("This is an alert!");
alert.initOwner(stage);
alert.setOnShown(new EventHandler<DialogEvent>() {
@Override
public void handle(DialogEvent event) {
System.out.println(alert.getOwner().getX());
System.out.println(alert.getOwner().getY());
//Values from screen
int screenMaxX = (int) Screen.getPrimary().getVisualBounds().getMaxX();
int screenMaxY = (int) Screen.getPrimary().getVisualBounds().getMaxY();
//Values from stage
int width = (int) stage.getWidth();
int height = (int) stage.getHeight();
int stageMaxX = (int) stage.getX();
int stageMaxY = (int) stage.getY();
//Maximal values your stage
int paneMaxX = screenMaxX - width;
int paneMaxY = screenMaxY - height;
//Check if the position of your stage is not out of screen
if (stageMaxX > paneMaxX || stageMaxY > paneMaxY) {
//Set stage where ever you want
}
}
});
alert.showAndWait();
}
});
pane.getChildren().add(button);
stage.setScene(scene);
stage.show();
}
添加回答
举报