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 40 41 42 43 44 45 46 47 48 49 | import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Main extends JFrame { public Main() { initialize(); } private void initialize() { setSize(300, 300); setLayout(new FlowLayout(FlowLayout.LEFT)); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String[] names = new String[] { "Java", "C++", "C" }; JComboBox comboBox = new JComboBox(names); comboBox.setEditable(true); comboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { JComboBox comboBox = (JComboBox) event.getSource(); System.out.println("Selected Item = " + comboBox.getSelectedItem()); System.out.println("Action Command = " + event.getActionCommand()); if ("comboBoxEdited".equals(event.getActionCommand())) { System.out.println("User has typed a string in the combo box."); } else if ("comboBoxChanged".equals(event.getActionCommand())) { System.out.println("User has selected an item from the combo box."); } } }); getContentPane().add(comboBox); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new Main().setVisible(true); } }); } } |
Output:
1 2 3 4 5 | Selected Item = C++ Action Command = comboBoxChanged User has selected an item from the combo box. |