The JComboBox Class

JComboBox combines a button or editable field and a drop-down list. It is very similar to the AWT Choice component and even implements the ItemSelectable interface for backward compatibility. By default, the JComboBox component provides a single text edit field adjacent to a small button with a downward arrow. When the button is pressed, a pop-up list of choices is displayed, one of which can be selected by the user. If a selection is made, the choice is copied into the edit field, and the pop up disappears. If there was a previous selection, it is erased. You can also remove the pop up by pressing Tab (or Esc, depending on the L&F) while the combo box has the focus. Figure 7-11 shows combo boxes as they appear in four different L&Fs.

The JComboBox component in four L&Fs

Figure 7-11. The JComboBox component in four L&Fs

The text field in the JComboBox component can be either editable or not editable. This state is controlled by the editable property. If the text field is editable, the user is allowed to type information into the text box (which may not correspond to anything in the list), as well as make selections from the list. If the component is not editable, the user can only make selections from the list.

Unless you specify a set of objects in the constructor, the combo box comes up empty. You can use the addItem( ) method to add objects to the combo box list. Conversely, the removeItem( ...

Get Java Swing, 2nd Edition 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.