简体   繁体   中英

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. 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 . Then your code will be adding three separate work items to the queue:

  1. a repaint request;
  2. the call to 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. 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 .

Start your function on a different thread. If this is not feasible, look into the paintImmediately method of JComponent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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