2

我在运行时通过“for 循环”动态创建了一个 JTextField 数组。

我使用相同或等效的“for循环”将DocumentListener添加到每个。在用户编辑任何这些 JTextField 的内容后应该执行的代码似乎是为每个 JTextField/DocumentListener 单独定义的。

问题:这不起作用,因为在用户操作之后执行的代码处于最后一次“for 循环”回合完成时最后看到的状态。

int counter; // this is global, because otherwise needs to be final
JTextField[] a;

void calculate() {

    // ...the code sections that contains a = new JTextField[limit]; and
    // a[i] = new JTextField(); is omitted...

    for(counter = 0; counter < limit; counter++) {

        a[counter].getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                in = a[counter].getText(); 
                // this fails, because in the case of any text edits in any
                // of the JTextFields a[0...limit-1]
                // the code that executes is the one with counter = limit
            }


            public void removeUpdate(DocumentEvent e) {
                in = a[counter].getText(); // this fails
            }


            public void changedUpdate(DocumentEvent e) {
                in = a[counter].getText(); // obsolete
            }

        });

    }    

}
4

1 回答 1

4

这是因为在 for 循环完成后 counter = limit 。

尝试这样的事情:

int counter;    // this is global, because otherwise needs to be final

void calculate() {

    for (counter = 0; counter < limit; counter++) {

        a[counter].getDocument().addDocumentListener(
                new MyDocumentListener(counter)); 

    }
}

class MyDocumentListener implements DocumentListener {
    int counter;

    public MyDocumentListener(int counter) {
        this.counter = counter;
    }

    public void insertUpdate(DocumentEvent e) {
        in = a[counter].getText();
        // this fails, because in case of a text edit in any
        // of JTextFields
        // the code that executes is the one with counter = limit
    }

    public void removeUpdate(DocumentEvent e) {
        in = a[counter].getText();
    }

    public void changedUpdate(DocumentEvent e) {
        in = a[counter].getText();
    }
}
于 2013-06-06T18:30:12.897 回答