[英]JList and ArrayList update
I would like to have example on how to update a JList when I add or remove elements from a ArrayList. 我想举一个有关如何在ArrayList中添加或删除元素时更新JList的示例。
The ArrayList is part of Model class. ArrayList是Model类的一部分。 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. Model类通过其构造函数传递给视图(这是一个包含多个swing组件的JPanel,以及我要更新的JList)。 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). 当我从服务器接收数据时,通过执行model.getArrayList()。add(data)将其中一些添加到我的arrayList中。 When I add data to the arrayList i would like to update the JList in my view. 当我向arrayList添加数据时,我想更新视图中的JList。 I would like to have help on how to link my ArrayList with my JList. 我想获得有关如何将ArrayList与JList链接的帮助。
You need to use a ListModel to control adding and removing items from a JList. 您需要使用ListModel来控制从JList添加和删除项目。 The tutorial is very useful: http://download.oracle.com/javase/tutorial/uiswing/components/list.html 该教程非常有用: http : //download.oracle.com/javase/tutorial/uiswing/components/list.html
Here is some example code from the tutorial: 这是本教程中的一些示例代码:
listModel = new DefaultListModel();
listModel.addElement("Jane Doe");
listModel.insertElementAt(employeeName.getText(), index);
int index = list.getSelectedIndex();
listModel.remove(index);
If you have an arraylist you could build your own List Model around it. 如果您有一个arraylist,则可以围绕它构建自己的List Model 。
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: 如果创建自己的ListModel
,则应扩展AbstractListModel
并在实现addElement
方法时,需要调用fire方法(用于通知更新的用户界面),例如:
public void addElement(MyObject obj) {
myArrayList.add(obj);
fireIntervalAdded(this, myArrayList.size()-1, myArrayList.size()-1);
}
You custom ListModel should look something like this: 您自定义的ListModel应该看起来像这样:
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(); }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.