MultipleListeners.java Source code

Java tutorial

Introduction

Here is the source code for MultipleListeners.java

Source

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;

public class MultipleListeners {
    JLabel statusbar = new JLabel("0");
    JSpinner spinner = new JSpinner();
    static int count = 0;

    class ButtonListener1 implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            Integer val = (Integer) spinner.getValue();
            spinner.setValue(++val);
        }
    }

    class ButtonListener2 implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            statusbar.setText(Integer.toString(++count));
        }
    }

    public MultipleListeners() {
        JPanel panel = new JPanel();
        JButton add = new JButton("+");
        add.addActionListener(new ButtonListener1());
        add.addActionListener(new ButtonListener2());

        panel.add(add);
        panel.add(spinner);
        JFrame f = new JFrame();
        f.add(panel);
        f.add(statusbar, BorderLayout.SOUTH);

        f.setSize(300, 200);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }

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