Java

java中jlabel的文本能否实现旋转

小樊
83
2024-09-09 14:32:17
栏目: 编程语言

在Java中,要实现JLabel文本的旋转,可以使用Graphics2D类的rotate方法。以下是一个简单的示例:

import javax.swing.*;
import java.awt.*;

public class RotatedJLabel extends JLabel {
    private double angle;

    public RotatedJLabel(String text, double angle) {
        super(text);
        this.angle = angle;
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 获取当前字体的宽度和高度
        FontMetrics fm = g2d.getFontMetrics();
        int width = fm.stringWidth(getText());
        int height = fm.getHeight();

        // 计算旋转后的文本位置
        int x = (getWidth() - width) / 2;
        int y = (getHeight() + height) / 2;

        // 旋转文本
        g2d.rotate(Math.toRadians(angle), getWidth() / 2, getHeight() / 2);
        g2d.drawString(getText(), x, y);

        // 重置旋转状态
        g2d.rotate(-Math.toRadians(angle), getWidth() / 2, getHeight() / 2);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Rotated JLabel Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 300);

            RotatedJLabel label = new RotatedJLabel("Hello, World!", 45);
            frame.add(label);

            frame.setVisible(true);
        });
    }
}

在这个示例中,我们创建了一个名为RotatedJLabel的自定义JLabel类,它接受一个额外的参数angle,表示文本旋转的角度。在paintComponent方法中,我们使用Graphics2D对象的rotate方法来旋转文本。注意,在旋转文本之后,我们需要重置旋转状态,以便其他组件正常显示。

0
看了该问题的人还看了