A combo box is a combination of a list component and text field component. It can consist of more than one item, however, displays only one item at any point of time. It also allows user to type their selection. Unlike list component, combo box allows user to select only one item at a time. A combo box is an object of JComboBox class.
Some of the constructors defined by JComboBox class are as follows.
JComboBox ()
JComboBox(Object combodata[])
where,
combodata represents the array of Object type that displays the elements
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/*<APPLET CODE = ComboBoxEventsInJavaAppletSwing.class WIDTH = 320 HEIGHT = 220 ></APPLET>*/
public class ComboBoxEventsInJavaAppletSwing extends JApplet implements ItemListener
{
JComboBox CmbBx = new JComboBox();
String OutStrng = " ";
public void init()
{
Container cntnr = getContentPane();
CmbBx.addItem("First Item");
CmbBx.addItem("Second Item");
CmbBx.addItem("Third Item");
CmbBx.addItem("Fourth Item");
CmbBx.addItem("Fifth Item");
cntnr.setLayout(new FlowLayout());
cntnr.add(CmbBx);
CmbBx.addItemListener(this);
}
public void itemStateChanged(ItemEvent e1)
{
if(e1.getStateChange() == ItemEvent.SELECTED)
OutStrng += "Selected: " + (String)e1.getItem();
else
OutStrng += "DeSelected: " + (String)e1.getItem();
showStatus(OutStrng);
}
}