我正在尝试向 JCheckBox 添加匿名 actionListener,但在访问我想要更新值的对象时遇到一些困难。我不断收到有关非最终的错误,然后当我将它们更改为最终时,它会提示其他事情。
我想做的如下(我删除了一些 gui 代码以使其更易于阅读):
for (FunctionDataObject fdo : wdo.getFunctionDataList())
{
JLabel inputTypesLabel = new JLabel("Input Types: ");
inputsBox.add(inputTypesLabel);
for (int i = 0; i < fdo.getNumberOfInputs(); i++)
{
JLabel inputLabel = new JLabel(fdo.getInputNames().get(i));
JComboBox inputTypeComboBox = new JComboBox(getTypes());
inputTypeComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
fdo.getInputTypes().set(i, (String) inputTypeComboBox.getSelectedItem());
}
});
}
}
最佳答案
您无法访问匿名类中的非最终变量。您可以稍微修改代码来解决该限制(我已将 fdo
和 inputTypeComboBox
最终化,并且还制作了 i
的最终副本>):
for (final FunctionDataObject fdo : wdo.getFunctionDataList()) {
JLabel inputTypesLabel = new JLabel("Input Types: ");
inputsBox.add(inputTypesLabel);
for (int i = 0; i < fdo.getNumberOfInputs(); i++) {
final int final_i = i;
JLabel inputLabel = new JLabel(fdo.getInputNames().get(i));
final JComboBox inputTypeComboBox = new JComboBox(getTypes());
inputTypeComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fdo.getInputTypes().set(final_i, (String) inputTypeComboBox.getSelectedItem());
}
});
}
}
关于java - jcheckbox 上的 Action 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12598607/