简体   繁体   中英

How to check which button in my JFrame was clicked if I have more than one button with the same text?

I am designing Reversi game in java, and the structure is as follows:

a. A JFrame with 64 buttons in it. The buttons are stored in an array.

b.The JButtons will have black circles or white circles.

So whenever a move is to be made, the program will highlight those boxes where a move can be made, but how can I know which button (I want to know the index of that button) has been clicked when all are highlighted the same way?

You probably have one ActionListener added to all buttons. Then the ActionEvent getSource passed to performAction has info. That is ugly, like testing the button text.

What is more normal is to use Action (take a look) and setting different actions bearing the 64 states.

public BoardAction extends AbstractAction {
    public BoardAction(int x, int y) { ... }

    @Override
    public void actionPerformed(ActionEvent e) {
        ...
    }
}

JButton button = new JButton(new BoardAction(x, y));

In an Action you can also specify the button caption, and an Action can also be (re)used in a JMenuItem and such.

Because of the extra indirection needed, most examples use an ActionListener, but swing interna use Action quite often. For instance having an edit menu with cut/copy/pase and a toolbar with cut/copy/paste icons, context menus.

From my understanding, you are attempting to detect when a specific JButton is pressed. The simplest way to do this is by implementing an ActionListener.

public class ExampleClass implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == buttonNameOne)
            System.out.println("Button One was pressed");
        else if (e.getSource() == buttonNameTwo)
            System.out.pringln("Button Two was pressed);
    }
}

Detecting an action

The actionPerformed(ActionEvent e) method will activate whenever any button is pressed.

Recording source of action

When it is pressed, it automatically detects the source of this action (the button) and stores it in parameter "e".

Using recorded source of action

By simply doing e.getSource() you are able to get the component which invoked this method and compare it to pre-existing components in your program.

Customized arguments

With each if statement, you are able to customize and personalize the result of the condition (which is if the button being pressed is equal to a specific button). Do this by putting arguments within the body of each conditional statement:

if (e.getSource == sayHiButton)
   System.out.println("Hi");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM