0

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
strings95
  • 661
  • 11
  • 26
  • 1
    Please have a look at this answer [Ball Animation](http://stackoverflow.com/a/9852739/1057230) – nIcE cOw Jul 21 '13 at 08:03
  • One more [example](http://stackoverflow.com/a/17586464/1057230), my personal favourite now a days by @MadProgrammer :-) – nIcE cOw Jul 21 '13 at 08:15
  • 2
    1) For better help sooner, post an [SSCCE](http://sscce.org/). 2) Please add an upper case letter at the start of sentences. Also use a capital for the word I, and abbreviations and acronyms like JEE or WAR. This makes it easier for people to understand and help. – Andrew Thompson Jul 21 '13 at 08:20
  • 1
    Here is an [SSCCE of dynamically changing an image](http://stackoverflow.com/a/10055306/418556), & [another one](http://stackoverflow.com/a/10628553/418556) & [another one](http://stackoverflow.com/a/11330719/418556).. – Andrew Thompson Jul 21 '13 at 08:33

2 Answers2

2

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();
    }
}
tbodt
  • 16,609
  • 6
  • 58
  • 83
1

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

Joris W
  • 517
  • 3
  • 16