简体   繁体   English

停止“ javax.swing.timer”不会暂停动画

[英]Stopping the “javax.swing.timer” won't pause the animation

I have created an animation with the javax.swing.timer and it seems to work fine. 我已经使用javax.swing.timer创建了一个动画,它似乎可以正常工作。

However, the animation is going on forever, so I decided to add the timer.stop() method. 但是,动画将永远持续下去,因此我决定添加timer.stop()方法。

Here's a small piece of the code: 这是一小段代码:

public void paintComponent(Graphics g) {

    super.paintComponent(g);

    g.setColor(Color.RED);
    g.fillOval(xGrid, 200, 50, 50);

    t.start();
}

public void actionPerformed(ActionEvent event) {

    if (xGrid >= 350) {

        t.stop();
    }

    xGrid++;
    repaint();
}

I'm expecting the animation to stop when the circle reaches the position of (350, 200). 我希望动画在圆到达(350,200)位置时停止。

But it doesn't. 但事实并非如此。 When I run the program, it just outputs the same as before, with the animation being slightly slower. 当我运行程序时,它的输出与以前相同,但动画稍慢一些。

This is quite confusing, can anyone please help? 这很令人困惑,任何人都可以帮忙吗?

Any help would be tremendously appreciated, 任何帮助将不胜感激,

The call to repaint() in your actionPerformed() implementation schedules a later call to paintComponent() , but your implementation of paintComponent() then calls start() on the Timer . actionPerformed()实现中对repaint()的调用安排了稍后对paintComponent()调用,但是您的paintComponent()随后在Timer上调用了start() This creates an infinite loop that keeps the Timer running. 这将创建一个无限循环,使Timer保持运行状态。 At a minimum, remove the call to start() from paintComponent() . 至少要从paintComponent()删除对start()的调用。

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

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