gpt4 book ai didi

java - 如何使用 JavaFX BarChart 在水平线上添加文本

转载 作者:行者123 更新时间:2023-12-01 10:35:50 24 4
gpt4 key购买 nike

我使用 BarChart 的扩展类在条形顶部添加垂直线和文本。这工作正常,但我想在水平线的右上角显示一个小文本。

我尝试过但没有成功:

public void addHorizontalValueMarker(Data<X, Y> marker) {
Objects.requireNonNull(marker, "the marker must not be null");
if (horizontalMarkers.contains(marker)) return;
Line line = new Line();
line.setStroke(Color.RED);
marker.setNode(line);
getPlotChildren().add(line);

// Adding a label
Node text = new Text("average");
nodeMap.put(marker.getNode(), text);
getPlotChildren().add(text);

horizontalMarkers.add(marker);
}

@Override
protected void layoutPlotChildren() {
super.layoutPlotChildren();
for (Node bar : nodeMap.keySet()) {
Node text = nodeMap.get(bar);
text.relocate(bar.getBoundsInParent().getMinX() + bar.getBoundsInParent().getWidth()/2 - text.prefWidth(-1) / 2, bar.getBoundsInParent().getMinY() - 30);
}
for (Data<X, Y> horizontalMarker : horizontalMarkers) {
Line line = (Line) horizontalMarker.getNode();
line.setStartX(0);
line.setEndX(getBoundsInLocal().getWidth());
line.setStartY(getYAxis().getDisplayPosition(horizontalMarker.getYValue()) + 0.5); // 0.5 for crispness
line.setEndY(line.getStartY());
line.toFront();
}

}

我做错了什么?

最佳答案

移动标记后,您需要移动文本,即。 e.您的代码集成在所需的位置:

    for (Data<X, Y> horizontalMarker : horizontalMarkers) {
Line line = (Line) horizontalMarker.getNode();
line.setStartX(0);
line.setEndX(getBoundsInLocal().getWidth());
line.setStartY(getYAxis().getDisplayPosition(horizontalMarker.getYValue()) + 0.5); // 0.5 for crispness
line.setEndY(line.getStartY());
line.toFront();

Node text = nodeMap.get(line);
text.relocate(line.getBoundsInParent().getMinX() + line.getBoundsInParent().getWidth()/2 - text.prefWidth(-1) / 2, line.getBoundsInParent().getMinY() - 30);
}

顺便说一句,我建议创建一个专用的标记类来保存线条和文本,而不是使用“松散”的 map 。

关于java - 如何使用 JavaFX BarChart 在水平线上添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34745600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com