Menu Bar Selection Models

In all GUI environments, menu components only allow one selection to be made at a time. Swing is no exception. Swing provides a data model that menubars and menus can use to emulate this behavior: the SingleSelectionModel.

The SingleSelectionModel Interface

Objects implementing the SingleSelectionModel interface do exactly what the name suggests: they maintain an array of possible selections, and allow one element in the array to be chosen at a time. The model holds the index of the selected element. If a new element is chosen, the model resets the index representing the chosen element and fires a ChangeEvent to each of the registered listeners.

Properties

Objects implementing the SingleSelectionModel interface contain the properties shown in Table 14.1. The selectedIndex property is an integer index that represents the currently selected item. The selected property is a boolean that tells if there is a selection.

Table 14-1. SingleSelectionModel Properties

Property

Data Type

get

is

set

bound

Default Value

selected

boolean

 

•

   

selectedIndex

int

•

 

•

  

Events

Objects implementing the SingleSelectionModel interface must fire a ChangeEvent (not a PropertyChangeEvent) when the object modifies its selectedIndex property, i.e., when the selection has changed. The interface contains the standard addChangeListener() and removeChangeListener() methods for maintaining a list of ChangeEvent listeners.

void addChangeListener(ChangeListener ...

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.