JList and ArrayList update

≡放荡痞女 提交于 2019-12-01 12:37:44

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);
}

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(); }
}

You need to use a ListModel to control adding and removing items from a JList. The tutorial is very useful: 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!