Adding and Removing an Item in a JList Component

The default model for a list does not allow the addition and removal of items. The list must be created with a DefaultListModel.
// Create a list that allows adds and removes DefaultListModel model = new DefaultListModel(); JList list = new JList(model); // Initialize the list with items String[] items = {"A", "B", "C", "D"}; for (int i=0; i<items.length; i++) { model.add(i, items[i]); } // Append an item int pos = list.getModel().getSize(); model.add(pos, "E"); // Insert an item at the beginning pos = 0; model.add(pos, "a");
This method replaces an item:
// Replace the 2nd item pos = 1; model.set(pos, "b");
These methods are used to remove items:
// Remove the first item pos = 0; model.remove(pos); // Remove the last item pos = model.getSize()-1; if (pos >= 0) { model.remove(pos); } // Remove all items model.clear();

Comments

7 Mar 2010 - 10:31pm by Chi kheang (not verified)

i having problem when i remove all item in Jlist when ever i click on JList.... so how can i do ?

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.