views:

220

answers:

3

I'm able to rotate an image that has been added to a JLabel. The only problem is that if the height and width are not equal, the rotated image will no longer appear at the JLabel's origin (0,0).

Here's what I'm doing. I've also tried using AffineTransform and rotating the image itself, but with the same results.

Graphics2D g2d = (Graphics2D)g;
g2d.rotate(Math.toRadians(90), image.getWidth()/2, image.getHeight()/2);
super.paintComponent(g2d);

If I have an image whose width is greater than its height, rotating that image using this method and then painting it will result in the image being painted vertically above the point 0,0, and horizontally to the right of the point 0,0.

+1  A: 

The Rotated Icon class might be what you are looking for.

camickr
+2  A: 

Use the g2d.transform() to shift the image back where it's needed. I'm just imagining what the calculation might be but I think something like:

int diff = ( image.getWidth() - image.getHeight() ) / 2;
g2.transform( -diff, diff );

BTW, you may have a problem with the label reporting its preferred size - you might need to override getPreferredSize() and account for swapping the images width and height if rotated.

staticman
+2  A: 
AffineTransform trans = new AffineTransform(0.0, 1.0, -1.0, 0.0, image.getHeight(), 0.0);
g2d.transform(trans);
g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
Maurice Perry