How can I find out which button was clicked?

2019-01-11 11:11发布

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.

4条回答
We Are One
2楼-- · 2019-01-11 11:49

ActionEvent has a method getActionCommand() that will get a JButton's actionCommand String. This is usually it's text as well (for JButtons).

查看更多
淡お忘
3楼-- · 2019-01-11 11:53

try this

ActionListener actionListener = new ActionListener()
 {
      public void actionPerformed(ActionEvent actionEvent) {

          System.out.println(actionEvent.getActionCommand());
      }
    };
查看更多
Emotional °昔
4楼-- · 2019-01-11 12:09
 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
l1.setText("");//name of level what you want

t1.setText(null);//text field what you want 

t2.setText(null);//text field what you want
}
查看更多
小情绪 Triste *
5楼-- · 2019-01-11 12:10

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();
     }
};
查看更多
登录 后发表回答