Markus Lausberg
Markus Lausberg

Reputation: 12257

JTextField sends data after no change event fired for the last 2 seconds

The requirement is simple: A text field is used to get some informations from the user. If the user does not type new characters for the last 2 seconds, the text in the text field is used and submitted to some interface. the interface is not important yet.

I have to attach a propertyChange or a key listener to the textfield. Everytime the user adds a new charachter my internal string buffer is updated.

Question: i need some template or design pattern for implementing a asynch thread which is waiting for 2 seconds before an action is fired. Within the delay of 2 seconds the thread can be resetted, so the thread is waiting again 2 seconds.

So if the text field changes, the thread is resetted. if the thread waited for 2 seconds, the text field data can be used to fill the interface.

I thought about creating a 2-second-delay thread and interrupt this thread, if a text field change is detected. After the thread was interrupted a new delay-thread is fired, but i am wondering if someone knows a java class i can directly use.

Upvotes: 1

Views: 438

Answers (2)

kajacx
kajacx

Reputation: 12939

I have implemented this once, you can use java.swing.Timer for instance, just set repetition to false (fire only once) and reset it every time user enters a character (test code here)

For example:

import javax.swing.Timer;

...

private Timer t; //declare "global" timer (needs to bee seen from multiple methods)

private void init() {

    t = new Timer(2000, putYourUsefullActionListenerHere);
    //the one that will acctually do something after two seconds of no change in your field

    t.setRepeats(false); // timer fires only one event and then stops
}

private void onTextFieldChange() { //call this whenever the text field is changed
    t.restart();
    //dont worry about "restart" and no start, it will just stop and then start
    //so if the timer wasnt running, restart is same as start
}

private void terminate() {
    //if you want for any reson to interrupt/end the 2 seconds colldown prematurelly
    //this will not fire the event
    t.stop();
}

Upvotes: 2

camickr
camickr

Reputation: 324147

I have to attach a propertyChange or a key listener to the textfield

You should be using a DocumentListener. You will be notified whenever text is added/removed from the text field.

Read the section from the Swing tutorial on How to Write a Document Listener for more information and examples. The tutorial also has a section on How to Use a Swing Timer.

Upvotes: 1

Related Questions