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

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

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

在这里你可以看到监听器被调用,我想知道我点击了哪个按钮。 有没有办法做到这一点?

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

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

尝试这个

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

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

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

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

  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 }