Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

swing - 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);
        }

    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could...

Use ActionEvent#getSource

You could...

Set the actionCommand property of each button to something unique and use ActionEvent#getActionCommand

You could...

Use separate listeners, either anonymously or as inner or outer classes depending on your needs

You could...

Make use of the Action API, which would allow you to define a common/abstract Action which defined the common properties (like the + text) and then extend this to make unique actions for each button

See How to Use Actions for more details

You could...

Use JButton#putClientProperty to set some unique flag on each button and cast the ActionEvent to a JComponent and use getClientProperty to retrieve the flag ... but given the previous suggestions, I'm not sure why you'd bother


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...