2011-06-12 86 views
5

我有這些代碼行。我知道你不能將一個非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); 
     } 
    }); 
} 
+0

如果您提供可顯示錯誤的最小編譯代碼,您將得到更好的答案。你的意思是'我'你在上面的代碼中有'seatID'嗎? – 2011-06-12 03:04:45

+0

實際上沒有錯誤,我試圖找出一種方法將變量從for循環傳遞給內部類,所以我可以將它分配爲一個座位號 – dave 2011-06-12 03:07:42

回答

8

簡單的方法是創建一個局部最終變量並用循環變量的值初始化它;例如

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); 
      } 
     }); 
    } 
+0

+1是的,這也是我提出的建議。 (只是我會命名這個'seatingID'而不是'ii')。 – 2011-06-12 03:17:22

+0

這幫了我,謝謝 – cljk 2012-11-04 23:15:42

2

你不能直接,但你可以做的ActionListener的(靜態專用)子類,它需要一個seatingID在其構造。

然後而非

seats[i].addActionListener(new ActionListener() { ... }); 

你必須

seats[i].addActionListener(new MySpecialActionListener(i)); 

[編輯]其實,有如此多的其他問題與您的代碼,我真的不知道,這個主意很不錯。如何呈現可編譯的代碼。

+0

哪部分?我是新的搖擺。這只是該計劃的一部分。 – dave 2011-06-12 03:03:41

+0

sw101沒有在任何地方聲明,不能在任何地方聲明seatID,當用戶多次點擊按鈕時會發生什麼?看到我對主要問題的評論。 – 2011-06-12 03:05:35

+0

sw101是一個飛行物體,它在某處被聲明,我的問題是找出一個方法來傳遞變量i。 – dave 2011-06-12 03:08:44