Java tutorial
import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.TexturePaint; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import javax.swing.JFrame; import javax.swing.JPanel; public class TransformDemo extends JPanel { public void init() { setBackground(Color.white); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; Rectangle rect = new Rectangle(5, 5, 200, 200); int w = getSize().width; int h = getSize().height; AffineTransform saveXform = g2.getTransform(); AffineTransform toCenterAt = new AffineTransform(); toCenterAt.translate(w / 2 - (rect.width / 2), h / 2 - (rect.height / 2)); g2.transform(toCenterAt); g2.fill(rect); g2.transform(saveXform); } public static void main(String s[]) { JFrame f = new JFrame(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); TransformDemo p = new TransformDemo(); f.getContentPane().add("Center", p); p.init(); f.pack(); f.setSize(new Dimension(300, 300)); f.show(); } }