Kcits970
Kcits970

Reputation: 642

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.

However, the animation is going on forever, so I decided to add the timer.stop() method.

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).

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,

Upvotes: 2

Views: 85

Answers (1)

trashgod
trashgod

Reputation: 205785

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. This creates an infinite loop that keeps the Timer running. At a minimum, remove the call to start() from paintComponent().

Upvotes: 3

Related Questions