再次使用Draw与Repaint [英] Using Draw again vs Repaint

查看:98
本文介绍了再次使用Draw与Repaint的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚repaint方法是否做了我们自己不能做的事情.

I'm trying to figure out if the repaint method does something that we can't do ourselves.

我的意思是,这两个版本有何不同?

I mean,how are these two versions different?

public class Component extends JComponent {
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        Rectangle r = new Rectangle(0,0,20,10);
        g2.draw(r);
        r.translate(5,5);
        g2.draw(r);
    }
}

public class Component extends JComponent {
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        Rectangle r = new Rectangle(0,0,20,10);
        g2.draw(r);
        r.translate(5,5);
        repaint();
    }
}

推荐答案

第二个版本可能会导致动画非常危险且效果不佳,因为它可能导致重复调用重新绘制,这是绝对不应该做的事情.如果您需要Swing GUI中的简单动画,请使用Swing计时器来驱动动画.

The 2nd version can result in a very risky and poor animation since it can result in repaints being called repeatedly, and is something that should never be done. If you need simple animation in a Swing GUI, use a Swing Timer to drive the animation.

public class MyComponent extends JComponent {
    private Rectangle r = new Rectangle(0,0,20,10);

    public MyComponent() {
        int timerDelay = 100;
        new Timer(timerDelay, new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                r.translate(5, 5);
                repaint();
            }
        }).start();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.draw(r);
    }
}

使用repaint()是为了建议 JVM,需要对该组件进行绘制,但是绝对不能在paint或paintComponent方法中以半递归的方式调用它.可以在上面看到其用法的示例.请注意,除非在非常特殊的情况下,否则您不希望直接调用绘画方法-paint或paintComponent.

The use of repaint() is to suggest to the JVM that the component needs to be painted, but it should never be called in a semi-recursive fashion within the paint or paintComponent method. An example of its use can be seen above. Note that you don't want to call the painting methods -- paint or paintComponent directly yourselves except under very unusual circumstances.

还避免调用类Componenet,因为该名称与关键的Java核心类冲突.

Also avoid calling a class Componenet since that name clashes with a key core Java class.

这篇关于再次使用Draw与Repaint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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