Rotate JLabel or ImageIcon on Java Swing
Instead of rotating the component itself, consider rotating the content of a component. This example draws a rotated image in a JPanel
.
Addendum: In the example RotatableImage.getImage()
creates a BufferedImage
directly in memory, but you can use ImageIO.read()
to obtain an image from elsewhere. BufferedImage#createGraphics()
is supported if you want to modify the image, but you probably just want to draw the unmodified image in a rotated graphics context as part of paintComponent()
.
Addendum: You're painting over the image with a rotated copy; instead, draw the image into a rotated graphics context:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String args[]) throws Exception {
JFrame frame = new JFrame("Rotation Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final BufferedImage bi = ImageIO.read(new File("img/stand.jpg"));
frame.add(new JPanel() {
@Override
public Dimension getPreferredSize() {
return new Dimension(bi.getWidth(), bi.getHeight());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.rotate(Math.PI / 4, bi.getWidth() / 2, bi.getHeight() / 2);
g2.drawImage(bi, 0, 0, null);
}
});
frame.pack();
frame.setVisible(true);
}
}
Since solutions that I found doesn't work or I don't understand them
Well, if you don't understand them, then you should post your SSCCE (http://sscce.org) demonstrating your test code. Then maybe someone will be able to explain how the code work.
I doubt you would be able to understand any new code we might post since the concepts of rotation an image or an Icon are all the same.
Since I'm positioning the image doing setBounds on the JLabel
Why are you using setBounds(). You should use a layout manager so you don't have to worry about this.
Edit:
Maybe you can use a Rotated Icon.