Using Draw again vs Repaint

荒凉一梦 提交于 2019-12-12 04:56:34

问题


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

and

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

回答1:


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.

i.e.,

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

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.

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



来源:https://stackoverflow.com/questions/29478300/using-draw-again-vs-repaint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!