在Java中,我可以在每次事件分派线程从处理输入事件返回时调用一个例程吗?
我正在开发一个 GUI,并且当下面的情况发生变化时,我有一个例程来更新显示:
void update() {
if (needsUpdating) {
// ...
needsUpdating = false;
}
}
我试图避免“过于频繁”调用 update() ——即,如果连续设置许多属性,我宁愿update() 只被调用一次。
是否可以在每个用户输入事件(键/鼠标等)之后调用 update() ?我可以手动执行此操作,但我有太多事件处理程序,而且我知道我会忘记 — Java 可以为我执行此操作吗?
I am working on a GUI, and I have a routine to update the display when things change underneath:
void update() {
if (needsUpdating) {
// ...
needsUpdating = false;
}
}
I'm trying to avoid calling update() "too often" -- ie, if many properties are set in succession I'd rather update() be called just once.
Is it possible to have update() called after every user input event -- key/mouse/etc? I could do this manually, but I have so many event handlers and I know I'll forget -- can Java do this for me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您可以全局监听用户事件,但我不推荐它,除非您找不到其他方法:
http://tips4java.wordpress.com/2009/08/30/global-event-listeners/
真正的问题似乎是您的应用程序设计:
尝试将这些“许多”建模为单独的部分,并明确定义哪个部分需要在何时触发更新。实际上,一旦您超越了最琐碎的应用程序,无论实际聆听的实现如何,都无法绕过这种模型。对于初学者,请参阅 fi
https://softwareengineering.stackexchange .com/questions/71022/what-is-good-programming-practice-for-structuring-java-project
yes, you can globally listen to user-events, though I wouldn't recommend it, except if you don't find another way:
http://tips4java.wordpress.com/2009/08/30/global-event-listeners/
The real problem seems to be your application design:
try to model those "many" into separate parts and clearly define which part need to trigger an update at which time. Actually, there's no way around such a model, whatever the implementation of the actual listening, once you are beyond the most trivial of applications. For starters, see f.i.
https://softwareengineering.stackexchange.com/questions/71022/what-is-good-programming-practice-for-structuring-java-project
您可以通过子类化 EventQueue< 来使用自己的事件队列/a>.用它控制所有事件,并在需要时进行更新。请参阅如何用自己的实现替换 AWT EventQueue 。
但我不明白你的用例:swing 为所有事件更新 gui,你为什么要自己做?
You can use your own event queue, by subclassing EventQueue. With it control all the events, and do your updates when you want. See How to replace the AWT EventQueue with own implementation.
But I don't understand your use case : swing makes gui updates for all events, why do you want do your own ?