简体   繁体   English

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

[英]How can I pass a non final variable to an anonymous inner class?

I have these lines of code.我有这些代码行。 I know you can not pass a non final variable to an inner class but I need to pass the variable i to the anonymous inner class to be used as a seatingID.我知道您不能将非最终变量传递给内部 class 但我需要将变量i传递给匿名内部 class 以用作座位ID。 Can you suggest ways of doing that?你能建议这样做的方法吗?

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);
        }
    });
}

The simple way is to create a local final variable and initialize it with the value of the loop variable;简单的方法是创建一个局部最终变量,并用循环变量的值对其进行初始化; eg例如

    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);
            }
         });
    }

You can't directly, but you can make a (static private) subclass of ActionListener that takes a seatingID in its constructor.您不能直接,但您可以创建一个 ActionListener 的(静态私有)子类,它在其构造函数中采用座位ID。

Then rather than然后而不是

seats[i].addActionListener(new ActionListener() { ... });

you'd have你会有

seats[i].addActionListener(new MySpecialActionListener(i));

[Edit] Actually, there's so much else wrong with your code that I'm not really sure that this advice is good. [编辑] 实际上,您的代码还有很多其他问题,我不确定这个建议是否正确。 How about presenting code that would compile.如何呈现可以编译的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM