5

我有这些代码行。我知道您不能将非最终变量传递给内部类,但我需要将变量传递i给匿名内部类以用作座位ID。你能建议这样做的方法吗?

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

2 回答 2

8

简单的方法是创建一个局部最终变量,并用循环变量的值对其进行初始化;例如

    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);
            }
         });
    }
于 2011-06-12T03:05:07.120 回答
2

您不能直接,但您可以创建一个 ActionListener 的(静态私有)子类,它在其构造函数中采用座位ID。

然后而不是

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

你会有

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

[编辑] 实际上,您的代码还有很多其他问题,我不确定这个建议是否正确。如何呈现可以编译的代码。

于 2011-06-12T02:58:55.367 回答