Java 我怎样才能知道单击了哪个按钮?
我的按钮工作正常,我是每个按钮的倾听者,如下所示:Java 我怎样才能知道单击了哪个按钮?,java,swing,button,actionlistener,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]); } 我需要某种方法来找到数组中的按钮。ActionEvent有一个方法getActionComman
for(int i = 0; i <= 25; ++i) {
buttons[i] = new Button(Character.toString(letters[i]));
buttons[i].addActionListener(actionListener);
panel1.add(buttons[i]);
}
我需要某种方法来找到数组中的按钮。ActionEvent有一个方法getActionCommand(),该方法将获取JButton的actionCommand字符串。这通常也是文本(对于JButtons)。试试这个
ActionListener ActionListener=new ActionListener(){
已执行的公共无效操作(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();
}
};
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt){
l1.setText(“”;//所需级别的名称
t1.setText(null);//所需的文本字段
t2.setText(null);//所需的文本字段
}
首先将源代码强制转换为按钮,然后获取标签((button)actionEvent.getSource()).getLabel()…哇,非常感谢java确实有很多东西,但有些函数是非常复杂的(然后按照actionEvent
继承的类的链接,并检查这些类的方法)。JavaDocs——这类东西非常方便我不知道你在回答谁的问题,但这似乎不是Makenshi提出的问题。+1用于提及getActionCommand()
,特别是“这通常也是文本”(强调我的)。我应该在哪里添加此代码?我希望它能为我的所有按钮工作。
ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent actionEvent) {
JButton button = (JButton)actionEvent.getSource();
String label = button.getLabel(); //Deprecated
String label2 = button.getText();
}
};