简体   繁体   English

Java-两个repaint()函数-第一个不会立即重绘

[英]Java - two repaint() functions - the first one doesn't repaint immediately

My code: 我的代码:

...
this.mainWindow.desk.repaint();
....
function();
...
this.mainWindow.desk.repaint();
...

The first repaint is not processed immediately, but waits for the second one and then both are processed together. 第一次重涂不会立即处理,而是等待第二次重涂,然后一起处理。 How could I call an immediate repaint without waiting to the second one please? 我怎么能立即调用重新粉刷而无需等到第二次?

repaint only places a paint request on the Event Dispatch Thread's work queue. repaint仅将绘制请求放置在事件调度线程的工作队列上。 Since you are probably running your code on the Event Dispatch Thread (inside an event handler), you are blocking the processing of further work items. 由于您可能正在事件调度线程上(事件处理程序内部)运行代码,因此将阻止进一步工作项的处理。 The cleanest way to fix this would be to wrap the function call in a Runnable and pass it to EventQueue.invokeLater . 解决此问题的最干净方法是将function调用包装在Runnable ,并将其传递给EventQueue.invokeLater Then your code will be adding three separate work items to the queue: 然后,您的代码将向队列添加三个单独的工作项:

  1. a repaint request; 重涂请求;
  2. the call to function ; function的调用;
  3. another repaint request. 另一个重画请求。

Just watch out: if function contains Thread.sleep , and it seems like it does, then you'll be blocking the EDT again. 请注意:如果function包含Thread.sleep ,并且看起来确实如此,那么您将再次阻止EDT。 If you want to paint something, have it stay for a while, then paint something else, then you'll need to schedule the painting of the second image with Swing's Timer . 如果您想绘画某些东西,将其放置一会儿,然后再绘画其他东西,则需要使用Swing的Timer安排第二幅图像的绘画。

Start your function on a different thread. 在其他线程上启动函数。 If this is not feasible, look into the paintImmediately method of JComponent. 如果这不可行,请查看JComponent的paintImmediately方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM