0

我正在尝试将匿名 actionListener 添加到 JCheckBox 中,但在访问要更新值的对象时遇到了一些困难。我不断收到关于非最终版本的错误,然后当我将它们更改为最终版本时,它会抱怨其他事情。
我试图做的是下面(我删除了一些 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());
             }
        });
     }
}    
4

3 回答 3

1

更新您的代码

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

链接解释了为什么您只能访问内部类中的最终变量

于 2012-09-26T09:30:22.600 回答
1

您不能访问匿名类中的非最终变量。您可以稍微修改您的代码以解决该限制(我已经制作fdoinputTypeComboBox最终版本,并且我还制作了 的最终副本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-26T09:31:41.337 回答
1

这将起作用:

    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());
                 }
            });
         }
    }    
于 2012-09-26T09:33:03.190 回答