Reading from Arrays and Collections

In many situations, the data is contained in a memory array. Although you can use the Chart FX for Java API to loop through array elements, read and populate the chart, you can also do so in an easier way.

This feature is supported by the ListProvider class, and the chart's DataSource property, as follows:


int[] valArray = {12, 15, 10, 7, 5};
ListProvider lstProvider = new ListProvider(valArray);
chart1.setDataSource(lstProvider);

If you want to load data from more than one array, you can use the add method shown in the following example:


int[] series1 = {12, 15, 10};
int[] series2 = {20, 25, 7};
string[] labels = {"Yes", "No", "Don't know"};

ListProvider lstProvider = new ListProvider();
lstProvider.add(series1);
lstProvider.add(series2);
lstProvider.add(labels);

chart1.setDataSource(lstProvider);

Please note that you can pass arrays filled with Numerical Data and String or Dates that will be taken as legends in the chart. In this particular sample there are 3 arrays, two containing numerical data to be contained in the chart and the other containing legends for each point in the nValues array. This means, there's no limitation on the number of arrays you can pass using this technique.

Important: you cannot pass multi-dimensional arrays to Chart FX for Java. This means, if you create a matrix or a multi-dimensional array as nData(10,10), Chart FX for Java will not know how to process this information. An error will occur.

Using the DataType property

The DataType property is an array property that indicates the type of every position and how it should be extracted from the Array or Collection and used in the chart. For example, with two arrays:


int[] year = {1999,2000,2001};
double[] sales = {100000, 125000, 150000};

Chart FX for Java will consider the year array as another series since it is a numeric field. Instead, we want this field to be used as a value for the X-axis. We can easily override the Chart FX default behavior by filling the DataType property as follows:


chart1.setDataType(0,DataType.XValue);
chart1.setDataType(1,DataType.Value);