I add some text at the top of bars (the value of each bar). It\'s working but the problem is I want to remove this text each time I update the chart. In fact, text stays aft
Thanks to Roland I was able to create the following chart with fixed alignments. This might be helpful for someone due the lack of proposed solutions for this problem.
public class CustomBarChart extends BarChart {
Map nodeMap = new HashMap<>();
public CustomBarChart(Axis xAxis, Axis yAxis) {
super(xAxis, yAxis);
this.setBarGap(0.0);
}
@Override
protected void seriesAdded(Series series, int seriesIndex) {
super.seriesAdded(series, seriesIndex);
for (int j = 0; j < series.getData().size(); j++) {
Data item = series.getData().get(j);
Text text = new Text(item.getYValue().toString());
text.setStyle("-fx-font-size: 10pt;");
TextFlow textFlow = new TextFlow(text);
textFlow.setTextAlignment(TextAlignment.CENTER);
nodeMap.put(item.getNode(), textFlow);
this.getPlotChildren().add(textFlow);
}
}
@Override
protected void seriesRemoved(final Series series) {
for (Node bar : nodeMap.keySet()) {
Node text = nodeMap.get(bar);
this.getPlotChildren().remove(text);
}
nodeMap.clear();
super.seriesRemoved(series);
}
@Override
protected void layoutPlotChildren() {
super.layoutPlotChildren();
for (Node bar : nodeMap.keySet()) {
TextFlow textFlow = nodeMap.get(bar);
if (bar.getBoundsInParent().getHeight() > 30) {
((Text) textFlow.getChildren().get(0)).setFill(Color.WHITE);
textFlow.resize(bar.getBoundsInParent().getWidth(), 200);
textFlow.relocate(bar.getBoundsInParent().getMinX(), bar.getBoundsInParent().getMinY() + 10);
} else {
((Text) textFlow.getChildren().get(0)).setFill(Color.GRAY);
textFlow.resize(bar.getBoundsInParent().getWidth(), 200);
textFlow.relocate(bar.getBoundsInParent().getMinX(), bar.getBoundsInParent().getMinY() - 20);
}
}
}
}