简体   繁体   中英

Delete elements from JList

I have a JList that I am populating from a MySQL database. This works fine and I can see the results in a JScrollPane, however, when I execute the query again the results are added to to JList; so if there are 10 rows of data, it shows 20 after 2 queries, a copy of each row.

I want to delete all elements in the JList before re-querying so that it only shows what is there, not duplicate data.

I have:

    ArrayList<String> results;
    JList list;
    JScrollPane listScroller;
    ... //button event and arraylist population

    for(int i=0; i < list.getModel().getSize(); i++){
        list.remove(i)
    }
    list = new JList(results.toArray);
    listScroller.setViewportView(list);

When I debug it, even thought there are 50 elements, i, in the for loop, stops at 25 and then throws an exception saying 25 is out of bounds.

Any suggestions?

Your code is removing elements from the list (in each iteration the list's size is decremented by 1). So when you reach i==25 the list's size is 25 and when you try to remove the 25th element you are out of bounds of the list.

Try this approach:

while (list.getModel().getSize() > 0) {
    list.remove(0);
}

Edited by the OP:
The problem with list.remove(i) in your loop is that every time an element in a JList is removed the index is filled in. So if i = 0 and there are 10 elements, you remove the first and then there are only 9 elements and they take indexes 0 through 8. By the time you get to i = 5 you only have 5 elements left and 4 is the top index so you get an out of bounds exception.

Avoid this by removing the first index (0) each time.

You can do this without a while loop :

DefaultListModel listModel = (DefaultListModel) yourJList.getModel();
listModel.removeAllElements();

覆盖列表中的数据将更快。

list.setListData(new String[0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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