1 回答

TA貢獻1993條經驗 獲得超6個贊
您已經找到了 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()));
即使他們之間有不止一個祖先,這也會起作用
添加回答
舉報