2010-03-21 72 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); 
     } 
} 
相关问题