Java ActionListener查找按下的JButton的正确名称(而不是显示的字符串)?

Java ActionListener查找按下的JButton的正确名称(而不是显示的字符串)?,java,swing,button,if-statement,jbutton,Java,Swing,Button,If Statement,Jbutton,我遇到了一个我找不到解决方案的问题,在Java中围绕JButtons运行 为了保持代码“干净”,我已使用以下for循环声明了我的所有按钮: JButton[] buttons= new JButton[10]; for(int i = 0;i < buttons.length;i++){ buttons[i] = new JButton("Example "+i); contents2.add(buttons[i]); buttons[i].addActionLis

我遇到了一个我找不到解决方案的问题,在Java中围绕JButtons运行

为了保持代码“干净”,我已使用以下
for
循环声明了我的所有按钮:

JButton[] buttons= new JButton[10];
for(int i = 0;i < buttons.length;i++){
    buttons[i] = new JButton("Example "+i);
    contents2.add(buttons[i]);
    buttons[i].addActionListener(listener);}
但是,
if(actionEvent.getSource()==(JButton)buttons[1].getSource())
中的
按钮
具有无法解析为变量的Eclipse告诉我按钮

在同一行中,我还尝试了不使用
(JButton)
、在
按钮[1]
之后不使用
.getSource()
以及更多组合

我把自己弄糊涂了,但是我只想在按下按钮时在
侦听器中执行操作


很抱歉造成混淆,但如果您理解这一点,将不胜感激。我只是不断得到我想要的字符串。

您可以使用动作侦听器中使用的
setActionCommand
方法,而不是使用不存在的源代码

示例:

ActionListener listener = new ActionListener() {
        public void actionPerformed (ActionEvent actionEvent) {
            String index = actionEvent.getActionCommand();

            switch(Integer.valueOf(index)){
                case 1: //your actions here for index 1 of button
                break;
            }
        }
    };

final JButton[] buttons= new JButton[10];
    for(int i = 0;i < buttons.length;i++){
        buttons[i] = new JButton("Example "+i);
        contents2.add(buttons[i]);
        buttons[i].setActionCommand(i+"");
        buttons[i].addActionListener(listener);
    }
ActionListener=newactionListener(){
已执行的公共无效操作(ActionEvent ActionEvent){
字符串索引=actionEvent.getActionCommand();
开关(整型.valueOf(索引)){
案例1://您在此处对按钮的索引1执行的操作
打破
}
}
};
最终JButton[]按钮=新JButton[10];
对于(int i=0;i
正如您所看到的,
action命令
是按钮的索引,因此您可以使用switch语句对每个按钮执行操作


案例1
表示
按钮
数组的
索引1

可能在
JButton
数组之前声明了
ActionListener

相反,将
按钮
声明为实例变量

 public class SomeClass extends ... {
     private JButton[] buttons;
然后,您应该能够使用

if(actionEvent.getSource() == buttons[1]){
构造按钮数组时,还需要确保没有隐藏变量,例如

buttons= new JButton[10]; 
for(int i = 0;i < buttons.length;i++){
buttons=newjbutton[10];
对于(int i=0;i

话虽如此,如果您想清理代码,那么我建议您看看,它为操作提供了一个可重用的API,可以附加到按钮、菜单项和键绑定上

有许多问题可能会导致这种情况,但如果没有更多的上下文,很难知道是哪一个问题您是否正在遭受折磨?考虑提供一个演示您的问题的方法,这将减少猜测工作并产生更好的响应<代码>,因为我希望保持代码“干净”,< /代码> -那么您不应该有I/OR(或开关)。ActionListener中的语句。如果按钮具有类似的功能,那么您应该执行中的示例。如果功能不能通用,那么您应该创建单独的ActionListener。因此,我们引入了一个效率更低的解决方案,而不是提供更干净的解决方案。此外,Java 7允许您使用
开关中的
字符串
statements@MadProgrammer是的,您是对的switch语句允许字符串,但它比integer慢,因为它将使用equals方法与每个case语句关联,而equals方法与integer将使用哈希表,速度为O(1)@MadProgrammer 10个实例??不,这只是一个实例,我正在尝试创建一个实例,并为将使用ActionListener的每个按钮使用case语句噢,对不起,我以为它在for循环中…所以现在代码不会编译:P@MadProgrammer是的,但它是独立的,ActionListener必须在或者他添加了监听按钮。
buttons= new JButton[10]; 
for(int i = 0;i < buttons.length;i++){