“变量必须是最终的”错误阻止循环将ActionListeners添加到ArrayList

时间:2015-07-04 17:46:40

标签: java swing arraylist jbutton actionlistener

我希望能够使用for循环有效地将ActionListeners添加到java swing对象。但是,我总是遇到这个错误:Local variable i defined in an enclosing scope must be final or effectively final并且它不会添加ActionListeners。

目标:当单击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
    ...
}

1 个答案:

答案 0 :(得分:2)

不需要变量本身。对所有按钮使用相同的侦听器

public SimpleDate(Calendar calendar) {
  setDateFields(calendar);        
}

public SimpleDate(long millis) {
  Calendar calendar = Calendar.getInstance();
  calendar.setTimeInMillis(millis);
  setDateFields(calendar);      
}

private void setDateFields(Calendar calendar) {
  this.year = calendar.get(Calendar.YEAR);
  this.month = calendar.get(Calendar.MONTH);
  this.day = calendar.get(Calendar.DAY_OF_MONTH);
  this.hour = calendar.get(Calendar.HOUR_OF_DAY);
  this.minute = calendar.get(Calendar.MINUTE);
  this.second = calendar.get(Calendar.SECOND);
}

这将从按钮列表中找到Button的索引并传递该索引以从textfield列表中找到文本字段