Search code examples
javaswingjbuttonactionlistener

Using multiple JButtons with the same label in Java


I have two buttons in my project that both have a "+" label. When the actionPerformed() method is called, it calls a specific method based on the label. How can I distiguish between two JButtons with the same label? Is there a better way to do this then how I've done it?

This is the definition of the buttons:

JButton keypadPlus1 = new JButton(" + ");
JButton keypadMinus1 = new JButton(" - ");
JButton keypadPlus2 = new JButton("+");
JButton keypadMinus2 = new JButton("-");

Adding the ActionListeners for the buttons:

keypadPlus1.addActionListener(backEnd);
keypadPlus2.addActionListener(backEnd);
keypadMinus1.addActionListener(backEnd);
keypadMinus2.addActionListener(backEnd);

The actionPerformed @Override in the backEnd:

public void actionPerformed (ActionEvent event) {
        String command = event.getActionCommand();
        if (command.equals("+")) {
            calcLifePoints(command);
        }
        if (command.equals("-")) {
            calcLifePoints(command);
        }
        if (command.equals(" + ")) {
            calcLifePoints(command);
        }
        if (command.equals(" - ")) {
            calcLifePoints(command);
        }

    }

Solution

  • Instead of this,

    public void actionPerformed (ActionEvent event) {
            String command = event.getActionCommand();
            if (command.equals("+")) {
                calcLifePoints(command);
            }
            if (command.equals("-")) {
                calcLifePoints(command);
            }
            if (command.equals(" + ")) {
                calcLifePoints(command);
            }
            if (command.equals(" - ")) {
                calcLifePoints(command);
            }
    
        }
    

    Use like this,

    public void actionPerformed (ActionEvent event) {
            Object command = event.getSource();
            if (command.equals(keypadPlus1)) {
                calcLifePoints(event.getActionCommand());
            }
            if (command.equals(keypadMinus1)) {
                calcLifePoints(event.getActionCommand());
            }
            if (command.equals(keypadPlus2)) {
                calcLifePoints(event.getActionCommand());
            }
            if (command.equals(keypadMinus2)) {
                calcLifePoints(event.getActionCommand());
            }
    
        }