Header javaperspective.com
JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.20. Combo boxes

5.20. Combo boxes
Last updated: 25 January 2013.

This tutorial will show you how to use combo boxes in Java.

A combo box is a component that allows the user to select an item in a drop-down list. At startup, only one item is visible. The complete list of items is displayed when the user clicks the combo box's button. A combo box can be editable or uneditable. If a combo box is editable, the user can enter a value in its textfield. The following picture shows a frame containing an uneditable combo box that allows the user to choose from a list of movie types:


Combo box


The next sample provides the code that builds the combo box shown above. Additionally, a label is placed next to the combo box. Also, the combo box registers an action listener so that every time the user selects an item in the drop-down list, the label displays the selected item. Here is the code:

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.BevelBorder;

public final class ComboBoxes extends JFrame implements ActionListener{

   
private JComboBox<String> comboBox;
   
private JLabel label;

   
public ComboBoxes() {
         
init();
          addComponents
();

          setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
          setVisible
(true);
   
}


   
public void actionPerformed(ActionEvent e){
         
if(e.getSource().equals(comboBox)){
               
String selectedItem = (String) comboBox.getSelectedItem();
                label.setText
("Selected item : " + selectedItem);
         
}
    }


   
private void addComponents() {
         
// Create the content pane
         
JPanel contentPane = new JPanel(new FlowLayout(FlowLayout.CENTER, 25, 10));

         
// Create the array containing the items of the combo box
         
String[] items = {"Action", "History", "Sci-Fi", "War",
                     
"Horror", "Western", "Thriller", "Documentary",
                     
"Drama", "Biography", "Adventure" };

         
// Create the combo box
         
comboBox = new JComboBox<String>(items);

         
// Register an action listener
         
comboBox.addActionListener(this);

         
// Add the combo box to the content pane
         
contentPane.add(comboBox);

         
// Create the label and add it to the content pane
         
label = new JLabel("Selected item : " + comboBox.getSelectedItem());
          label.setPreferredSize
(new Dimension(200, 30));
          label.setHorizontalAlignment
(SwingConstants.CENTER);
          label.setBorder
(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
          contentPane.add
(label);

         
// Add the content pane to the JFrame
         
add(contentPane);
   
}


   
private void init() {
         
try{
               
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
         
}
         
catch(Exception e){
               
e.printStackTrace();
         
}
         
setTitle("ComboBoxes");
          setSize
(400, 200);
          setLocationRelativeTo
(null);
   
}


   
public static void main(String[] args){
         
SwingUtilities.invokeLater(new Runnable() {
               
public void run() {
                     
new ComboBoxes();
               
}
          })
;
   
}
}


Here is the result:


Combo box 2


You can make a combo box editable by invoking the method setEditable(true) provided by the class JComboBox. In that case, the user can type a value in the combo box's texfield. When the user hits enter after typing a value within the texfield, an action event is fired. The next picture shows an editable version of the combo box that I have used earlier:


Combo box 3



How to associate a combo box with CardLayout

Combo boxes are often associated with the layout manager CardLayout. As explained in the tutorial How to use CardLayout, an ordered stack of components wherein each component is identified by its name is defined in a CardLayout. Only one component is visible at a time and you can select a component by its name. A combo box can be used to determine what component from the stack should be made visible. Basically, the selected item in the combo box is the name of the component to choose from the stack.

The frame shown below reuses the combo box that you have seen in the first picture of this tutorial. The frame is laid out with BorderLayout and displays two components at the top: a label that shows Genre and the combo box. A titled JPanel laid out with CardLayout at the center will display the component chosen from the stack. The CardLayout contains a stack of JPanel objects wherein each JPanel is identified by its name. When the user selects an item in the combo box, the corresponding panel is displayed at the center of the frame. Here is what it looks like:


Combo box 4


The code follows:

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;

public final class ComboBoxes2 extends JFrame implements ActionListener{

   
private JComboBox<String> comboBox;
   
private CardLayout cardLayout;
   
private JPanel centerPanel;
   
private Font centerPanelFont;

   
public ComboBoxes2() {
         
centerPanelFont = new Font("Times New Roman", Font.PLAIN, 15);
          init
();
          addComponents
();

          setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
          setVisible
(true);
   
}


   
public void actionPerformed(ActionEvent e){
         
cardLayout.show(centerPanel, (String) comboBox.getSelectedItem());
   
}


   
private void addComponents() {
         
// Create the content pane
         
JPanel contentPane = new JPanel(new BorderLayout(0, 5));

         
// Create the array containing the items of the combo box
         
String[] items = {"Action", "History", "Sci-Fi", "War",
                     
"Horror", "Western", "Thriller", "Documentary",
                     
"Drama", "Biography", "Adventure" };

         
// Create the combo box, clear the selection and register the action listener
         
comboBox = new JComboBox<String>(items);
          comboBox.setSelectedItem
(null);
          comboBox.addActionListener
(this);

         
// Create topPanel and set its layout and border (topPanel will contain the label "Genre" and the combo box)
         
JPanel topPanel = new JPanel();
          topPanel.setLayout
(new BoxLayout(topPanel, BoxLayout.LINE_AXIS));
          topPanel.setBorder
(BorderFactory.createEmptyBorder(10, 0, 0, 0));

         
// Add a horirontal glue to topPanel
         
topPanel.add(Box.createHorizontalGlue());

         
// Add the label "Genre" to topPanel
         
JLabel genreLabel = new JLabel("Genre");
          genreLabel.setBorder
(BorderFactory.createEmptyBorder(0, 0, 0, 15));
          topPanel.add
(genreLabel);

         
// Add the combo box to topPanel
         
topPanel.add(comboBox);

         
// Add another horirontal glue to topPanel
         
topPanel.add(Box.createHorizontalGlue());

         
// Add topPanel to contentPane
         
contentPane.add(topPanel, BorderLayout.PAGE_START);

         
// Create cardLayout and centerPanel (centerPanel will display the chosen panel)
         
cardLayout = new CardLayout();
          centerPanel =
new JPanel(cardLayout);

         
// Add panels to centerPanel
         
addPanelToCenter(centerPanel, "All");
          addPanelToCenter
(centerPanel, "Action");
          addPanelToCenter
(centerPanel, "History");
          addPanelToCenter
(centerPanel, "Sci-Fi");
          addPanelToCenter
(centerPanel, "War");
          addPanelToCenter
(centerPanel, "Horror");
          addPanelToCenter
(centerPanel, "Western");
          addPanelToCenter
(centerPanel, "Thriller");
          addPanelToCenter
(centerPanel, "Documentary");
          addPanelToCenter
(centerPanel, "Drama");
          addPanelToCenter
(centerPanel, "Biography");
          addPanelToCenter
(centerPanel, "Adventure");

         
// Add centerPanel to contentPane
         
contentPane.add(centerPanel, BorderLayout.CENTER);

         
// Add the content pane to the JFrame
         
add(contentPane);
   
}


   
private void addPanelToCenter(JPanel parent, String title){
         
JPanel panel = new JPanel();

          panel.setBorder
(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
                     
(title + " Movies"), TitledBorder.TRAILING, TitledBorder.DEFAULT_POSITION, centerPanelFont, Color.BLUE));

          parent.add
(panel, title);
   
}


   
private void init() {
         
try{
               
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
         
}
         
catch(Exception e){
               
e.printStackTrace();
         
}
         
setTitle("ComboBoxes");
          setSize
(500, 300);
          setLocationRelativeTo
(null);
   
}


   
public static void main(String[] args){
         
SwingUtilities.invokeLater(new Runnable() {
               
public void run() {
                     
new ComboBoxes2();
               
}
          })
;
   
}
}


You are here :  JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.20. Combo boxes
Next tutorial :  JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.21. Lists

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7