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

   2024-09-30 5970
核心提示:在Java中,要实现JLabel文本的旋转,可以使用Graphics2D类的rotate方法。以下是一个简单的示例:import javax.swing.*;import ja

在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方法来旋转文本。注意,在旋转文本之后,我们需要重置旋转状态,以便其他组件正常显示。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号