java 仅从 JavaFX ObservableList 中获取一些值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16262065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:26:39  来源:igfitidea点击:

Take only some value from JavaFX ObservableList

javachartsjavafx-2javafx

提问by Alfat Saputra Harun

I need to build a

我需要建立一个

LineChart<Number,Number>

I had the data stored in

我将数据存储在

ObservableList<MyData>

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

MyData有 4 个变量,它们都是int. 假设变量MyData是: No1, No2, No3, No4

Next, I need to build

接下来,我需要构建

LineChart<Number,Number>

and I need only No1and No2variable, but I don't know how to take that value from ObservableList, Now I just use XYChart.Datato add new data to XYChart.Seriesof my LineChart<Number,Number>like this:

而我只需要No1No2变化,但我不知道如何把从该值ObservableList,现在我只是用XYChart.Data新的数据添加到XYChart.Series我的LineChart<Number,Number>是这样的:

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 ObservableListI can just simply use :

如果我能从中获取价值,ObservableList我就可以简单地使用:

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

Can someone help me with this problem ?

有人可以帮我解决这个问题吗?

回答by Sergey Grinev

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.

如果您知道所需物品的位置,则可以使用List#subList()方法。

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);
    }
}