Search code examples
javaswingjtextfieldstring-lengthdocumentlistener

Constantly reading a String from JTextField


I've got a DocumentListener to look for any changes in the JTextField:

public class MyDocumentListener implements DocumentListener {

    static String text;

    public void insertUpdate(DocumentEvent e) {
        updateLog(e);
    }
    public void removeUpdate(DocumentEvent e) {
        updateLog(e);
    }
    public void changedUpdate(DocumentEvent e) {
        //Plain text components do not fire these events
    }

    public static String passText() {
        System.out.println("string that will be passed is: "+text);
        return text;
    }

    public void updateLog(DocumentEvent e) {

        Document doc = (Document)e.getDocument();
        int length = e.getLength();

        try {
            text = doc.getText(0, length);
        } catch (BadLocationException e1) {
            e1.printStackTrace();
        }
        System.out.println("you typed "+text);  
    }
}

And then, in the other class:

String info = MyDocumentListener.passText();

The problem is I'm getting only one character, instead of the whole String. Any suggestions?


Solution

  • You're getting the length of the change instead of the length of the document:

    int length = e.getLength(); // probably 1
    

    should be

    int length = doc.getLength();