that lets the user enter a selection into the text field. The JComboBox constructor used by
the example is shown here:
JComboBox(Object[ ] items)
Here, items is an array that initializes the combo box. Other constructors are available.
JComboBox uses the ComboBoxModel. Mutable combo boxes (those whose entries can
be changed) use the MutableComboBoxModel.
In addition to passing an array of items to be displayed in the drop-down list, items can
be dynamically added to the list of choices via the addItem( ) method, shown here:
void addItem(Object obj)
Here, obj is the object to be added to the combo box. This method must be used only with
mutable combo boxes.
JComboBox generates an action event when the user selects an item from the list.
JComboBox also generates an item event when the state of selection changes, which occurs
when an item is selected or deselected. Thus, changing a selection means that two item
events will occur: one for the deselected item and another for the selected item. Often, it is
sufficient to simply listen for action events, but both event types are available for your use.
One way to obtain the item selected in the list is to call getSelectedItem( ) on the combo
box. It is shown here:
Object getSelectedItem( )
You will need to cast the returned value into the type of object stored in the list.
The following example demonstrates the combo box. The combo box contains entries
for "France," "Germany," "Italy," and "Japan." When a country is selected, an icon-based
label is updated to display the flag for that country. You can see how little code is required
to use this powerful component.
// Demonstrate JComboBox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JComboBoxDemo" width=300 height=100>
</applet>
*/
public class JComboBoxDemo extends JApplet {
JLabel jlab;
ImageIcon france, germany, italy, japan;
JComboBox jcb;
String flags[] = { "France", "Germany", "Italy", "Japan" };
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home