Skip to content
Advertisement

Java Rotating Icon in JLabel

Hi I’m having a problem trying to rotate an image inside a JLabel. I got this code from StackOverflow, and I’m trying to change it a little bit so that instead of the image rotating in a Tab, it is rotating within a JLabel.

JavaScript

This is working, the image is rotating. However when i change it to this.

JavaScript

This stopped working, I’m sorry if it is a stupid question, but I don’t seem to find the answer.

Thank you

Advertisement

Answer

A painting method should only be used to paint something. It should not stop/start a Timer. So I would guess that you need get rid of the Timer logic from the painting method and then set the Timer to repeat so that continuous events are generated.

For an alternative approach check out the Animated Icon.

The Animated Icon will hold a list of Icons to display sequentially based on a Timer. When the Timer fires the next Icon in the cycle is displaye. You can configure the animation to be continuous or specify the number of cycles to display each Icon.

Note: this solution should be more efficient because it only repaints the Icon, not the entire Component.

If you don’t like the idea of creating all the Icons for the animation then you can use the Rotated Icon. With this class you set the degrees of rotation for the Icon. Then the Timer becomes completely separated from the class. Then when the Timer code fires you would increment the degrees of rotation.

Simple example using the AnimatedIcon:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement