我的按钮正常工作,并且我是每个按钮的监听者,如下所示:
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字符串。通常这也是文本(对于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
}