Using Draw again vs Repaint

2019-09-02 18:23发布

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条回答
迷人小祖宗
2楼-- · 2019-09-02 19:23

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.

查看更多
登录 后发表回答