Multiple calls, one timer

I've been struggled this java problem for some hours, which i first thought was quite easy.. -.-

The problem is that i have a textfield.. Every time the user writes a character in the field, a method is invoked. The thing is that i want to implement a timer. The time is set to for example 5 seconds. Every time the user writes, the timer resets. That means.. The method will only be invoked if the user havent wrote anything for 5 seconds..

I've tried using thread, timer, timertask etc. As i google it you cant really modify a timertask, you have to start a new one every time.

Can you help me?


Yes, you have to abort and create a new Timer/TimerTask each time, there is no way to pause or reset it, once it is running. Depending on how hard your timing requirements are, you could work around this by running a timer that fires once every second or so and look at the time the last character was entered to decide if you need to actually do something.

This will reduce the overhead significantly, because you will not start a new Thread and end the previous one (this is what Timer does) for every keypress.

Also, please have a look at this question for a better alternative, if you have at least Java 5 at your disposal:

Resettable Java Timer

Use a DocumentListener to listen for text being added/removed from the JTextField.

Then you can use a Swing Timer. It has a restart() method.

Need Your Help

Rhino mocks and objects created in using statements

c# mocking rhino-mocks using-statement

Most of the time when we use Rhino mocks it works well, but we have problems mocking objects created using the using statements.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.