简体   繁体   English

从JList中删除所选项目

[英]Delete selected item from JList

Can anyone tell me a short way to delete the selected items from my JList ? 任何人都可以告诉我从我的JList删除所选项目的简短方法吗?

I searched on google and here, but I found very many ways. 我搜索谷歌和这里,但我找到了很多方法。 Which way should I use? 我应该使用哪种方式?

As @Andreas_D said, the data centered, more abstract ListModel is the solution. 正如@Andreas_D所说,数据居中,更抽象的ListModel就是解决方案。 This can be a DefaultListModel . 这可以是DefaultListModel You should explicitly set the model in the JList. 您应该在JList中显式设置模型。 So (thanks to comment by @kleopatra): 所以(感谢@kleopatra的评论):

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

There are several remove... methods in DefaultListModel. DefaultListModel中有几个remove...方法。 By the way, this is a good question, as there is no immediate solution in the API (ListModel). 顺便说一句,这是一个很好的问题,因为API(ListModel)中没有直接的解决方案。

The JList component is backed by a list model. JList组件由列表模型支持。 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. 您可以参考此JList文章以获取更多信息。 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. 你只需要刷新视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM