如何将DocumentListeners分配给JTextFields数组?

时间:2013-06-06 18:15:35

标签: java swing jtextfield documentlistener

我在运行时通过" for循环"动态创建一个JTextFields数组。

我将addDocumentListener添加到每个使用相同或等效的" for循环"。在用户编辑任何这些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
            }

        });

    }    

}

1 个答案:

答案 0 :(得分: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();
    }
}