JList 和 ArrayList 更新 [英] JList and ArrayList update
问题描述
我想举例说明当我从 ArrayList 添加或删除元素时如何更新 JList.
I would like to have example on how to update a JList when I add or remove elements from a ArrayList.
ArrayList 是 Model 类的一部分.Model 类通过其构造函数传递给视图(它是一个包含多个摆动组件的 JPanel,以及我要更新的 JList).模型类也被注入到读取从服务器接收的值的类中.当我从服务器收到数据时,我通过执行 model.getArrayList().add(data) 将其中一些添加到我的 arrayList 中.当我向 arrayList 添加数据时,我想在我的视图中更新 JList.我想获得有关如何将我的 ArrayList 与我的 JList 链接的帮助.
The ArrayList is part of Model class. The Model class is passed to the view (which is a JPanel containing several swing components, and the JList I want to update) via its constructor. The model class is also injected in a class that reads values received from the server. When i received data from the server I add some of them to my arrayList by doing model.getArrayList().add(data). When I add data to the arrayList i would like to update the JList in my view. I would like to have help on how to link my ArrayList with my JList.
推荐答案
如果您创建自己的 ListModel
,您应该扩展 AbstractListModel
并且在实现您的 addElement
方法时,您需要调用fire 方法(用于通知用户界面进行更新),例如:
If you create your own ListModel
you should extend AbstractListModel
and when implementing your addElement
method, you need to call a fire-method (for notifying the user interface for the update), like:
public void addElement(MyObject obj) {
myArrayList.add(obj);
fireIntervalAdded(this, myArrayList.size()-1, myArrayList.size()-1);
}
您的自定义 ListModel 应如下所示:
You custom ListModel should look something like this:
public class MyListModel extends AbstractListModel {
private final ArrayList<MyObject> myArrayList = new ArrayList<MyObject>();
public void addElement(MyObject obj) {
myArrayList.add(obj);
fireIntervalAdded(this, myArrayList.size()-1, myArrayList.size()-1);
}
@Override
public Object getElementAt(int index) { return myArrayList.get(index); }
@Override
public int getSize() { return myArrayList.size(); }
}
这篇关于JList 和 ArrayList 更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!