Handling Selections

The JList class in Swing depends on a second model, this one to monitor the elements that have been selected by the user. As with the list data model, the programmer is given a wide latitude of control when dealing with selections. Swing uses a simple interface for models that handle list selections—ListSelection-Model — and also provides a default implementation—DefaultListSelection-Model.

The ListSelectionModel Interface

The ListSelectionModel interface outlines the methods necessary for managing list selections. Selections are represented by a series of ranges, where each range is defined by its endpoints. For example, if the elements “One,” “Two,” “Three,” “Six,” “Seven,” and “Nine” were selected in the opening example of the chapter, the list selection model would contain three entries that specified the ranges {1,3} and {6,7} and {9,9}. All selection range endpoints are zero-based. If only one element is present in a range, such as with “Nine,” both endpoints are identical.


Table 7.5 shows the properties of the ListSelectionModel interface. The first four properties of the list selection model can be used to retrieve various indices in the list that are currently selected. The anchorSelectionIndex and leadSelectionIndex properties represent the anchor and lead indices of the most recent range of selections. The maxSelectionIndex and minSelectionIndex properties return the largest and smallest selected index in the entire list, respectively. ...

Get Java Swing now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.