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 anyt开发者_StackOverflowhing 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.
精彩评论