【问题标题】:How can I pass a non final variable to an anonymous inner class?如何将非最终变量传递给匿名内部类?
【发布时间】:2011-06-12 02:53:03
【问题描述】:

我有这些代码行。我知道您不能将非最终变量传递给内部类,但我需要将变量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);
        }
    });
}

【问题讨论】:

  • 如果您提供演示该错误的最少量可编译代码,您将获得更好的答案。你是说上面代码中有“seatingID”的地方是“i”吗?
  • 实际上没有错误,我试图找出一种方法将变量 i 从 for 循环传递到内部类,以便我可以将其分配为座位 ID

标签: java inner-classes anonymous-inner-class


【解决方案1】:

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

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

【讨论】:

  • +1 是的,这也是我提议的。 (只是我会将此命名为 seatingID 而不是 ii。)
【解决方案2】:

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

然后而不是

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

你应该有

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

[编辑] 实际上,您的代码还有很多其他问题,我不确定这个建议是否正确。展示可以编译的代码怎么样?

【讨论】:

  • 哪一部分?我是新手。这只是计划的一部分。
  • sw101 没有在任何地方声明,satingID 也没有在任何地方声明,当用户多次点击按钮时会发生什么?请参阅我对主要问题的评论。
  • sw101 是一个飞行对象,它在某处声明,我的问题是想办法传递变量 i。
猜你喜欢
  • 2011-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多