In this example we are going to see how to use JComboBox Listner With ItemListener In Java Example
Java Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import java.awt.BorderLayout; import java.awt.ItemSelectable; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JComboBox; import javax.swing.JFrame; public class Main { static private String selectedString(ItemSelectable is) { Object selected[] = is.getSelectedObjects(); return ((selected.length == 0) ? "null" : (String) selected[0]); } public static void main(String args[]) { String labels[] = { "A", "B", "C", "D", "E", "F" }; JFrame frame = new JFrame("Selecting JComboBox"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JComboBox comboBox = new JComboBox(labels); frame.add(comboBox, BorderLayout.SOUTH); ItemListener itemListener = new ItemListener() { public void itemStateChanged(ItemEvent itemEvent) { int state = itemEvent.getStateChange(); System.out.println((state == ItemEvent.SELECTED) ? "Selected" : "Deselected"); System.out.println("Item: " + itemEvent.getItem()); ItemSelectable is = itemEvent.getItemSelectable(); System.out.println("Selected: " + selectedString(is)); } }; comboBox.addItemListener(itemListener); frame.setSize(400, 200); frame.setVisible(true); } } |
Output:
1 2 3 4 5 6 7 8 | Deselected Item: A Selected: C Selected Item: C Selected: C |