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.
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?
See Question&Answers more detail:os