geometrikal
geometrikal

Reputation: 3294

JavaFX chart: proper way to switch series data

We have a java program that takes a CSV file and processes it into multiple sets of data. The data is displayed one at a time on an XYChart with a ComboBox to choose between them. However we keep running into problems updating / changing the data:

First we had a bunch of ObservableList objects for each data series, e.g.

ObservableList<XYChart.Data<T,V>> data = FXCollections.observableArrayList();

and whenever the ChoiceBox selection was changed we would clear the series and add the one corresponding to the different selection, e.g.

theChart.getData().clear();
theChart.getData().add(new XYChart.Series<T,V>(data));

However, we would get errors when data was updated saying something about same data added to multiple charts. I think this would occur if theChart.getData().add(new XYChart.Series<T,V>(data)); had been called twice for the same data beforehand.

So I wrapped it up like

XYChart.Series<T,V> series = new XYChart.Series<>(data);

and changed the chart data like:

theChart.getData().clear();
theChart.getData().add(series);

Works fine on my computer but on another when data is cleared and then added to we get a null pointer exception during the series onChanged event, which suggests some kind of race condition.

Questions:

Upvotes: 1

Views: 2104

Answers (1)

transgressoft
transgressoft

Reputation: 165

You can't do a clear(), that will throw an UnsupportedOperationException. The proper way to update the chart is setting a new empty ObservableList and then add the new XYChart.Series with the proper XYChart.Data objects into.

chart.setData(FXCollections.observableArrayList());
XYChart.Series<T, V> series = new XYChart.Series<T, V>();
XYChart.Data<T, V> data = new XYChart.Data<T, V>(t_type_Value, v_type_Value);

series.getData().add(data);

chart.getData().add(series);

Upvotes: 1

Related Questions