How to differentiate buttons within the same event?

0

I'd like to know a method to differentiate a button that generated event, in my method that will handle events.

In the example below I add the same class that handles events to 2 buttons, but I can not differentiate the buttons in my method actionPerformed() ;

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    public class Main{
        public static void main(String[] args){
            JFrame f = new JFrame();

            JButton b1 = new JButton("B1");
            JButton b2 = new JButton("B2");
            ActionListener evento = new Eventos();

            b1.addActionListener(evento);
            b2.addActionListener(evento);
            f.getContentPane().add(b1);
            f.getContentPane().add(b2);

            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(300,400);
            f.setVisible(true);
            f.setLayout(new GridLayout(1,2));
            f.pack();
        }
    }

    class Eventos implements ActionListener{

        public void actionPerformed(ActionEvent e) {
            // diferenciar b1 do b2;
            System.out.println("Clique");
        }

    }
    
asked by anonymous 13.05.2017 / 03:36

1 answer

1

A simple way is to define Action Commands using the setActionCommand() ":

JButton b1 = new JButton("B1");
JButton b2 = new JButton("B2");

ActionListener evento = new Eventos();

b1.setActionCommand("botao1");
b1.setActionCommand("botao2");

b1.addActionListener(evento);
b2.addActionListener(evento);

(...)

class Eventos implements ActionListener{

    public void actionPerformed(ActionEvent e) {

        String action = e.getActionCommand();

        switch(action) {
            case "botao1":
                //Ação do botao 1
            break;
            case "botao2":
                //Ação do botao 2
            break;
        } 
    }
}

The advantage of using action command instead of button.getText() is that you can freely change the text of the buttons without having to update the listener. Remember that this option is not restricted to only 2 buttons, others can be added, you will only have to add case to switch , but in case of many buttons, there are better solutions to identify the buttons than using switch, in this answer has an example using HashMap .

    
13.05.2017 / 03:46