getSelectedItem() - Selected Item of Combo Box

This section provides a tutorial example on how to use the getSelectedItem() method to know which option is selected from a combo box.

If you are using a combo box with multiple options, you can use the getSelectedItem() method to find out which option is selected. Here is a sample program:

 * Copyright (c) 1997-2018 All Rights Reserved.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JComboBoxAction implements ActionListener {
   JComboBox<String> combo;
   JLabel myLabel = null;
   public static void main(String[] a) {
      JComboBoxAction myTest = new JComboBoxAction();
   public void createFrame() {
    JFrame f = new JFrame("My Combo Box");
      Container c = f.getContentPane();
      c.setLayout(new BoxLayout(c,BoxLayout.Y_AXIS));
      JLabel color = new JLabel("Colors:");

      String[] options = {"Red", "Green", "Blue"};
      combo = new JComboBox<String>(options);
      JButton b = new JButton("Done");
      myLabel = new JLabel("Please select");
   public void actionPerformed(ActionEvent e) {
    String t = (String) combo.getSelectedItem();
    if (t == null) t = "Nothing selected";

If you run this program, you will see none of the options is selected initially. If you click "Done", you will get the "Nothing selected" message. If you select an option then click "Done", you will get the selected color:

JComboBox Selected Option
JComboBox Selected Option

Table of Contents

 About This Book

 JDK (Java Development Kit)

 Introduction of Java Swing Package

 Graphics Environment of the Local System

 JFrame - Main Frame Class

 JLabel - Swing Label Class

 JButton - Swing Button Class

 JCheckBox - Swing Check Box Class

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field Class

JComboBox - Swing Combo Box Class

 javax.swing.JComboBox and Related Methods

 ActionListener and ItemListener

getSelectedItem() - Selected Item of Combo Box

 setEditable() - Use Combo Box as Text Field

 Menu Bar, Menus, Menu Items and Listeners

 Creating Internal Frames inside the Main Frame

 Layout of Components in a Container

 LookAndFeel and UIManager

 Option Dialog Boxes

 JEditorPane - The Editor Pane Class

 SwingWorker - The Background Task Worker

 AWT (Abstract Windows Toolkit)

 Integration with Desktop System

 Archived Tutorials


 Full Version in PDF/EPUB