I would like to keep on checking a JTextField until the field equals ten digits. When the JTextField equals ten digits then an event will happen. I want to do this without a button.

Here is what i tried to do:

JTextField get = new JTextField(10);
String a;

public className(String title)
    //Some other code here


//The class implements the Runnable class

public void run()
        a = get.getText();
        if(a.length() == 10)
            System.out.println("You entered 10 digits");

But my way does not work. How do I fix this?

Edited 4 Years Ago by godzab

Burning the CPU in an infinite loop is a very bad way to look for changes.
Add a TextListener to your JTextField. It will be called once every time the text is updated in any way, so that's the ideal place for you to check the length.
See the API documentation for details.

I mean how would I add the TextListner to the JTextField?

I'm really sorry man, that was for the AWT text field, not JTextField. I should have said add a DocumentListener. You'll find more info and an example in the API doc for JTextField. My apologies for that mistake.

Better use DocumentListener for JTextField, this will solve your problem,
search DocumentListener examples in google

Edited 4 Years Ago by softswing

This question has already been answered. Start a new discussion instead.