0

I want to know if I can create an array of XYChart.Series<String, Number> on JavaFX?

Because I need to create a XYChart.Series for each person on database, and I tried to make an array of XYChart.Series<String, Number> for my LineChart but I couldn't.

This is what I tried:

List<XYChart.Series<String, Number>> seriesList = new ArrayList<XYChart.Series<String, Number>>();

Because I had no idea how to do it otherways.

Can you please help me?

fabian
  • 80,457
  • 12
  • 86
  • 114
Ertan Hasani
  • 797
  • 1
  • 18
  • 37
  • 1
    Chart takes an `ObservableList` of series data for it's `setData()` method, so you could have had `ObservableList> seriesList = FXCollections.observableArrayList();` then `chart.setData(seriesList);` or you can call `chart.getData().add(mySeries);` for each as you are building it/them, which uses the default collection in the new chart. – Geoff Dec 12 '16 at 00:00

1 Answers1

1

You can create a array of the raw type and assign it to a variable declared with a generic type.

int size = ...
XYChart.Series<String, Number>[] seriesArray = new XYChart.Series[size];

Update

Array elements still need to be initialized this way since arrays generated this way are filled with null elements.

Java 8 provides a way create & initilize a array using short code via streams API:

XYChart.Series<String, Number>[] seriesArray = Stream.<XYChart.Series<String, Number>>generate(XYChart.Series::new).limit(size).toArray(XYChart.Series[]::new);
fabian
  • 80,457
  • 12
  • 86
  • 114
  • Thank you :), but why it gives me NullPointerException here: seriesArray[i].setName("emri "); – Ertan Hasani Dec 11 '16 at 23:12
  • @ErtanHasani Arrays are filled with `null` elements, if they are created using `Type[size]`. You still need to assign instances to the array's elements. – fabian Dec 11 '16 at 23:13
  • i added this line first series[i] = new XYChart.Series(); and now i got Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: [Ljavafx.scene.chart.XYChart$Series; cannot be cast to javafx.scene.chart.XYChart$Series – Ertan Hasani Dec 11 '16 at 23:20
  • Not sure how exactly you managed to create produce this exception, but `[Ljavafx.scene.chart.XYChart$Series;` is a array of `javafx.scene.chart.XYChart.Series` so somwhere you attempt to assign such an array to a `javafx.scene.chart.XYChart.Series` target type. – fabian Dec 11 '16 at 23:39
  • Sorry my bad. I had something else on my code that made that comes out. Found that out . Thank you so much. – Ertan Hasani Dec 11 '16 at 23:44