从paintComponent调用repaint是一个很好的做法 [英] Is calling repaint from paintComponent a good practice

查看:107
本文介绍了从paintComponent调用repaint是一个很好的做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我们应用程序中的一些UI组件,我们覆盖 paintComponent ,在某些条件下,递归通过调用重绘。我们使用这种方法来实现组件中动画的高刷新率。

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();
        }
    }
}

这是一个好习惯(特别是在性能/效率/ CPU使用方面)?

使用计时器或后台线程到更好吗?重新粉刷我们的组件?

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?

推荐答案


这是一个好习惯吗(特别是在性能/效率/ CPU使用方面)?

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

不,这不是一个好习惯。从 paintComponent 中调用重绘是不好的做法,因为:

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


  1. 像这样的高帧速率这几乎不需要

  2. 不保证帧速率(重绘不会直接调用绘制方法,但会导致尽快调用此组件的绘制方法 '(可能不会立即))

  3. 优先绘制单个组件,并且不仅可能导致绘画效果不佳一个组件,但也绘制其他组件以及对其他EDT特定任务的响应(例如事件)

  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)




使用Timer或后台线程重新绘制我们的组件会更好吗?

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

是的,使用计时器线程可让您更好地控制帧速率,而不会在执行此操作时阻碍EDT。根据上下文,在EDT上运行 Timer (而不是线程),因此不需要调度到EDT。

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.

这篇关于从paintComponent调用repaint是一个很好的做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆