简体   繁体   中英

Is calling repaint from paintComponent a good practice

For some UI components in our application, we override paintComponent , which under some conditions "recursively" calls itself by invoking repaint . We use this approach to achieve high refresh rate of animations in the component.

For instance, a progress bar we use looks something like:

public class SimpleProgressBar extends JPanel {
    private boolean inProgress;

    ....

    @Override
    protected void paintComponent(Graphics g) {
        if (inProgress) {
            paintBar(g);
            repaint();
        } else {
            doSomeOtherThings();
        }
    }
}

Is this a good practice (especially in terms of performance / efficiency / CPU usage)?
Is it better to use a Timer or a background thread to repaint our components?

Is this a good practice (especially in terms of performance / efficiency / CPU usage)?

No, it is not good practice. Calling repaint from within paintComponent is bad practice because:

  1. A high frame rate like this is virtually never required
  2. The frame rate is not guaranteed (repaint does not directly call the painting method, but causes a call to this component's paint method as soon as possible ' (which may not be immediately))
  3. Places priority on painting of a single component , and can result in poor performance not only in painting of that one component, but also painting of other Components as well as response to other EDT specific tasks (eg events)

Is it better to use a Timer or a background thread to repaint our components?

Yes, using a Timer or Thread gives you much better control over the frame rate, without bogging down the EDT while doing so. Depending upon the context, a Timer runs on the EDT (as opposed to a Thread) so no dispatching to the EDT is required.

There are very few situations where overriding paintComponent is a good thing. Your situation seems to be one of them; however, it is important to remember that it is not your job to call paintComponent . What I mean by this, is that it is an office of the System to decide when to repaint certain components. This is especially evident when you drag the screen around, or when you put another screen over yours. That being said, it is very difficult to say how many times your method will be called; therein, making it difficult to say when it would be worth using that implementation.
On a side note, a background thread, as you put it, would more than likely not make it better, and Swing is notoriously not thread-safe.
I hope this helps, and best of luck to you!

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