如何使用摆动计时器开始/停止动画 [英] how to use a swing timer to start/stop animation
问题描述
有人可以教我如何使用 swing timer
用于以下目的:
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.
我在理解 MouseListener
的工作方式方面没有问题,但是对于实际的动画.我尝试在 paint()
方法中使用 while 块模拟动画,我将在其中绘制、擦除和重绘多边形(例如模拟旋转),但在 while 中,小程序不会听点击.它只会在一段时间后听.当我点击鼠标时,我需要摆动计时器来打破时间.
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.
推荐答案
import javax.swing.Timer;
添加属性;
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();
}
});
覆盖paint(Graphics g)
并从actionPerformed(e)
修改的数据中绘制多边形.
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;
这篇关于如何使用摆动计时器开始/停止动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!