Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple ActionListeners for multiple buttons in Java Swing

Tags:

java

swing

I know how to create one button and an Action Listener for it. But I want to have several buttons and actionListeners for them doing separate actions unrelated to each other.

Example:

protected JButton x;

x = new JButton("add");
x.addActionListener(this);

public void actionPerformed(ActionEvent evt) { //code.....}

Now I want to have other buttons which may hav different functions like subtract, multiply etc. please suggest. thanks

like image 796
JavaBits Avatar asked May 06 '11 12:05

JavaBits


People also ask

What is use of getSource () method?

The getSource method is used in the actionPerformed method to determine which button was clicked. For more information, see Event Handling.

What is actionPerformed in Java?

An action event occurs, whenever an action is performed by the user. Examples: When the user clicks a button, chooses a menu item, presses Enter in a text field. The result is that an actionPerformed message is sent to all action listeners that are registered on the relevant component.


2 Answers

What about:

    JButton addButton = new JButton( new AbstractAction("add") {
        @Override
        public void actionPerformed( ActionEvent e ) {
            // add Action
        }
    });

    JButton substractButton = new JButton( new AbstractAction("substract") { 
        @Override
        public void actionPerformed( ActionEvent e ) {
            // substract Action
        }
    });
like image 178
oliholz Avatar answered Oct 06 '22 00:10

oliholz


Use inner classes:

x = new JButton("add"); 
x.addActionListener(
  new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      //your code here
    }
  }
);
like image 31
Liv Avatar answered Oct 06 '22 02:10

Liv