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

    add(get);
}

//The class implements the Runnable class

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

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

Recommended Answers

All 5 Replies

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.

How would I hadd the TextListner to the JTextField?

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.