By Tony Bevis on Friday, 20 October 2023
Category: Java

Java programming course: 14.11 JList

JList

The JList class displays a selection of a number of items, from which one or more may be selected. It is possible to pass an array of objects into the JList constructor, and it is usual to nest the list inside a JScrollPane:  

The above should result in the following:

By default, the user is allowed to select multiple items in the list. If you want to ensure that only one item can be selected at a time use the setSelectionMode() method:

As you learned in Section 6, arrays are of a fixed size and therefore lack the flexibility of being able to dynamically contract or expand with new or removed items. To obtain the additional flexibility you can assign a ListModel object to your JList in order to provide the items to appear in the list[1]. ListModel is an interface which you can implement to provide the list data, although typically an easier way is to extend the Java supplied DefaultListModel class (which itself implements ListModel). In DemoUI define an inner class called ColourListModel as follows:

[1] When you passed an array into the JList constructor it used a ListModel behind the scenes.

You can now instantiate a ColourListModel object and pass it as the argument to the JList constructor:

If you need to programmatically select one of the items in the list as a default you can use the setSelectedIndex() method:

To obtain which item has been selected you can use either the getSelectedIndex() or getSelectedValue() methods:

Next lesson: 14.12 JTable 

Related Posts

Leave Comments