Delete selected item from JList

為{幸葍}努か 提交于 2019-11-28 11:02:06

As @Andreas_D said, the data centered, more abstract ListModel is the solution. This can be a DefaultListModel. You should explicitly set the model in the JList. So (thanks to comment by @kleopatra):

DefaultListModel model = (DefaultListModel) jlist.getModel();
int selectedIndex = jlist.getSelectedIndex();
if (selectedIndex != -1) {
    model.remove(selectedIndex);
}

There are several remove... methods in DefaultListModel. By the way, this is a good question, as there is no immediate solution in the API (ListModel).

The JList component is backed by a list model. So the only recommended way to remove an item from the list view is to delete it from the model (and refresh the view).

Once you delete the element from the model it will also be removed from the list. You can refer this JList article for more information. As the list is backed by a model if you do any operation on the model it will also reflect on the list. you just need to refresh the view.

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