JavaFX BarChart, Set Series Color by Series Name

Viewed 2979

I am trying to dynamically set the BarChart Series color.

I want to have always the same color for the same Series name. Its not always the same Series names in the chart, which is why I cannot rely on the position in the chart (colors per default always the same at the same position in the data list).

chart.getData().addListener(new ListChangeListener<Series<String, Number>>() {

        @Override
        public void onChanged(
            final javafx.collections.ListChangeListener.Change<? extends Series<String, Number>> c) {
        while (c.next()) {
            for (final Series s : c.getAddedSubList()) {
            if ("booking".equalsIgnoreCase(s.getName())) {
                if (s.getNode() != null) {
                s.getNode().getStyleClass().add(".source-background-booking");
                }
            } else if ("airbnb".equalsIgnoreCase(s.getName())) {
                if (s.getNode() != null) {
                s.getNode().getStyleClass().add(".source-background-airbnb");
                }
            }
            }
        }
        }
    });

This does not work as expected. The Series's Node is always null. Why is that?

EDIT: Another approach that is not working:

chart.getData().addListener(new ListChangeListener<Series<String, Number>>() {

        @Override
        public void onChanged(
            final javafx.collections.ListChangeListener.Change<? extends Series<String, Number>> c) {
        while (c.next()) {
            System.err.println("Series " + c.getAddedSubList() + " kommt rein..");
            for (final Series<String, Number> s : c.getAddedSubList()) {
            s.nodeProperty().addListener(new ChangeListener<Node>() {

                @Override
                public void changed(final ObservableValue<? extends Node> observable, final Node oldValue,
                    final Node newValue) {
                System.err.println("Already good");
                if ("booking".equalsIgnoreCase(s.getName())) {
                    newValue.getStyleClass().add(".source-background-booking");
                    System.err.println("Seems to work..");
                } else if ("airbnb".equalsIgnoreCase(s.getName())) {
                    newValue.getStyleClass().add(".source-background-airbnb");
                    System.err.println("Seems to work..");
                }
                }
            });

            }
        }
        }
    });

Unfortunately, this callback seems to be never called..

1 Answers
Related