Question

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?

Was it helpful?

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();

OTHER TIPS

The answer provided by paislee is indeed correct. You would like to add just another way to do the same thing. You can use bindings, which adds the concept of ValueHolders, variables that will store and reflect imediatley any property changes of your graphical components. It can provide a very effective way to implement MVC design pattern with Swing since the communication between Model-Controller-View is much more affective and decoupled.

JGoodies has an excellent and open source implementation for it. If you can spend sometime and want to improve your design, don't hesitate to take a look.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top