Is calling repaint from paintComponent a good practice

后端 未结 2 1938
孤街浪徒
孤街浪徒 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: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.

提交回复
热议问题