本文介绍了Java中的GUI线程(和SwingUtilities)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用swing制作一个简单的Java游戏,并且在按下按钮后,我的GUI会偶尔出现问题(很可能是由于线程问题),这应该会触发JPanels中的切换。

I'm making a simple game in Java using swing and am having problems with my GUI freezing up sporadically (due to threading issues most probably) after a button press that is supposed to trigger a switch in JPanels.

我发布了一个相关主题关于我正在使用的实际代码的更多细节(虽然我确实更新了倒计时并使其工作正常)。从该线程的答案,似乎使用 SwingUtilities.invokeLater() invokeAndWait()可能是我需要的解决问题,但我不确定我的代码在哪里是必要的,或者确切地知道如何实现它。

I posted a related thread here, which has more details about the actual code I'm currently using (although I did update the countdown and get that working fine). From answers to that thread, it seems like usingSwingUtilities.invokeLater() or invokeAndWait() might be what I need to solve the problem, but I'm not sure where in my code it is necessary or exactly how to implement it.

我不太了解线程和我可以使用任何帮助(最好是有些详细和一些示例代码)。如果有任何进一步的细节有用,请告诉我。

I don't know that much about threading and could use any help (preferably somewhat detailed and with some sample code) that I can get. Let me know if any further details would be useful.

推荐答案

参见:

一般来说,Eve​​nt Dispatch Thread是一个单一的线程,通过事件队列,一次处理一个。

Generally speaking, the Event Dispatch Thread is a single thread, chugging through the event queue, processing one at a time.

SwingUtilities.invokeLater(..)

将Runnable放入此队列。因此当EDT完成队列之前的所有事情时,它将由EDT处理(这就是为什么睡在队列上会阻止其他事件,如重新绘制)。从EDT本身调用invokeLater(..)是相对不寻常的,尽管有些情况下它很有用(通常作为一个黑客)。我认为在过去的6年中我没有合法使用SwingUtilities.invokeAndWait(..)。也许一次。

puts a Runnable on this queue. So it will be processed by the EDT when the EDT finishes everything on the queue before it (This is why sleeping on the queue blocks other events like repainting). It's relatively unusual to call invokeLater(..) from the EDT itself, though there are situations where it is useful (usually as a hack). I don't think I have had a legitimate use for SwingUtilities.invokeAndWait(..) in the last 6 years. Maybe once.

javax.swing.Timer 可配置为触发一次或定期触发。当它触发时,它会在EDT队列上放置一个事件。如果您需要完成计算密集型处理,请考虑使用 javax.swing.SwingWorker 在另一个线程上进行计算,并在线程中返回结果 - 安全的方式(这也相对罕见)。

javax.swing.Timer can be configured to fire once or periodically. When it fires, it puts an event on the EDT queue. If you have computationally-intensive processing that need to be done, consider using javax.swing.SwingWorker to do the computation on another thread, and give you back the result in a thread-safe manner (this is also comparatively rare).

这篇关于Java中的GUI线程(和SwingUtilities)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 11:07