I create an array of JTextFields dynamically during runtime by means of a "for loop".

I addDocumentListener to each one using the same or equivalent "for loop". The code that is supposed to execute after the user edits the contents of any of these JTextFields is seemingly defined for each JTextField/DocumentListener separately.

Problem: this does not work, because the code that is executed after the user action, is in the state last seen when the last "for loop" round finished.

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
            }

        });

    }    

}
有帮助吗?

解决方案

It's because counter = limit after the for loop is completed.

Try something like this:

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();
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top