Set selected item for JComboBox in Java

Description

The following code shows how to set selected item for JComboBox.

Example


 /*from w ww . j av  a2 s .  c  om*/

import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main {

  public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    String labels[] = { "A", "B", "java2s.com", "D", "E"};
    JComboBox comboBox = new JComboBox(labels);
    
    comboBox.setSelectedItem("java2s.com");
    
    Object cmboitem = comboBox.getSelectedItem();
    System.out.println(cmboitem);
    frame.setLayout(new java.awt.FlowLayout());
    frame.add(comboBox);

    frame.setSize(300, 200);
    frame.setVisible(true);
  }

}

The code above generates the following result.

Set selected item for JComboBox in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer