且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用摆动计时器启动/停止动画

更新时间:2023-01-26 14:06:56

 进口javax.swing.Timer中;

添加属性;

 定时器定时器;
布尔B: //启动和回采动画

添加以下code到框架的构造。

 定时器=新定时器(100,新的ActionListener(){
    @覆盖
    公共无效的actionPerformed(ActionEvent的AE){
        //改变多边形数据
        // ...        重绘();
    }
});

覆盖涂料(图形G),并从由的actionPerformed修改的数据绘制多边形(E)

最后,启动/停止动画按钮,在其事件处理程序如下code。

 如果(B){
    timer.start();
}其他{
    timer.stop();
}
B =!;

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.

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;