我有這些代碼行。我知道你不能將一個非final變量傳遞給一個內部類,但我需要將變量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);
}
});
}
如果您提供可顯示錯誤的最小編譯代碼,您將得到更好的答案。你的意思是'我'你在上面的代碼中有'seatID'嗎? – 2011-06-12 03:04:45
實際上沒有錯誤,我試圖找出一種方法將變量從for循環傳遞給內部類,所以我可以將它分配爲一個座位號 – dave 2011-06-12 03:07:42