2012-09-26 33 views
0

我想添加一個匿名actionListener到JCheckBox,但有一些困難訪問我想更新值的對象。我不斷收到關於非最終的錯誤,然後當我將它們改爲最終時,它會抱怨其他事情。
什麼即時試圖做的是下面(我已經刪除了一些GUI代碼,使其更易於閱讀):jquckbox上的actionListener

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

我認爲這個問題隱藏在沒有提供的代碼中,爲了更快地發佈[SSCCE](http://sscce.org/)以獲得更好的幫助,代碼概念中可能會出現錯誤,而不是如何爲匿名設置最終指示符聽衆 – mKorbel

回答

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

工作得很好,非常感謝! – user1584120

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

This鏈接解釋了爲什麼您只能訪問內部類中的最終變量

+0

'我'也需要是最終的。 – assylias

+0

謝謝@assylias我已經更新了它現在 – RNJ

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