我只是根据我的需要制作了以下代码。
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JLabel;
public class RotatedLabel extends JLabel {
//we need to remember original size
private int originalWidth = 0;
private int originalHeight = 0;
//I do rotation around the center of label, so save it too
private int originX = 0;
private int originY = 0;
public RotatedLabel(String text, int horizotalAlignment) {
super(text, horizotalAlignment);
}
@Override
public void setBounds(int x, int y, int width, int height) {
//save new data
originX = x + width / 2;
originY = y + height / 2;
originalWidth = width;
originalHeight = height;
super.setBounds(x, y, width, height);
};
@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
int w2 = getWidth() / 2;
int h2 = getHeight() / 2;
double angle = -Math.PI / 2;//it's our angle
//now we need to recalculate bounds
int newWidth = (int)Math.abs(originalWidth * Math.cos(angle) + originalHeight * Math.sin(angle));
int newHeight = (int)Math.abs(originalWidth * Math.sin(angle) + originalHeight * Math.cos(angle));
g2d.rotate(angle, w2, h2);
super.paint(g);
//set new bounds
super.setBounds(originX - newWidth / 2, originY - newHeight / 2, newWidth, newHeight);
}
}