Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Delete all elements in a JListBox except for the one selected

 
Jahed Hossain
Greenhorn
Posts: 11
Firefox Browser Linux Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a window with a JListBox and a button which deletes all the elements of the list except the element that is currently selected on the JListBox.

So, this is the code I've written at an unsuccessful attempt:



I'm actually just confused of what to do in order to make this happen, I'm trying anythin.

The strange thing is that there is always going to be an ArrayIndexOutOfBoundsException and after that listBox's Model gets modified without me trying to change it, I've only tried to changed defaultListModel.
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try iterating backwards, starting at defaultListModel.getSize() and continuing as long as i >= 0. The thing is, if you remove the element at index X, then the element previously at index X + 1 gets placed at index X. The loop doesn't know about that though. By iterating backwards, you will shift elements back, but you've already encountered those elements and will no longer examine them.
 
Tony Docherty
Bartender
Posts: 2952
59
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or you could just get the selected item, use the model's clear() method to remove all the items from the list and then put the selected item back into the list.
 
Jahed Hossain
Greenhorn
Posts: 11
Firefox Browser Linux Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tony Docherty wrote:Or you could just get the selected item, use the model's clear() method to remove all the items from the list and then put the selected item back into the list.


Yeah, that's what I thought of before, but I remembered that I also have to delete files based on the names on the listBox, so that wouldn't totally help
 
Darryl Burke
Bartender
Posts: 5125
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's a JListBox?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic