Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out which button was clicked?

I've got my buttons working right, and I'm a listener to each button like this:

for(int i = 0; i <= 25; ++i) {
    buttons[i] = new Button(Character.toString(letters[i]));
    buttons[i].addActionListener(actionListener);
    panel1.add(buttons[i]);
}

Here as you can see the listener is called, and I want to find out which button I'm clicking. Is there a way to do that?

ActionListener actionListener = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        System.out.println(actionEvent.getSource());
    }
};

I need some way to find the button in the array.

like image 424
Makenshi Avatar asked Sep 22 '11 05:09

Makenshi


People also ask

How do I know which button is clicked in HTML?

The Html <button onclick=" "> is an event attribute, which executes a script when the button is clicked. This attribute is supported by all browsers. It is also used to call a function when the button is clicked.

What happens if a toggle button is clicked?

By default, toggle buttons are OFF. When a user clicks the toggle, it will switch to ON. If a user clicks it again, it will toggle back to OFF.


1 Answers

In order to get label, try this.

ActionListener actionListener = new ActionListener()
{
      public void actionPerformed(ActionEvent actionEvent) {
            JButton button = (JButton)actionEvent.getSource();
            String label = button.getLabel(); //Deprecated 

            String label2 = button.getText();
     }
};
like image 144
Adil Soomro Avatar answered Sep 21 '22 00:09

Adil Soomro