Draw Ellipse and rotate in Java

Description

The following code shows how to draw Ellipse and rotate.

Example


import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
/*w  w  w  .  j  ava 2  s  . co  m*/
import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    int x = 50;
    int y = 75;
    int width = 200;
    int height = 100;
    Shape r1 = new Ellipse2D.Float(x, y, width, height);
    for (int angle = 0; angle <= 360; angle += 45) {
      g2.rotate(Math.toRadians(angle), x + width / 2, y + height / 2);
      g2.setPaint(Color.YELLOW);
      g2.fill(r1);
      g2.setStroke(new BasicStroke(4));
      g2.setPaint(Color.BLACK);
      g2.draw(r1);
    }
  }


}

public class Main {
  public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBounds(30, 30, 450, 450);
    window.getContentPane().add(new MyCanvas());
    window.setVisible(true);
  }
}

The code above generates the following result.

Draw Ellipse and rotate in Java




















Home »
  Java Tutorial »
    Graphics »




Animation
BufferedImage
Color
Font
Gradient
Graphics Settings
Image
Mouse Draw
Print
Shape
Text
Transform