Removing items from JList

前端 未结 6 1072
野性不改
野性不改 2021-01-01 05:26

I\'ve got a simple Jlist with data from List, Now I want to remove selected item from Jlist. Here is the code:

final DefaultListMo         


        
相关标签:
6条回答
  • 2021-01-01 05:32
    DefaultListModel model=new DefaultListModel();
        model.clear();
     jList1.setModel(model);
    

    if you want delete all item

    0 讨论(0)
  • 2021-01-01 05:47

    According to the javadoc, using remove() instead of removeElementAt() is recommended, so :

    public void actionPerformed(ActionEvent arg0) {
        int index = list.getSelectedIndex();
        if (index != -1) {
            model.remove(index);
    }
    
    0 讨论(0)
  • 2021-01-01 05:47

    According to the Javadoc for getSelectedIndex():

    Returns the smallest selected cell index; the selection when only a single item is selected in the list. When multiple items are selected, it is simply the smallest selected index. Returns -1 if there is no selection

    The reason that you're experiencing the error is because for some reason, no items are selected from your list and as such -1 is returned by this method. When you call removeElementAt() and pass it -1 as a parameter value, it would throw you the exception.

    What you need to do is as follows:

    public void actionPerformed(ActionEvent arg0) {
        int index = list.getSelectedIndex();
        if(index >= 0){ //Remove only if a particular item is selected
            model.removeElementAt(index);
        }
    }
    
    0 讨论(0)
  • 2021-01-01 05:51

    Assuming your index is non-negative (as mentioned by others), see if this works (in your listener):

    ((DefaultListModel) jList.getModel()).remove(index);
    

    If so, then you're using using a stale model.

    0 讨论(0)
  • 2021-01-01 05:53
    int selectedIndex = yourJLIST.getSelectedIndex();
        String [] ListData = new String[yourJLIST.getModel().getSize()];
        for (int i = 0; i < ListData.length; i++) {
            if(i == selectedIndex){
                
            }else{
                ListData[i] = yourJLIST.getModel().getElementAt(i);
            }
        }
        yourJLIST.setListData(ListData);
    
    0 讨论(0)
  • 2021-01-01 05:54

    The question is that you have a problem in the listener, because when the element is removed the selected value will change. This is the reason that your "valueChanged" method is trying to get the selectedValue in a wrong position. I can't see your method valueChanged, but I think this is the reason.

    0 讨论(0)
提交回复
热议问题