Java Reference
In-Depth Information
Figure 13-16. Listening for JComboBox selections
Listening to JComboBox Events with a ListDataListener
You can attach a ListDataListener to the data model of the JComboBox . This listener would then
be notified when the selected element of the model changes. Unfortunately, the listener would
also be notified of other data model changes. In other words, using a ListDataListener to find
out when an element of a JComboBox is selected is not a recommended option.
Note Mouse movement and cursor movement events within a JComboBox don't change the selected
entry; mouse release events do change the selected entry. Any registered listeners would be notified when a
selected mouse button is released over an element within the JComboBox pop-up list.
Editing JComboBox Elements
You may want to use a combo box like a text field in which you list the most likely text input
from the user, but also allow the user to enter something else. By enabling the editable property
of the JComboBox , you've added this capability. To demonstrate, Figure 13-17 shows an editable
JComboBox . The window also contains a text area that reports the current selected item and
index. Even if you manually enter one of the choices within the JComboBox , getSelectedIndex()
will report the proper position. Remember that if you enter a value that's not present,
getSelectedIndex() returns -1.
Figure 13-17. Using an editable JComboBox
The source for the example in Figure 13-17 is shown in Listing 13-13.
 
Search WWH ::




Custom Search