import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TransformExample extends JFrame {
GraphicPanel gPanel;
public TransformExample() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
gPanel = new GraphicPanel();
getContentPane().add(gPanel);
setBounds(100, 100, 200, 200);
setVisible(true);
}
class GraphicPanel extends JPanel {
TextLabel label1;
TextLabel label2;
TextLabel label3;
protected void paintComponent(Graphics g) {
if (label1 == null) {
// lazy initilization so I have dimensions to work with
FontMetrics fm = g.getFontMetrics();
int width = getWidth();
int height = getHeight();
label1 = new TextLabel("Hi Vernon", Color.YELLOW,
20, height/2, -Math.PI/2);
String labelText = "I'm over here";
int labelLen = fm.stringWidth(labelText);
label2 = new TextLabel(labelText, Color.CYAN,
width-labelLen, height/2, -Math.PI/4);
labelText = "Standing on my head";
labelLen = fm.stringWidth(labelText);
label3 = new TextLabel(labelText, Color.ORANGE,
(width+labelLen)/2, height-20, Math.PI);
}
Graphics2D g2 = (Graphics2D)g;
g2.setBackground(Color.BLACK);
g2.clearRect(0, 0, getWidth(), getHeight());
label1.draw(g2);
label2.draw(g2);
label3.draw(g2);
}
}
class TextLabel {
private AffineTransform transform;
private Point location;
private double rotation;
private String text;
private Color color;
public TextLabel(String text, Color color, int x, int y,
double rotation) {
this.text = text;
this.color = color;
this.location = new Point(x, y);
this.rotation = rotation;
transform = new AffineTransform();
transform.translate(location.x, location.y);
transform.rotate(rotation);
}
public void draw(Graphics2D g){
// save current color and transform
AffineTransform currentTransform = g.getTransform();
Color currentColor = g.getColor();
// apply my own color and transform
g.setTransform(transform);
g.setColor(color);
// this will be left aligned at the origin
// a parameter for left/center/right alignment
// could be added easily
g.drawString(text, 0, 0);
// restore the original state
g.setColor(currentColor);
g.setTransform(currentTransform);
}
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new TransformExample();
}
});
}
}