简体   繁体   中英

stop animation in java applet at mouse click

I have the following scenario: If I have a while block in the paint() method (used for example to simulate a simple animation such as rotating a polygon, done by multiple drawing and erasing the figure), is there a way to break the while block, when clicking the mouse inside the applet?

The animation of the polygon is done without recalling the paint() method. Also would it be possible to do so if the while block looked something like this:

while (count<n)
{
    //code that draws the polygon rotating
    count++;
}

Yes there is a scenario to hold on your while loop.

The simpliest way would be to set up a variable in your classfile private boolean stopLoop=false and within your while loop check for this attribute while (!stopLoop) .

Now the MouseEvent just set the attribute stopLoop=true and you are done (if you need help, here you are How to Write a Mouse Listener

The other solution is using Swing Timer as mentioned by @camickr (see other answer). Lets assume you have a general Timer method outside your paint() method. Then you sould't use a while loop in there. I would suggest to just paint a static picture and if you want that your poligon rotates, just draw the next one, but with another angle and so on.

The idea is that you cut out your while loop into the Timer method so paint() gets called a lot of times. If you want to stop the poligon from circling around use a boolean flag for it or stop the timer. In the first case you can handle more then one polygon and each of them can be started and stopped, if you handle the boolean variables and the mouse event correct.

If you have further questions please add some more detail, or bedder show us some minimized code.

Don't use a while loop.

Instead use a Swing Timer to schedule the animation. Then you can simply start/stop the timer as required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM