作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我有这些代码行。我知道您不能将非最终变量传递给内部类,但我需要将变量 i
传递给匿名内部类以用作 seatingID。你能建议这样做的方法吗?
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);
}
});
}
最佳答案
简单的方法是创建一个局部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);
}
});
}
关于java - 如何将非最终变量传递给匿名内部类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6319828/
我是一名优秀的程序员,十分优秀!