1

I am trying to understand how the StackedAreaChart colors its series, in order to color series consistently in my application when data is replaced with entirely new data. Initially, I thought StackedAreaChart cycles through 8 default colors. In other words, data series are colored according to their index in getData(), mod 8. But I am encountering unexpected behavior:

enter image description here

The output above comes from the application below, which clears the StackedAreaChart's data and repopulates it with 10 new series every time the window is clicked. As you can see, only the first 8 colors are consistent across clicks/repopulations.

public class TestChartColors extends Application {

    private int clickCount = 0;

    @Override
    public void start(Stage primaryStage) {

        NumberAxis xAxis = new NumberAxis(0, 10, 1);
        NumberAxis yAxis = new NumberAxis(0, 10, 1);
        final StackedAreaChart<Number,Number> chart = new StackedAreaChart<>(xAxis,yAxis);
        chart.setLegendVisible(false);
        chart.setCreateSymbols(false);
        chart.setAnimated(false);

        chart.setOnMouseClicked((MouseEvent event) -> {
            clickCount++;
            chart.getData().clear();
            for(int i=0; i<10; i++){
                chart.getData().add(flatSeries());
            }
            primaryStage.setTitle("After " + clickCount + " clicks.");
        });

        StackPane root = new StackPane();
        root.getChildren().add(chart);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setScene(scene);
        primaryStage.setTitle("Click the window.");
        primaryStage.show();
    }

    private Series<Number,Number> flatSeries(){
        Series<Number,Number> s = new Series<>();
        ObservableList<XYChart.Data<Number, Number>> d = s.getData();
        d.add(new XYChart.Data<>(0, 1));
        d.add(new XYChart.Data<>(10, 1));
        return s;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}
Museful
  • 6,711
  • 5
  • 42
  • 68

1 Answers1

0

Workaround found:

Insert

while(chart.getData().size() % 8 != 0){
    final XYChart.Series<Number,Number> series = new XYChart.Series<>();
    series.getData().add(new XYChart.Data<>(0,0));             
    chart.getData().add(series);
}

before chart.getData().clear();.

StackedAreaChart seems to continue the numbering where it left off, except, strangely, for the first 8 colors.

Museful
  • 6,711
  • 5
  • 42
  • 68