Posted by Rob Camick on April 6, 2009
Icons are painted on a component in the orientation in which they where created. That is, the text in the TextIcon is painted in a left-to-right order. Image icons are painted as the image was created in the image editor. If we could change the orientation of the icon, then maybe we could create some interesting effects.
The RotatedIcon class will allow you to change the orientation of an icon by rotating it before doing the painting. RotatedIcon acts as a wrapper class. There are two ways to create a RotatedIcon:
1) You create the class by specifying the Icon and the type of rotation desired:
- down – the icon is rotated 90 degrees
- up (default) – the icon is rotated -90 degrees
- upside down – the icon is rotated 180 degrees
2) Or, you can create the class by specifying the Icon and an angle of rotation. In this case the Icon will be rotated “about its center“. The size of the Icon will be recalculated based on the angle of rotation.
Thats all there is to say about the class. So lets take a look at examples of rotated icons:
The first two examples show a JButton with a rotated TextIcon. So in effect, not only have we create a rotated icon, but we have also created a “rotated” button. Or, you may want to call this a “vertical” button.
JButton button = new JButton(); TextIcon t1 = new TextIcon(button, "Rotated Down", TextIcon.Layout.HORIZONTAL); RotatedIcon r1 = new RotatedIcon(t1, RotatedIcon.Rotate.DOWN); button.setIcon( r1 );
Note, to give the buttons a proper looking border I also altered the margins on each button using:
Insets bm = UIManager.getInsets("Button.margin"); Insets margin = new Insets(bm.left, bm.top, bm.left, bm.top); button.setMargin( margin );
The last example shows another usage of the CompoundIcon to rotate the text and image at the same time. The code to create this icon uses all the icon classes presented in this series:
JButton button = new JButton(); TextIcon ti = new TextIcon(button, "Upside Down"); ImageIcon ii = new ImageIcon(...); CompoundIcon ci = new CompoundIcon(ii, ti); RotatedIcon ri = new RotatedIcon(ci, RotatedIcon.Rotate.UPSIDE_DOWN); button.setIcon( ri );
To create an Icon rotated about its center you would use code something like:
ImageIcon ii = new ImageIcon(...); RotatedIcon ri = new RotatedIcon(ii, 45.0); JButton button = new JButton( ri );
The degrees of rotation can be dynamically changed, but the Icon will not repaint itself, so you are responsible for invoking repaint() on any component using the Icon.
Of course you can add a RotatedIcon to a label, check box or radio button just as easy. Your challenge is to play with these Icon classes to see what other interesting effects you can achieve.