删除comboBox的actionlistener,但找不到参数

时间:2014-06-13 07:12:33

标签: java combobox

comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                JComboBox comboBox = (JComboBox) event.getSource();
                Object selected = comboBox.getSelectedItem();
                switch(selected.toString()){
                        //some actions based on String picked
                    default:
                    break;
                }
            }
        });

我不知道哪个参数必须有.removeActionListener()方法来删除动作侦听器并更改comboBox的内容。

2 个答案:

答案 0 :(得分:2)

问题是,你已经创建了一个内联匿名内部类,这意味着你没有外部引用它......

您可以创建ActionListener,但首先将其分配给实例变量

private ActionListener actionListener;
//...
actionListener = new ActionListener() {...};
comboBox.addActionListener(actionListener);

然后您可以稍后使用...

删除它
comboBox.removeActionListener(actionListener);

答案 1 :(得分:1)

您必须将actionListener存储在变量中:

ActionListener al = new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                JComboBox comboBox = (JComboBox) event.getSource();
                Object selected = comboBox.getSelectedItem();
                switch(selected.toString()){
                        //some actions based on String picked
                    default:
                    break;
                }
            }
        }

并使用comboBox.removeActionListener(al)删除actionListener,并且必须使用al来添加侦听器