如何将非最终变量传递给匿名内部类?

问题描述

| 我有这些代码行。我知道您不能将非最终变量传递给内部类,但是我需要将变量“ 0”传递给匿名内部类以用作SeatingID。你能建议这样做的方法吗?
JButton [] seats = new JButton [40]; //creating a pointer to the buttonsArray
for (int i = 0; i < 40; i++)
{
    seats[i] = new JButton();//creating the buttons
    seats[i].setPreferredSize(new Dimension(50,25));//button width
    panel4seating.add(seats[i]);//adding the buttons to the panels

    seats[i].addActionListener(new ActionListener()
    {  //anonymous inner class
        public void actionPerformed(ActionEvent evt)
        {  
            String firstName = (String)JOptionPane.showInputDialog(\"Enter First Name\");
            String lastName = (String)JOptionPane.showInputDialog(\"Enter Last Name\");

            sw101.AddPassenger(firstName,lastName,seatingID);
        }
    });
}
    

解决方法

        一种简单的方法是创建一个局部最终变量,并使用循环变量的值对其进行初始化。例如
    JButton [] seats = new JButton [40]; //creating a pointer to the buttonsArray
    for (int i = 0; i < 40; i++)
    {
        seats[i] = new JButton();//creating the buttons
        seats[i].setPreferredSize(new Dimension(50,25));//button width
        panel4seating.add(seats[i]);//adding the buttons to the panels
        final int ii = i;  // Create a local final variable ...
        seats[i].addActionListener(new ActionListener()
         {  //anonymous inner class
            public void actionPerformed(ActionEvent evt)
            {  
                String firstName = (String)JOptionPane.showInputDialog(\"Enter First Name\");
                String lastName = (String)JOptionPane.showInputDialog(\"Enter Last Name\");

                sw101.AddPassenger(firstName,lastName,ii);
            }
         });
    }
    ,        您不能直接这样做,但可以创建ActionListener的(静态私有)子类,该子类在其构造函数中采用了SeatingID。 然后,而不是
seats[i].addActionListener(new ActionListener() { ... });
你会
seats[i].addActionListener(new MySpecialActionListener(i));
[编辑]实际上,您的代码有很多其他错误,以至于我不确定该建议是否正确。如何展示将要编译的代码。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...