Java Reference
In-Depth Information
There are two basic ways in which you can use a ListView . First, you can ignore events
generated by the list and simply obtain the selection in the list when your program needs it.
Second, you can monitor the list for changes by registering a change listener. This lets you
respond each time the user changes a selection in the list. This is the approach used here.
A change listener is supported by the ChangeListener interface, which is packaged
in javafx.beans.value . The ChangeListener interface defines only one method, called
changed( ) . It is shown here:
void changed(ObservableValue<? extends T> changed , T oldVal , T newVal )
In this case, changed is the instance of ObservableValue<T> which encapsulates an object
that can be watched for changes. The oldVal and newVal parameters pass the previous
value and the new value, respectively. Thus, in this case, newVal holds a reference to the
list item that has just been selected.
To listen for change events, you must first obtain the selection model used by the
ListView . This is done by calling getSelectionModel( ) on the list. It is shown here:
final MultipleSelectionModel<T> getSelectionModel( )
It returns a reference to the model. MulitpleSelectionModel is a class that defines the mod-
el used for multiple selections, and it inherits SelectionModel . However, multiple selec-
tions are allowed in a ListView only if multiple-selection mode is turned on.
Using the model returned by getSelectionModel( ) , you will obtain a reference to the
selected item property that defines what takes place when an element in the list is selected.
This is done by calling selectedItemProperty( ) , shown next:
final ReadOnlyObjectProperty<T> selectedItemProperty( )
You will add the change listener to this property by using the addListener( ) method on
the returned property. The addListener( ) method is shown here:
void addListener(ChangeListener<? super T> listener )
In this case, T specifies the type of the property.
The following example puts the preceding discussion into action. It creates a list view
that displays a list of computer types, allowing the user to select one. When one is chosen,
the selection is displayed.
Search WWH ::




Custom Search