2010-03-21 20 views
4

我在這個類中有一個靜態變量partner。我想在每次按下單選按鈕時設置這些變量的值。這是我嘗試使用代碼:我怎樣才能給一個動作監聽器一個變量?

for (String playerName: players) { 
    option = new JRadioButton(playerName, false); 
    option.addActionListener(new ActionListener(){ 
     @Override 
     public void actionPerformed(ActionEvent evt) { 
      partner = playerName; 
     } 
    }); 
    partnerSelectionPanel.add(option); 
    group.add(option); 
} 

這裏的問題是,actionPerformed沒有看到環產生的變量playerName。我如何將這個變量傳遞給actionListener?

回答

9
for (final String playerName: players) { 
    option = new JRadioButton(playerName, false); 
    option.addActionListener(new ActionListener(){ 
     @Override 
     public void actionPerformed(ActionEvent evt) { 
      partner = playerName; 
     } 
    }); 
    partnerSelectionPanel.add(option); 
    group.add(option); 
} 

傳遞給內部類的局部變量必須是最終的。本來我認爲你不能在for循環中做最後的playerName,但實際上你可以。如果不是這種情況,您只需將playerName存儲在附加的最終變量(final String pn = playerName)中,並使用actionPerformed中的pn

2

變量必須是最終將其傳入內部類。

1
JButton button = new JButton("test"); 

button.addActionListiner(new ActionForButton("test1","test2")); 

class ActionForButton implements ActionListener { 

    String arg,arg2; 
    ActionFroButton(String a,String b) { 
     arg = a; arg2 = b; 
    } 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      Sustem.out.println(arg + "--" + arg2); 
     } 
} 
相關問題