如何将非最终变量传递给匿名内部类? [英] How can I pass a non final variable to an anonymous inner class?
本文介绍了如何将非最终变量传递给匿名内部类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这些代码行.我知道您不能将非最终变量传递给内部类,但是我需要将变量i
传递给匿名内部类以用作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);
}
});
}
推荐答案
简单的方法是创建一个局部最终变量,并使用循环变量的值对其进行初始化.例如
The simple way is to create a local final variable and initialize it with the value of the loop variable; e.g.
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);
}
});
}
这篇关于如何将非最终变量传递给匿名内部类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文