Use a string array as the data for JComboBox in Java

Description

The following code shows how to use a string array as the data for JComboBox.

Example


 //from w  w  w  . j a  v a2  s.  co m
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", "C", "D", "E"};
    JComboBox comboBox = new JComboBox(labels);
    
    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.

Use a string array as the data 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