Java - Updating JList after changing an object

耗尽温柔 提交于 2019-12-01 16:28:41

You need to call fireContentsChanged() on the ListModel.

Instead of setModel(), update your existing model using one of the DefaultListModel methods such as setElementAt(), which will fireContentsChanged() for you.

You need to call DefaultListModel.fireContentsChanged(). But since this method is protected (I really wonder why), you can't do that directly. Instead, make a small subclass:

class MinoListModel<T> extends DefaultListModel<T>
{
    public void update(int index)
    {
        fireContentsChanged(this, index, index);
    }
}

Use it as your list model:

m = new MinoListModel<>();
jl = new JList(m);

After updating a user number, update the corresponding entry: m.update(theIndex);

Alternatively, if you don't want a subclass, you can just replace the JList element after the user number changed: m.setElementAt(theSameElement, theIndex);. Though this is somewhat cumbersome and having a subclass seems the cleaner approach.

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