Java如何将动作侦听器添加到JComboBox?
下面显示的代码,你如何将添加ActionListener到JComboBox组件。在代码段中,我们通过调用addActionListener()方法来添加侦听器,并将侦听器的实例ActionListener作为匿名类(没有指定名称的类)作为参数。
该ActionListener接口契约说,我们必须实现的actionPerformed(ActionEvente)方法。这是我们的程序将处理事件的地方。
package org.nhooo.example.swing; import javax.swing.*; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ComboBoxActionListener extends JFrame { public ComboBoxActionListener() { initialize(); } private void initialize() { setSize(300, 300); setLayout(new FlowLayout(FlowLayout.LEFT)); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); String[] names = new String[]{ "James", "Joshua", "Matt", "John", "Paul" }; JComboBox comboBox = new JComboBox<String>(names); comboBox.setEditable(true); //为JComboBox组件创建一个ActionListener。 comboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { //获取组件的来源,这是我们的组合 //框。 JComboBox comboBox = (JComboBox) event.getSource(); //打印选择的项目和操作命令。 Object selected = comboBox.getSelectedItem(); System.out.println("Selected Item = " + selected); String command = event.getActionCommand(); System.out.println("Action Command = " + command); //检测操作命令是否为“comboBoxEdited”"comboBoxEdited" //或“comboBoxChanged”"comboBoxChanged" if ("comboBoxEdited".equals(command)) { System.out.println("User has typed a string in " + "the combo box."); } else if ("comboBoxChanged".equals(command)) { 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 ComboBoxActionListener().setVisible(true); } }); } }