Java ActionListener remove action listener from component

Description

Java ActionListener remove action listener from component

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
   JButton add = new JButton("+");
   JCheckBox active = new JCheckBox("Active listener");
   ButtonListener buttonlistener = new ButtonListener();
   int count = 0;

   class ButtonListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {
         System.out.println(++count);
      }/* w w  w .j a  va  2  s  . c  o  m*/
   }

   public Main() {
      JPanel panel = new JPanel();
      active.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent event) {
            if (active.isSelected()) {
               add.addActionListener(buttonlistener);
            } else {
               add.removeActionListener(buttonlistener);
            }
         }
      });
      panel.add(add);
      panel.add(active);
      JFrame f = new JFrame();
      f.add(panel);

      f.setSize(310, 200);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setVisible(true);
   }

   public static void main(String[] args) {
      new Main();
   }
}



PreviousNext

Related