Rom*_*man 4 java variables visibility actionlistener
我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);
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是actionPerformed没有看到playerName循环中创建的变量.如何将此变量传递给actionListener?
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);
}
Run Code Online (Sandbox Code Playgroud)
传递给内部类的局部变量必须是最终的.最初我认为你不能playerName在for循环中做出最终结果,但事实上你可以.如果不是的话,你会简单地存储playerName在附加的最终变量(final String pn = playerName),并使用pn从actionPerformed.