How to differentiate buttons within the same event?

Asked

Viewed 366 times

0

I would like to know a method to differentiate a button that generated event, in my method that will treat the events.

In the example below I add the same class that handles the events to 2 buttons, but I can’t 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");
        }

    }

1 answer

1


A simple way is to define Action Commands using the method 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 in using action command instead of button.getText() is that you can freely change the text of buttons without having to update the Switch. Remembering that this option is not restricted to only 2 buttons, can be added other, just have to add case in the 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.