Is calling repaint from paintComponent a good practice

后端 未结 2 1937
孤街浪徒
孤街浪徒 2020-12-21 17:57

For some UI components in our application, we override paintComponent, which under some conditions \"recursively\" calls itself by invoking repaint

相关标签:
2条回答
  • 2020-12-21 18:35

    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!

    0 讨论(0)
  • 2020-12-21 18:50

    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.

    0 讨论(0)
提交回复
热议问题