Java Reference
In-Depth Information
Finally, itemStateChanged( ) checks the selected state of each check box, building
a string that contains the names of those that are selected. It displays this string in the
jlabSelected label.
Work with JList
The last component that we will examine is JList . This is Swing's basic list class. It sup-
ports the selection of one or more items from a list. Although often the list consists of
strings, it is possible to create a list of just about any object that can be displayed. JList is
so widely used in Java that it is highly unlikely that you have not seen one before.
In the past, the items in a JList were represented as Object references. However, begin-
ning with JDK 7, JList was made generic, and it is now declared like this:
class JList<E>
Here, E represents the type of the items in the list. As a result, JList is now type-safe.
JList provides several constructors. The one used here is
JList(E[ ] items )
This creates a JList that contains the items in the array specified by items .
Although a JList will work properly by itself, most of the time you will wrap a JList
inside a JScrollPane , which is a container that automatically provides scrolling for its con-
tents. Here is the constructor that we will use:
JScrollPane(Component comp )
Here, comp specifies the component to be scrolled, which in this case will be a JList . When
you wrap a JList in a JScrollPane , long lists will automatically be scrollable. This sim-
plifies GUI design. It also makes it easy to change the number of entries in a list without
having to change the size of the JList component.
A JList generates a ListSelectionEvent when the user makes or changes a selection.
This event is also generated when the user deselects an item. It is handled by implementing
ListSelectionListener , which is packaged in javax.swing.event . This listener specifies
only one method, called valueChanged( ) , which is shown here:
void valueChanged(ListSelectionEvent le )
Here, le is a reference to the object that generated the event. Although ListSelectionEvent
does provide some methods of its own, often you will interrogate the JList object itself to
determine what has occurred. ListSelectionEvent is also packaged in javax.swing.event .
Search WWH ::




Custom Search