观察列表不更新ArrayList

 2023-02-16    281  

问题描述

对于学校作业,我们正在使用Javafx(对吗?)的Observablelist对象.我已经为此工作了一天,无法弄清楚.老师只告诉我们” Google It”,所以也没有帮助.

基本上,我们正在研究基本的管理申请,以跟踪人们及其家人.人们是家庭成员,一个家庭可以有多个成员.

观察列表不更新ArrayList

当添加一个人或家庭时,将它们添加到应该然后更新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’列表时,添加的对象都不存在:(

我们是否缺少明显的东西?

推荐答案

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

根据observableList的文档:

构建了由指定列表支持的观察者.

因此,可观察列表的任何修改都将报告给备用列表.但是,在observableArrayList的情况下:

创建一个新的可观察数组列表,并在其中添加了Collection col的内容.

因此,此列表不受给定列表的支持,它只是用作初始集合.

作为旁注,您不应该致电notifyAll():此方法与Javafx无关,并且与在此对象上等待的唤醒线有关.

其他推荐答案

ArrayList如何同步到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

其他推荐答案

一旦尝试此代码,它的工作量为我:

在这里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>)

以上所述是小编给大家介绍的观察列表不更新ArrayList,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对77isp云服务器技术网的支持!

原文链接:https://77isp.com/post/33834.html

=========================================

https://77isp.com/ 为 “云服务器技术网” 唯一官方服务平台,请勿相信其他任何渠道。