How to use the rotation timer to start / stop animation

Can anyone teach me how to use it swing timerwith the goal of:

I need to have a polygon that starts to animate (simple animation such as rotation) on mouse click; and stops the animation when pressed again.

I have no problem understanding how it works MouseListener, but with the actual animation. I tried to simulate the animation using the while block inside the method paint(), where I would draw, erase and redraw the polygon (for example, to simulate a rotation), but inside this time the applet will not listen to clicks. He only listened after that. I will need a rotation timer to break it when I click on the mouse.

+5
source share
3 answers
import javax.swing.Timer;

Add attribute;

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

Add the following code to the frame constructor.

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

        repaint();
    }
});

Override paint(Graphics g)and draw a polygon from data that has been modified using actionPerformed(e).

Finally, the button that starts / stops the animation has the following code in the event handler.

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

This example is controlled javax.swing.Timerby a button, while it linked responds to a mouse click. The last example changes direction for every click, but the start / stop is a direct change.

+2
source

, (Thread Dispatch Thread, EDT) while .

. ( SwingWorker http://download.oracle.com/javase/tutorial/uiswing/concurrency/worker.html)

, SwingWorker while , , .

EDT can then focus on any events (like clicks). Then you can simply use the click event to kill SwingWorker if you want to stop it.

Good luck.

+1
source

All Articles