RemoveListener.java Source code

Java tutorial

Introduction

Here is the source code for RemoveListener.java

Source

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 RemoveListener {
    class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            System.out.println(++count);
        }
    }

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

    public RemoveListener() {
        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 RemoveListener();
    }
}