Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use a swing timer to start/stop animation

Could someone teach me how to use a swing timer with the following purpose:

I need to have a polygon that begins being animated(simple animation such as rotating) when I click the mouse; and stops animating when I click again.

I do not have problems understanding the way the MouseListener works, but with the actual animation. I tried simulating the animation with a while block inside the paint() method where I would draw, erase and redraw the polygon(to simulate a rotation for example), but inside the while, the applet would not listen to the clicks. It would listen only after the while. I would need the swing timer to break the while when I click the mouse.

like image 779
biggdman Avatar asked Nov 10 '11 23:11

biggdman


2 Answers

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;
like image 146
wannik Avatar answered Oct 05 '22 21:10

wannik


This example controls a javax.swing.Timer using a button, while this related example responds to a mouse click. The latter example reverses direction on each click, but start/stop is a straightforward alteration.

like image 42
trashgod Avatar answered Oct 05 '22 20:10

trashgod