浏览网络我没有找到任何解决方案。下图解释了我想要实现的目标:
<小时/>为具有一个屏幕的计算机创建了一种可能的解决方案,对于多个屏幕,它需要修改。虽然它有效[适用于一个屏幕],但我不确定这是否是正确的方法......
问题:
这是正确的方向吗?JavaFX 有可能没有为 Nodes
构建这样的功能,而只为 Stage
提供这样的功能吗?
代码:
/**
* Makes a question to the user.
*
* @param text
* the text
* @param node
* The node owner of the Alert
* @return true, if successful
*/
public static boolean doQuestion(String text, Node node) {
questionAnswer = false;
// Show Alert
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.initStyle(StageStyle.UTILITY);
alert.setHeaderText("");
alert.setContentText(text);
// Make sure that JavaFX doesn't cut the text with ...
alert.getDialogPane().getChildren().stream().filter(item -> node instanceof Label)
.forEach(item -> ((Label) node).setMinHeight(Region.USE_PREF_SIZE));
// I noticed that height property is notified after width property
// that's why i choose to add the listener here
alert.heightProperty().addListener(l -> {
// Width and Height of the Alert
int alertWidth = (int) alert.getWidth();
int alertHeight = (int) alert.getHeight();
// Here it prints 0!!
System.out.println("Alert Width: " + alertWidth + " , Alert Height: " + alertHeight);
// Find the bounds of the node
Bounds bounds = node.localToScreen(node.getBoundsInLocal());
int x = (int) (bounds.getMinX() + bounds.getWidth() / 2 - alertWidth / 2);
int y = (int) (bounds.getMinY() + bounds.getHeight() / 2 - alertHeight / 2);
// Check if Alert goes out of the Screen on X Axis
if (x + alertWidth > InfoTool.getVisualScreenWidth())
x = (int) (getVisualScreenWidth() - alertWidth);
else if (x < 0)
x = 0;
// Check if Alert goes out of the Screen on Y AXIS
if (y + alertHeight > InfoTool.getVisualScreenHeight())
y = (int) (getVisualScreenHeight() - alertHeight);
else if (y < 0)
y = 0;
// Set the X and Y of the Alert
alert.setX(x);
alert.setY(y);
});
return questionAnswer;
}
上面缺少的两个方法:
/**
* Gets the visual screen width.
*
* @return The screen <b>Width</b> based on the <b>visual bounds</b> of the
* Screen.These bounds account for objects in the native windowing
* system such as task bars and menu bars. These bounds are
* contained by Screen.bounds.
*/
public static double getVisualScreenWidth() {
return Screen.getPrimary().getVisualBounds().getWidth();
}
/**
* Gets the visual screen height.
*
* @return The screen <b>Height</b> based on the <b>visual bounds</b> of the
* Screen.These bounds account for objects in the native windowing
* system such as task bars and menu bars. These bounds are
* contained by Screen.bounds.
*/
public static double getVisualScreenHeight() {
return Screen.getPrimary().getVisualBounds().getHeight();
}
最佳答案
看看 JavaFX CenteredAlert 的实现
此实现将alert居中在当前屏幕,如果需要实现不同的居中逻辑可以通过编辑centerAlertInStage()方法来实现
关于java - JavaFX 节点上的中心 Java 警报 [例如 StackPane 或按钮],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41887437/