垂直旋转 JTextField [英] Rotating a JTextField vertically

查看:30
本文介绍了垂直旋转 JTextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过很多问题,询问如何以任意角度旋转 JLabel 或图像.我需要做的就是将我的文本字段旋转 90 度,但我还没有找到专门针对该角度的更简单的方法.我以为我正确地复制了答案,但我的文本字段没有旋转.

I've seen a number of questions that ask how to rotate a JLabel or image at an arbitrary angle. All I need to do is rotate my text field 90 degrees, but I haven't found an easier way specifically for that angle. I thought I copied the answers correctly, but my text field is not rotating.

这是我正在做的事情的 SSCCE:

Here's an SSCCE of what I'm doing:

import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class VerticalRotationSSCCE {

private static class VerticalTextField extends JTextField {

    private static final long serialVersionUID = 1L;

    public VerticalTextField(String text) {
        super(text);
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        int cx = getWidth() / 2;
        int cy = getHeight() / 2;
        g2.rotate(1/2 * Math.PI, cx, cy);
        super.paintComponent(g2);
    }

}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            JFrame frame = new JFrame();
            frame.getContentPane().add(new VerticalTextField("Foo"));
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }

    });
}

}

关于如何旋转组件的答案中我遗漏了什么?

What am I missing from the answers on how to rotate components?

推荐答案

你不能在不转换鼠标坐标的情况下有效地旋转交互式组件,但你可以旋转用于呈现交互组件(如 JLabel)的图形上下文,如此处.

You can't usefully rotate interactive components without also transforming the mouse coordinates, but you can rotate the graphics context to render non-interactive components like JLabel, as shown here.

在您的示例中,1/2 * Math.PI != Math.PI/2.

这篇关于垂直旋转 JTextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆