java fx节点 位置更新_如何根据JavaFX 8中的特定祖先获取节点边界?

您已经找到了Chart-Plot背景节点,并根据其祖先需要简单地调用它来获取坐标

chartPlotArea.getBoundsInParent();

如果它们之间有多个祖先,你可以获得char-plot界限

在AnchorPane这样的坐标系中

Bounds bounds =

anchorPane.sceneToLocal(chartPlotArea.localToScene(chartPlotArea.getBoundsInLocal()));

这里的一个小技巧是,它们将为0,直到你显示阶段并让javaFX布局节点,所以你需要在.show()方法后更新它,所以结果可能如下所示:

NumberAxis numberAxis = new NumberAxis();

LineChart chart = new LineChart(numberAxis,new NumberAxis());

chart.getYAxis().setSide(Side.RIGHT);

Node chartPlotArea = chart.lookup(".chart-plot-background");

chartPlotArea.setStyle("-fx-background-color: cyan");

Text text = new Text();

text.setText("Text");

AnchorPane anchorPane = new AnchorPane();

AnchorPane.setTopAnchor(chart,0.0);

AnchorPane.setRightAnchor(chart,0.0);

AnchorPane.setBottomAnchor(chart,0.0);

AnchorPane.setLeftAnchor(chart,0.0);

anchorPane.getChildren().addAll(chart,text);

Scene scene = new Scene(anchorPane);

primaryStage.setScene(scene);

primaryStage.setMaximized(true);

primaryStage.show();

Bounds bounds =

anchorPane.sceneToLocal(chartPlotArea.localToScene(chartPlotArea.getBoundsInLocal()));

double textRelativeX = (bounds.getMinX() + bounds.getMaxX()) / 2 - text.getLayoutBounds().getWidth() / 2;

double textRelativeY = bounds.getMinY() - text.getLayoutBounds().getHeight() / 2;

AnchorPane.setLeftAnchor(text,textRelativeX);

AnchorPane.setTopAnchor(text,textRelativeY);

请记住,如果您想在调整大小时更改坐标,可以将其绑定到图表或chartPlotArea绑定/宽度更改,这样的事情

chart.layoutBoundsProperty().addListener((observable,oldValue,newValue) -> {

double textRelativeXz = (newValue.getMinX() + newValue.getMaxX()) / 2 - text.getLayoutBounds().getWidth() / 2;

double textRelativeYz = newValue.getMinY() - text.getLayoutBounds().getHeight() / 3;

AnchorPane.setLeftAnchor(text,textRelativeXz);

AnchorPane.setTopAnchor(text,textRelativeYz);

});

编辑:如果你有一个以上的祖先,你可以这样做,以接收anchorPane坐标系中的char-plot界限

Bounds bounds =

anchorPane.sceneToLocal(chartPlotArea.localToScene(chartPlotArea.getBoundsInLocal()));

即使它们之间存在多个祖先,这也会起作用

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值