sonti yo
sonti yo

Reputation: 61

Why does my RotateTransition throw errors after it runs for the first time?

Warning: This is my first time using threads and my first time trying out an animation. Please bear with me.

I want to rotate an ImageView. I set up a thread for it:

public class ThreadAnimation extends Thread
{
    private ImageView iv;
    private RotateTransition rt;

    public ThreadAnimation(ImageView iv)
    {
            this.iv = iv;
    }

    @Override
    public void run()
    {
        while (true)
        {
            RotateTransition r = new RotateTransition();
            r.setToAngle(360);
            r.setCycleCount(1);
            r.setDuration(Duration.millis(300));
            r.setNode(iv);
            r.play();

            try
            {
                sleep(100);
            } catch (InterruptedException e)
            {
                return;
            }
        }
    }

}

I call this inside my controller class, upon pressing a Button.

animation.setOnAction(new EventHandler<ActionEvent>()
{
    @Override
    public void handle (ActionEvent abschicken)
    {
        ThreadAnimation thread = null;      //ANIMATION PIZZA
        if (thread == null)
        {
            thread = new ThreadAnimation(olivenview);
            thread.start();
        }
    }
});

My ImageView olivenview will rotate just like I wanted it to. However it takes quite a long time until it seems to stop (I can see it because the button triggering it still looks triggered for a while) and when I go ahead to press it a second time afterwards, I get a nonstop error stream with a lot of null pointer exceptions. I am very clueless, can anyone help me out? Is this due to my Thread Setup or does the problem lie somewhere else (in code that I didn't post here)?

Upvotes: 0

Views: 30

Answers (1)

staad
staad

Reputation: 836

I believe you do not need threads for this. Notice the .play() method returns immediately and the animation will run in the background.

That being said, try this.

...
//Create your rotation
final RotateTransition r = new RotateTransition();
r.setToAngle(360);
r.setCycleCount(1);
r.setDuration(Duration.millis(300));
r.setNode(iv);

//When the button is pressed play the rotation. Try experimenting with .playFromStart() instead of .play()
button.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent action) {
        r.play();
    }
});

...

On an other note I recommend switching to java 8 so that you can use lambda expressions instead of the anonymous class!

Upvotes: 1

Related Questions