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

时间:2016-01-12 13:56:07

标签: 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();
    }

}

我做错了什么?

1 个答案:

答案 0 :(得分:1)

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

    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);
    }

顺便说一句,我建议创建一个专用的标记类来保存行和文本,而不是使用&#34;松散&#34;地图。