gpt4 book ai didi

java - 如何将非最终变量传递给匿名内部类?

转载 作者:搜寻专家 更新时间:2023-10-31 19:30:48 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com