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:

/* JComboBoxAction.java
 * Copyright (c) HerongYang.com. 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();
      myTest.createFrame();
   }
   public void createFrame() {
	  JFrame f = new JFrame("My Combo Box");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container c = f.getContentPane();
      c.setLayout(new BoxLayout(c,BoxLayout.Y_AXIS));
	  
      JLabel color = new JLabel("Colors:");
      c.add(color);

      String[] options = {"Red", "Green", "Blue"};
      combo = new JComboBox<String>(options);
	  combo.setSelectedIndex(-1);
      c.add(combo);
	  
      JButton b = new JButton("Done");
      b.addActionListener(this);
      c.add(b);
	  
      myLabel = new JLabel("Please select");
      c.add(myLabel);
      f.pack();
      f.setVisible(true);
   }
   public void actionPerformed(ActionEvent e) {
	  String t = (String) combo.getSelectedItem();
	  if (t == null) t = "Nothing selected";
      myLabel.setText(t);
   }
}

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

 Outdated Tutorials

 References

 Full Version in PDF/EPUB