JComboBox监听器

时间:2015-07-16 08:57:51

标签: java swing

我想根据JComboBox更改按钮的功能。

例如,当我选择单数和复数名词时,按钮行为应更改为此项目,当我从JComboBox按钮中选择另一项时,按钮的行为应相应更改。

1 个答案:

答案 0 :(得分:1)

您可以在组合框中添加一个监听器:

//In your class
comboList.addActionListener(this);

然后在ActionPerformed中,您可以更改所需功能的按钮的监听器:

//In your class
JButton btn1 = new JButton("Button1");

--------------------------------------------------------

// Your actionPerformed for combo box listener
 public void actionPerformed(ActionEvent e) {
        JComboBox cb = (JComboBox)e.getSource();
        String itemName = (String)cb.getSelectedItem();
        if(itemName.equals("str"){

           //checking if you are not adding listener twice
           if(btn1.getActionListeners().length > 0){
                //remove all the existing listener, iterate and remove if more than one
                btn1.removeActionListener(existingListener);                    
           }
           btn1.addActionListener(new ButtonListener1());
        }
        if(itemName.equals("str2"){
           //follow same process as for above if
        }
    }