ComboBox - JavaFX

A control related to the list view is the combo box, which is implemented in JavaFX by the ComboBox class.

ComboBox

A control related to the list
view is the combo box, which is implemented in JavaFX by the ComboBox class. A combo box displays
one selection, but it will also display a drop-downlist that allows the user to select a different item. You can also
allow the user to edit a selection. ComboBox
inherits ComboBoxBase, which
provides much of its functionality. Unlike the ListView, which can allow multiple selections, ComboBox is designed for single-selection.

ComboBox is a generic class that is declared like this:class ComboBox<T>

Here, T specifies the type of entries. Often, these are entries of type String, but other types are also
allowed.

ComboBox defines two constructors. The first is the default constructor,
which createsan empty ComboBox. The second lets you specify
the list of entries. It is shown here:

ComboBox(ObservableList<T>
list)

In this case, list specifies a list of the items that
will be displayed. It is an object of type ObservableList,
which defines a list of observable objects. As explained in the previoussection, ObservableList inherits java.util.List.
As also previously explained, an easy way to create an ObservableList is to use the factory method observableArrayList( ), which is a static method defined by the FXCollections class.

A ComboBox generates an action event when its selection changes. It
will also generate a change event. Alternatively, it is also possible to ignore
events and simply obtain the current selection when needed.

You can obtain the current
selection by calling getValue( ),
shown here: final T getValue( )

If the value of a combo box
has not yet been set (by the user or under program control), then getValue( ) will return null. To set the value of a ComboBox under program control, call setValue( ):

final void setValue(T newVal)

Here, newVal becomes the new value.

The following program
demonstrates a combo box by reworking the previous list view example. It
handles the action event generated by the combo box.

As mentioned, ComboBox can be configured to allow the
user to edit a selection. Assuming that it contains only entries of type String, it is easy to enable editing
capabilities. Simply call setEditable( ),
shown here:

final void
setEditable(boolean enable)

If enable is true, editing
is enabled. Otherwise, it is disabled. To see the effects of editing, add this
line to the preceding program:

cbTransport.setEditable(true);

After making this addition,
you will be able to edit the selection.

ComboBox supports many additional features and functionality beyond those
mentionedhere. You might find it
interesting to explore further. Also, an alternative to a combo box in some
cases is the ChoiceBox control. You
will find it easy to use because it is has similarities to both ListView and ComboBox.