这是一个显示我的问题的示例代码:
public class TestApplication extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
VBox box = new VBox();
Button button = new Button("Add a Label at top.");
button.setOnAction(event -> {
box.getChildren().addFirst(new Label("Label"));
// Here I want to compute something about coordinate
Platform.runLater(() -> System.out.println(button.getBoundsInParent().getMinY()));
});
box.getChildren().add(button);
box.setPrefSize(500, 500);
Scene scene = new Scene(box);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
点击按钮后,窗口的布局如下:
然后我想要得到button.getBoundsInParent().getMinY()
。
我认为这minY
等于标签的高度(这也是我想要得到的)。
但是结果却是-1.399999976158142(不知道为什么不是0,不过和我这次的问题没关系)。
我想问的是:
为什么只能获取到添加标签前的坐标,如何才能获取到 位置的正确坐标System.out.println
。
提前感谢您的帮助!🙏
更新:
我已阅读评论。我想要实现的功能是滚动以使节点可见。
button
在我的程序中,和之间有很多层容器ScrollPane
。所以我尝试编写一个静态方法来处理这个任务。
它如下所示:
public class TestApplication extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
VBox box = new VBox();
Button button = new Button("Add a Label at top.");
button.setOnAction(event -> {
box.getChildren().addFirst(new Label("Label"));
Platform.runLater(() -> scrollVerticalToVisible(button));
});
box.getChildren().add(button);
box.setPrefSize(500, 500);
Scene scene = new Scene(new ScrollPane(box));
primaryStage.setScene(scene);
primaryStage.show();
}
public static void scrollVerticalToVisible(Node node) {
Bounds bounds = node.getBoundsInParent();
Node container = node;
while (container != null && !(container instanceof ScrollPane)) {
bounds = container.localToParent(bounds);
container = container.getParent();
}
if (container == null) {
return;
}
ScrollPane scrollPane = (ScrollPane) container;
double height = scrollPane.getContent().getBoundsInLocal().getHeight();
// Same Issue, I cannot get correct y
double y = bounds.getMaxY() - scrollPane.getViewportBounds().getMinY();
double viewHeight = scrollPane.getViewportBounds().getHeight();
System.out.println(y + " " + viewHeight + " " + height);
scrollPane.setVvalue((y - viewHeight) / (height - viewHeight));
}
public static void main(String[] args) {
launch(args);
}
}