多个调用,一个计时器

发布于 2024-10-05 15:55:07 字数 244 浏览 0 评论 0原文

我已经在这个java问题上挣扎了几个小时,我首先认为这很简单..-.-

问题是我有一个文本字段..每次用户在字段中写入一个字符时,都会调用一个方法。问题是我想实现一个计时器。时间设置为例如5秒。每次用户写入时,计时器都会重置。这意味着..只有当用户5秒内没有写任何东西时才会调用该方法..

我尝试过使用线程,计时器,计时器任务等。当我谷歌它时,你不能真正修改计时器任务,你必须启动一个新的计时器任务。每次一个。

你能帮助我吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

醉南桥 2024-10-12 15:55:07

是的,您每次都必须中止并创建一个新的 Timer/TimerTask,一旦运行就无法暂停或重置它。根据您的计时要求有多困难,您可以通过运行一个每秒左右触发一次的计时器来解决这个问题,并查看输入最后一个字符的时间来决定是否需要实际执行某些操作。

这将显着减少开销,因为您不会为每次按键启动一个新线程并结束前一个线程(这就是计时器所做的)。

另外,如果您至少有 Java 5 可供使用,请查看此问题以获得更好的替代方案:

可重置Java定时器

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

萌逼全场 2024-10-12 15:55:07

使用 DocumentListener 侦听从 JTextField 添加/删除的文本。

然后您可以使用 Swing 计时器。它有一个 restart() 方法。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文