by Dinesh Thakur Category: Swing

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);
         }
   }

Java - JComboBox Selection Change Listener Example



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles