How to add text to a horizontal line using JavaFX BarChart

I use the extended BarChart class to add vertical lines and text on top of bars. This works fine, but I want to display a little text in the upper right corner of the horizontal line.

I tried this without success:

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

}

What am I doing wrong?

0
source share
1 answer

You need to move the text after moving the marker, i.e. e. your code is integrated in the desired position:

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

By the way, I suggest creating a dedicated marker class for what contains a string and text instead of using a “free” map.

+1
source

All Articles