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?

4

3 回答 3

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

传递给内部类的局部变量必须是最终的。本来我以为你不能playerName在for循环中做final,但实际上你可以。如果不是这种情况,您只需存储playerName额外的最终变量 ( final String pn = playerName) 并使用pnfrom actionPerformed

于 2010-03-21T17:44:32.683 回答
2

变量必须是final才能将其传递给内部类。

于 2010-03-21T17:42:40.793 回答
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);
        }
}
于 2012-12-09T14:29:04.790 回答