[英]How can I pass a non final variable to an anonymous inner class?
我有這些代碼行。 我知道您不能將非最終變量傳遞給內部 class 但我需要將變量i
傳遞給匿名內部 class 以用作座位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);
}
});
}
簡單的方法是創建一個局部最終變量,並用循環變量的值對其進行初始化; 例如
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);
}
});
}
您不能直接,但您可以創建一個 ActionListener 的(靜態私有)子類,它在其構造函數中采用座位ID。
然后而不是
seats[i].addActionListener(new ActionListener() { ... });
你會有
seats[i].addActionListener(new MySpecialActionListener(i));
[編輯] 實際上,您的代碼還有很多其他問題,我不確定這個建議是否正確。 如何呈現可以編譯的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.