如何将非最终变量传递给匿名内部类?
我有这些代码行。我知道您不能将非最终变量传递给内部类,但我需要将变量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);
}
});
}
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. 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);
}
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简单的方法是创建一个局部最终变量并使用循环变量的值对其进行初始化;例如
The simple way is to create a local final variable and initialize it with the value of the loop variable; e.g.
您不能直接这样做,但您可以创建 ActionListener 的(静态私有)子类,该子类在其构造函数中采用 SeatingID。
然后,而不是
你
[编辑]实际上,你的代码还有很多其他错误,我不确定这个建议是否好。展示可以编译的代码怎么样?
You can't directly, but you can make a (static private) subclass of ActionListener that takes a seatingID in its constructor.
Then rather than
you'd have
[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.