O'Reilly logo

Java Swing by Dave Wood, Marc Loy, Robert Eckstein

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required