Get selected item from JComboBox in Java
Description
The following code shows how to get selected item from JComboBox.
Example
//from w w w. j av a 2s . c o m
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class Main extends JFrame {
JComboBox combo = new JComboBox();
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
combo.addItem("A");
combo.addItem("H");
combo.addItem("P");
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(" Selected item=" + combo.getSelectedItem());
}
});
getContentPane().add(combo);
setLayout(new java.awt.FlowLayout());
pack();
setVisible(true);
}
public static void main(String arg[]) {
new Main();
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »