retreiving actionlistner for jcombobox
I am wanting to remove the actionlistener that is set to a jcombobox and i tried this line
cboPatients.removeActionListener(cboPatients.getActionListeners());
but gives me the error
removeActionListener(java.awt.event.ActionListener) in javax.swing.JComboBox cannot be applied to (java.awt.event.ActionListener[])
here is how my jcombobox is setup
privatevoid cboPatientsActionPerformed(java.awt.event.ActionEvent evt){
I am needing to remove the action listener so that i can do a removeallitems() and then re-enstate the actionlistener.
let me know if more information is needed
The error message says it all. Method getActionListeners returns an array of ActionListeners because there are often multiple listeners. If you want to remove a specific listener you should save a reference to that listener before adding it to the collection, so that later, you can recall it!
Demo:
import java.awt.event.*;
import javax.swing.*;
public class Gui {
private JComboBox combo = new JComboBox(new String[]{"apple","berry","cherry"});
private ActionListener al = new ActionListener(){
public void actionPerformed(ActionEvent evt) {
System.out.println(combo.getSelectedItem());
}
};
private ItemListener il = new ItemListener() {
public void itemStateChanged(ItemEvent evt) {
if (evt.getStateChange() == ItemEvent.SELECTED)
combo.addActionListener(al);
else
combo.removeActionListener(al);
}
};
public Gui() {
JCheckBox listening = new JCheckBox("Listening");
listening.addItemListener(il);
JPanel contentPane = new JPanel();
contentPane.add(combo);
contentPane.add(listening);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(contentPane);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
new Gui();
}
});
}
}