简体   繁体   English

从JList中删除多个选择

[英]removing multiple selections from JList

I have a JList with some elements where multiple selection is allowed. 我有一个JList,其中包含允许多个选择的元素。 Before these elements are added to the JList, some information about them is being stored in a static HashMap in a separate class. 在将这些元素添加到JList之前,有关它们的一些信息存储在单独的类中的静态HashMap中。 When more than 1 items are selected and the 'Remove selected' button is pressed, I am trying to remove the selected items (which works fine) and also delete their records from the HashMap. 当选择了多个项目并按下“删除选中”按钮时,我试图删除所选项目(工作正常)并从HashMap中删除它们的记录。 For some reason though, if I select more than 1 elements, only the first record in the HashMap is removed. 但是出于某种原因,如果我选择多个元素,则只删除HashMap中的第一个记录。 I don't understand how this works for the JList but doesn't work for the HashMap. 我不明白它如何适用于JList,但不适用于HashMap。 My code below: 我的代码如下:

remove.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                    Object[] selectedElementsValues = jList.getSelectedValues();

                    for (int i = 0; i < selectedElementsValues.length; i++) {
                        System.out.println(jList.getSelectedValue().toString());
                        System.out.println(PersonClass.map.get(jList.getSelectedValue().toString()));

PersonClass.map.remove(jList.getSelectedValue().toString());

System.out.println(PersonClass.map);

                }

It works fine if I select only one item at a time and remove it. 如果我一次只选择一个项目并将其删除,它工作正常。 But not with multiple selection. 但不是多选。 The items from the JList are removed properly, though, so I don't see why it doesn't do the same for the map. 但是,JList中的项目已被正确删除,因此我不明白为什么它对地图不会这样做。

Thx 谢谢

The problem is that the loop that removes items from the map uses jList.getSelectedValue().toString() , when the jList selection is not modified. 问题是,当jList选择时,从地图中删除项的循环使用jList.getSelectedValue().toString() You can use the selection array you obtained earlier: 您可以使用之前获得的选择数组:

for (Object o : selectedValues) {
    PersonClass.map.remove(o.toString());
}

Note that getSelectedValues() is deprecated, and you should use getSelectedValuesList() instead. 需要注意的是getSelectedValues()已被弃用,你应该使用getSelectedValuesList()来代替。

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

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