2015-07-04 39 views
-1

我希望能夠到的ActionListeners增加有效使用for循環的Java Swing對象。但是,我總是遇到這個錯誤:Local variable i defined in an enclosing scope must be final or effectively final,它不會添加ActionListeners。「變量必須是最後的」錯誤防止for循環從添加的ActionListeners對象的ArrayList中

目標:單擊button ArrayList中的JButton時,將清除textfield ArrayList中相應的JTextField。

ArrayList <JButton> button = new ArrayList <JButton>(); 
ArrayList <JTextField> textfield = new ArrayList <JTextField>(); 

for (int i = 0; i < 10; i++) { //Adds 10 JButtons/JTextfields to their corresponding ArrayLists 
    button.add (new JButton()); 
    textfield.add (new JTextField()); 
} 

for (int i = 0; i < 10; i++) { //Adds ActionListeners to the JButtons in the buttons ArrayList 
    button.get(i).addActionListener (new ActionListener() { 
     public void actionPerformed (ActionEvent e) { 
      textfield.get(i).setText(""); //This is where the "variable must be final" stuff comes in, for loop won't run 
     } 
    }); 
} 

public void makeFrame() { 
    ... 
    //Make JFrame and add all the JButtons and JTextFields from the ArrayLists 
    ... 
} 

回答

2

沒有必要與同一個偵聽變量itself.Replace所有按鈕

ActionListener listener = new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      textfield.get(button.indexOf(e.getSource())).setText(""); 
     } 
    }; 

    for (int i = 0; i < 10; i++) { 
     button.get(i).addActionListener(listener); 
    } 

這將從按鈕列表中找到按鈕的索引,並通過該索引來找到文本字段文本字段名單

+0

是動作監聽者是同爲相應的文本框爲button.So all.The運算需求我認爲這將是簡單和容易的 – Madhan

+0

等那麼什麼將我的ActionListener的增加? – Nick

+0

@DavidWallace是的療法是沒有必要的,我已經更新了它 – Madhan

相關問題