JComboBox Example Java Swing


A JComboBox (sometimes called a drop-down list) provides a list of items from which the user can make a selection.

Combo boxes are implemented with class JComboBox, which inherits from class JComponent. JComboBox generates ItemEvent like JCheckBox and JRadioButton. Its counterpart in AWT is Choice.

In the following JComboBox example a combo box and text field are added to JFrame. User’s selection of item in the combo box is displayed in the text field. To catch the events generated by items of combo box, a separate helper class is created (generally we write GUI and event handling code in a single program). Always in projects, event handling mechanism is written separately in a class as in the following program. Observe that the text field is passed as a parameter to the helper class. This is the way to create a link between the helper class and the main class components.

import javax.swing.*;     
import java.awt.* ;   
import java.awt.event.* ;
public class ComboBoxDemo extends JFrame   
{
  JComboBox cbox;
  JTextField jfield;                                     // a text field to display your selection of combo box
  public ComboBoxDemo()   
  {
    Container c = getContentPane();
    c.setLayout(new FlowLayout());
    String sarray[] = {"Idly", "Dosa", "Vada"};
    jfield = new JTextField ("Displays the selection", 20);
    cbox = new JComboBox(sarray);                         // a constructor which accepts an array of string items unlike AWT Choice component 
    cbox.addItem("Puri");                                 // items to combo box can be added individually also
    cbox.addItem("Utappa");
    cbox.addItem("Coffee");

    HelperListener hl = new HelperListener(jfield);       // item is event  in a separate class
    cbox.addItemListener(hl); 

    c.add(cbox);    c.add(jfield) ;
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       // to close the JFrame window
  }
  public static void main(String args[])  					
  {
    JFrame f = new ComboBoxDemo();
    f.setSize(300, 150);
    f.setVisible( true ) ;
  }
}
class HelperListener implements ItemListener  
{
  JTextField jf ;
  HelperListener(JTextField j) 
  {
    jf = j ; 
  }
  public void itemStateChanged(ItemEvent e)  
  {
    String str = (String) e.getItem();
    jf.setText("You selected " + str);       
  }	
}


JComboBox
Output screen of JComboBox Example