简体   繁体   中英

Java Waiting for repaint() method to finish - Don't know how to implement

I have searched through the many questions saying wait until repaint has finished but I have never found an answer that I could really implement or understand!
I don't want the code to continue when the screen has been repainted!
I have a simple function:

public static void clearScreen()
{
    panel.repaint();    
}

I can tell you now that this works!
The only problem being that it does not wait to repaint so for example:

public static void blah()
{
    drawSomething();
    clearScreen();
    drawSomething();
}

There is a good chance that both drawings would get clear from the screen. As you might be able to guess I do not want this!
I would just like to mention that !

Requesting a repaint on a component will add a repaint event to the Event Dispatch Thread which is a separate background thread that will actually call paint() later.

Depending on what you are doing in drawSomething() may happen before or after the event dispatch thread has repainted. The best thing to do is to do all of your work on the event dispatch thread by doing your "draw something" inside a call to SwingUtilities.invokeLater . Which will run your code on the event dispatch thread. All processes on the event dispatch thread are executed in the order they are submitted (usually, some repaint requests are combined etc) so the logical order of calls are preserved.

Learn more about the Event Dispatch Thread in the Oracle Java Tutorial

Swing uses a passive painting system, that is, the screen is not updated on a regular bases, but is painted as is required (or more precisely, when ever the RepaintManager thinks it should be).

You can make requests that UI be updated by calling repaint, buts it's up to the RepaintManager to decide what and when that should occur. The RepaintManager will place a repaint event on the event queue which will be processed by the Event Dispatching Thread at some time in the future.

What this basically means, is that is generally not possible to know when a paint may occur (as painting may happen for all sorts of reasons).

Take a look at Painting in AWT and Swing for more details

You could...

Employee your own buffer, onto which you paint when ever you want, but is the painted to the screen independently. You can use a BufferedImage for this. The problem with this is you're going to have to monitor the changes to the container to ensure that the buffer is the right size

You could...

Implement your own queue, which you add "commands" to, which is then processed by your paint method

The problem with this is ensuring that you lock or copy the queue before processing it

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