how to use a swing timer to start/stop animation

import javax.swing.Timer;

Add an attribute;

Timer timer; 
boolean b;   // for starting and stoping animation

Add the following code to frame’s constructor.

timer = new Timer(100, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent ae) {
        // change polygon data
        // ...

        repaint();
    }
});

Override paint(Graphics g) and draw polygon from the data that was modified by actionPerformed(e).

Finally, a button that start/stop animation has the following code in its event handler.

if (b) {
    timer.start();
} else {
    timer.stop();
}
b = !b;

Leave a Comment