Dynamic graphic programming (Animation)

孤街浪徒 提交于 2019-12-12 01:15:03

问题


I am trying to code a simple animation like a moving circle. I have tried using getGraphics() and work with that but it's not dynamic and it's painted for just one time

So please help me and guide me to code a dynamic graphic program.

I mean for example defining a function and every time when it called, it draws a line on a label.


回答1:


Here is how to make a growing rectangle:

public class MovingRectangle extends JPanel {
    private Timer timer = new Timer(500, new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            rectWidth += 100;
            repaint();
        }
    };

    private int rectWidth = 100;

    public void paintComponent(Graphics g) {
         super.paintComponent(g);
         g.drawRect(0, 0, 100. rectWidth);
    }

    public void start() {
        timer.start();
    }

    public void stop() {
        timer.stop();
    }

    public void reset() {
        rectWidth = 100;
        repaint();
    }
}



回答2:


you should override the paintComponent(Graphic g). This method is called every time the repaint() is called, so you should periodic calling that method.

You should also set DoubleBuffering on true: setDoubleBuffered(true) It will prevent possible flicker of your animation



来源:https://stackoverflow.com/questions/17770249/dynamic-graphic-programming-animation

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