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

标签 java text javafx line bar-chart

我使用 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/

相关文章:

css - 自动换行 : break-word adds padding on top of text

image - .Jar 文件在 NeBeans 中运行良好,但在/dist lib 中运行不佳

java - 如何设置 JavaFX WebView 的编码?

Java:枚举 toString()

java - 如何以编程方式关闭Android中的对话框?

java - 跟进: Create an an array of objects from classname

java - 将 XML 导入到 app-properties.xml

javascript - 当字符串位于注释中时,如何改进此正则表达式以使其不匹配

html - 如何让我的文本包裹在一个 div 中?

java - 警告 : CSS Error parsing