wood burning stoves 2.0*
The moose likes Java in General and the fly likes Delete all elements in a JListBox except for the one selected Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Delete all elements in a JListBox except for the one selected" Watch "Delete all elements in a JListBox except for the one selected" New topic
Author

Delete all elements in a JListBox except for the one selected

Jahed Hossain
Greenhorn

Joined: Nov 30, 2012
Posts: 11

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

Joined: Oct 27, 2005
Posts: 19697
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Tony Docherty
Bartender

Joined: Aug 07, 2007
Posts: 2300
    
  49
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

Joined: Nov 30, 2012
Posts: 11

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

Joined: May 03, 2008
Posts: 4571
    
    5

What's a JListBox?


luck, db
There are no new questions, but there may be new answers.
 
GeeCON Prague 2014
 
subject: Delete all elements in a JListBox except for the one selected