简体   繁体   English

鼠标单击时在Java applet中停止动画

[英]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? 我有以下场景:如果我在paint()方法中有一个while块(例如用于模拟一个简单的动画,例如旋转多边形,通过多个绘图完成并擦除图形),有没有办法打破阻止时,点击小程序内的鼠标?

The animation of the polygon is done without recalling the paint() method. 完成多边形的动画而不调用paint()方法。 Also would it be possible to do so if the while block looked something like this: 如果while块看起来像这样,也可以这样做:

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

Yes there is a scenario to hold on your while loop. 是的,有一个场景可以保持你的while循环。

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) . 最简单的方法是在类文件中设置一个变量private boolean stopLoop=false并在while循环中检查此属性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 现在MouseEvent只设置了属性stopLoop=true并且你已经完成了(如果你需要帮助,这里你是如何写一个鼠标监听器

The other solution is using Swing Timer as mentioned by @camickr (see other answer). 另一个解决方案是使用@camickr提到的Swing Timer(参见其他答案)。 Lets assume you have a general Timer method outside your paint() method. 让我们假设你在paint()方法之外有一个通用的Timer方法。 Then you sould't use a while loop in there. 然后你不能在那里使用while循环。 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. 我建议只绘制静态图片,如果你想让你的poligon旋转,只需绘制下一个,但是用另一个角度等等。

The idea is that you cut out your while loop into the Timer method so paint() gets called a lot of times. 我的想法是你将while循环切换到Timer方法中,因此paint()会被调用很多次。 If you want to stop the poligon from circling around use a boolean flag for it or stop the timer. 如果你想阻止poligon盘旋,请使用布尔标志或停止计时器。 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. 如果您还有其他问题,请添加更多细节,或者bedder向我们展示一些最小化的代码。

Don't use a while loop. 不要使用while循环。

Instead use a Swing Timer to schedule the animation. 而是使用Swing Timer来安排动画。 Then you can simply start/stop the timer as required. 然后您可以根据需要简单地启动/停止计时器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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