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.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »