3

对于学校作业,我们正在使用 JavaFX 中的 ObservableList 对象(对吗?)。我已经为此工作了一天多,但无法弄清楚。老师只告诉我们“谷歌”所以这也无济于事..

基本上,我们正在开发一个基本的管理应用程序来跟踪人们及其家人。人们是一个家庭的成员,一个家庭可以有多个成员。

当一个人或一个家庭被添加时,他们被添加到一个 observableList 中,然后应该更新一个 ArrayList(这样数据可以被序列化)和一个 GUI 元素。这就是问题所在。

我们目前有以下实现:

private List<Persoon> personen;
private List<Gezin> gezinnen;
this.personen = new ArrayList<Persoon>();
this.gezinnen = new ArrayList<Gezin>();

private transient ObservableList<Persoon> observablePersonen;
private transient ObservableList<Gezin> observableGezinnen;
observablePersonen = FXCollections.observableArrayList(personen);
observableGezinnen = FXCollections.observableArrayList(gezinnen);

然后当添加一个项目时,我们执行以下操作:

Persoon p = new Persoon();
observablePersonen.add(p);
observablePersonen.notifyAll();

在此之后,当我们检查“personen”列表时,添加的对象不存在:(

我们是否遗漏了一些明显的东西?

4

3 回答 3

12

您需要使用FXCollections.observableList而不是FXCollections.observableArrayList.

根据以下文档observableList

构造一个由指定列表支持的 ObservableList。

因此,对可观察列表的任何修改都将报告给支持列表。但是,在以下情况下observableArrayList

创建一个新的 observable 数组列表并向其中添加集合 col 的内容。

所以这个列表不受给定列表的支持,它只是作为一个初始集合。

作为旁注,您不应该调用notifyAll():此方法与 JavaFX 无关,它与唤醒等待该对象的线程有关。

于 2015-10-02T13:13:28.637 回答
0

如何将 anArrayList同步到ObservableList.

public class Main {

    public static ArrayList<Double> arrayList = new ArrayList();
    public static ObservableList<Double> observableList = FXCollections.observableArrayList();

    public static void main(String[] args) {

        // add a listener to the ObservableList
        observableList.addListener(new ListChangeListener<Double>() {
            @Override
            public void onChanged(Change<? extends Double> c) {
                // c represents the changed element
                System.out.println("Added " + c + " to the Observablelist");
                // we add the last element added to the observable list to the arraylist
                arrayList.add(observableList.get(observableList.size()-1));
                System.out.println("Added " + arrayList.get(arrayList.size()-1) + " to the Arraylist");
            }
        });

        observableList.add(5.0);
        observableList.add(7.0);
    }
}

输出:

Added { [5.0] added at 0 } to the Observablelist
Added 5.0 to the Arraylist
Added { [7.0] added at 1 } to the Observablelist
Added 7.0 to the Arraylist
于 2015-10-02T13:21:34.517 回答
0

一旦尝试此代码,它对我的​​工作:

old_list是类型ObservableArrayList<CustomType>

//update new changes
old_list.map{
//do your changes
}
val templist=old_list.clone() // make a clone
old_list.clear() //clear old list
old_list.addAll(templist as ObservableArrayList<CustomType>)
于 2020-06-24T17:22:31.277 回答