1 回答
TA贡献1993条经验 获得超5个赞
您已经找到了 Chart-Plot 背景节点,要根据其祖先获取坐标,您只需调用
chartPlotArea.getBoundsInParent();
如果它们之间有多个祖先,您可以像这样在 AnchorPane 坐标系中获得字符图边界
Bounds bounds =
anchorPane.sceneToLocal(chartPlotArea.localToScene(chartPlotArea.getBoundsInLocal()));
这里的一个小技巧是,在您显示舞台并让 javaFX 布局节点之前,它们将是 0,因此您需要在.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 坐标系中接收字符图边界
Bounds bounds =
anchorPane.sceneToLocal(chartPlotArea.localToScene(chartPlotArea.getBoundsInLocal()));
即使他们之间有不止一个祖先,这也会起作用
添加回答
举报