我正在尝试向JCheckBox添加一个匿名actionListener,但是在访问我想要用来更新值的对象时遇到了一些困难。我一直收到关于非final的错误,然后当我将它们更改为final时,它会抱怨其他事情。
我尝试做的事情如下(我删除了一些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());
}
});
}
} 发布于 2012-09-26 17:31:41
您不能访问匿名类中的非final变量。你可以稍微修改一下你的代码来绕过这个限制(我已经完成了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());
}
});
}
}发布于 2012-09-26 17:30:23
从更新您的代码
inputTypeComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
fdo.getInputTypes().set(i, (String) inputTypeComboBox.getSelectedItem());
}
});至
final counter = i;
final JComboBox inputTypeComboBox = new JComboBox(getTypes());
final FunctionDataObject finalFDO = fdo;
inputTypeComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
finalFDO.getInputTypes().set(counter, (String) inputTypeComboBox.getSelectedItem());
}
});This链接解释了为什么只能访问内部类中的最终变量
发布于 2012-09-26 17:33:03
这将会起作用:
for (final 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));
final JComboBox inputTypeComboBox = new JComboBox(getTypes());
final int index = i;
inputTypeComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fdo.getInputTypes().set(index, (String) inputTypeComboBox.getSelectedItem());
}
});
}
} https://stackoverflow.com/questions/12598607
复制相似问题