-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
...
}
是動作監聽者是同爲相應的文本框爲button.So all.The運算需求我認爲這將是簡單和容易的 – Madhan
等那麼什麼將我的ActionListener的增加? – Nick
@DavidWallace是的療法是沒有必要的,我已經更新了它 – Madhan