如何找出点击了哪个按钮?

Mak*_*shi 13 java swing button actionlistener

我的按钮工作正常,我是每个按钮的监听器,如下所示:

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

在这里你可以看到调用者被调用,我想找出我点击的按钮.有没有办法做到这一点?

ActionListener actionListener = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        System.out.println(actionEvent.getSource());
    }
};
Run Code Online (Sandbox Code Playgroud)

我需要一些方法来找到数组中的按钮.

Pra*_*tik 22

试试这个

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

          System.out.println(actionEvent.getActionCommand());
      }
    };
Run Code Online (Sandbox Code Playgroud)


Adi*_*mro 7

为了得到标签,试试这个.

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

            String label2 = button.getText();
     }
};
Run Code Online (Sandbox Code Playgroud)


Hov*_*els 5

ActionEvent有一个方法getActionCommand(),它将获得JButton的actionCommand String.这通常是它的文本(对于JButtons).