Draw a rotated rectangle - Java 2D Graphics

Java examples for 2D Graphics:Transform

Description

Draw a rotated rectangle

Demo Code

     // w  w w.  j a  v  a  2s .com

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class PE3 extends JFrame
{
     private static final long serialVersionUID = 62;

     public static void main(String arg[]) 
     {
         JFrame frame = new PE3();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
         frame.setSize(new Dimension(400,400));
         frame.pack();
         frame.setVisible(true);
       }
     
     public PE3()
     {
          super("Programming Exercise 2.3");
          JPanel panel = new DrawStuff();
          panel.setPreferredSize(new Dimension(400,400));
          add(panel);
     }
     
     class DrawStuff extends JPanel
     {
          private static final long serialVersionUID = -8;
          int nPoints = 1000;

           public void paintComponent(Graphics g) 
           {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D)g;                
                Rectangle2D.Double rect = new Rectangle2D.Double(0,0,100,100);
                rect.setRect(-rect.width/2, -rect.height/2, rect.width, rect.height);
                g2.rotate(Math.PI/4);
                g2.draw(rect);
           }
     }
}

Related Tutorials