从JavaFX ObservableList中只取一些值 [英] Take only some value from JavaFX ObservableList
问题描述
我需要构建一个
LineChart<Number,Number>
我将数据存储在
ObservableList<MyData>
MyData
有4个变量,全部都是是 int
。假设 MyData
中的变量是: No1,No2,No3,No4
。
MyData
had 4 variable, all of it are int
. Let just say the variable in MyData
are: No1, No2, No3, No4
.
接下来,我需要构建
LineChart<Number,Number>
我只需要 No1
和 No2
变量,但我不知道如何从 ObservableList
获取该值,现在我只使用 XYChart.Data
将新数据添加到我的 LineChart< Number,Number> $ c的
XYChart.Series
$ c>像这样:
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)
);
}
如果我只能从 ObservableList <中取值/ code>我可以简单地使用:
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 ?
推荐答案
无论如何,您需要创建一个新列表。这不是问题,它很快,只会使用一些新的内存(仅适用于处理程序,不适用于对象):
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):
如果您知道所需项目的位置可以使用 List#subList()
方法。
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);
}
}
这篇关于从JavaFX ObservableList中只取一些值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!