Java JButton add more than one action listener

Description

Java JButton add more than one action listener

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 Main {
  JLabel statusbar = new JLabel("0");
  JSpinner spinner = new JSpinner();
  JButton add = new JButton("+");
  static int count = 0;

  class ButtonListener1 implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      Integer val = (Integer) spinner.getValue();
      spinner.setValue(++val);
    }/* ww w .  j av  a 2 s.  com*/
  }

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

  public Main() {
    JPanel panel = new JPanel();

    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 Main();
  }
}



PreviousNext

Related