Take only some value from JavaFX ObservableList


Question

I need to build a

LineChart<Number,Number>

I had the data stored in

ObservableList<MyData>

MyData had 4 variable, all of it are int. Let just say the variable in MyData are: No1, No2, No3, No4.

Next, I need to build

LineChart<Number,Number>

and I need only No1 and No2 variable, but I don't know how to take that value from ObservableList, Now I just use XYChart.Data to add new data to XYChart.Series of my LineChart<Number,Number> like this:

private static XYChart.Series dataLineChart = new XYChart.Series();
public static void updateDataChart(){
    dataLineChart.getData().addAll(
                new XYChart.Data(3,15),
                new XYChart.Data(7,20)
            );
}

If only I can take the value from ObservableList I can just simply use :

private static XYChart.Series dataLineChart = new XYChart.Series();
public static void updateDataChart(){
    dataLineChart.getData().addAll(
                myObservableList
            );
}

Can someone help me with this problem ?

1
2
4/28/2013 11:06:19 AM

Accepted Answer

You need to create a new list anyway. It's not a problem, it's fast and only a bit of new memory will be used (only for handlers, not for objects):

If you know positions of required items you can use List#subList() method.

private static XYChart.Series dataLineChart = new XYChart.Series();
public static void updateDataChart(){
    dataLineChart.getData().addAll(
            myObservableList.subList(0,2);
    );
}

If items are not consequent, you may to create new list in one line:

ObservableList<String> sublist = FXCollections.observableArrayList( 
                     myObservableList.get(3), myObservableList.get(5) );

Also you may save on new list if you use your condition to filter old list into new directly in update method:

public static void updateDataChart(){
    for (MyData data : myObservableList) {
        if ( data.isLucky() ) // or whatever is your condition
            dataLineChart.getData().add(data);
    }
}
4
4/28/2013 5:57:52 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon