JList Basics

 

Creating, Adding and Deleting Elements from a JList

 

JLists may be initialized with a set of strings using the constructor

 

public JList(Object[] listData)

for example, you can supply an array of Strings:

String[] ar = {"one", "two", "three"};
JList list = new JList(ar);

However, JList has no method to add or delete items once it is initialized.  Instead, if you need to do this, you must use the ListModel class with a JList.  Think of the ListModel as the object which holds the items and the JList as the displayer.

 

1. Declare an instance of DefaultListModel:

 

DefaultListModel listModel;

 

2. Create it:

 

listModel = new DefaultListModel();

 

3. Populate it (now or later):

 

listModel.addElement(“item 1”);

listModel.addElement(“item 2”);

etc.

 

4. Use the DefaultListModel in the constructor of a JList (instead of a String array):

 

JList list = new JList(listModel);

 

5. Now to add additional elements at any time during execution, use addElement() again:

 

listModel.addElement(“new item”);

 

and it will show up in the JList. (You can also use add(int index) where you specify the 0-based position of the element to be added.)

 

6. To delete an item, just call

 

listModel.remove(n);

 

where n is the 0-based index of the item to remove.  It will disappear.

 

7. To delete all the items, call

listModel.clear();

Other Notes:

To highlight (i.e. select) an item in a JList use

list.setSelectedItem(n); 

To return the currently selected String in a JList, use

s = (String) list.getSelectedValue();

(This method is defined to return Object because JList actually can contain object types other than Strings (for example, small images know as Icons.  Therefore you must typecast the returned value.)