Java Graphics How to - Draw Ellipse with Ellipse2D.Float








Question

We would like to know how to draw Ellipse with Ellipse2D.Float.

Answer

//from w w w.  j a v a  2  s  . c  o  m
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;

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

public class MainClass extends JFrame {
  public MainClass() {
    getContentPane().add(new DrawingCanvas());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(500, 500);
    setVisible(true);
  }

  public static void main(String arg[]) {
    new MainClass();
  }
}

class DrawingCanvas extends JPanel {
  DrawingCanvas() {
    setSize(300, 300);
    setBackground(Color.white);
  }

  public void paint(Graphics g) {
    Graphics2D g2D = (Graphics2D) g;

    Graphics2D g2 = (Graphics2D) g;

    int w = getSize().width;
    int h = getSize().height;
    Ellipse2D e = new Ellipse2D.Float(w / 4.0f, h / 4.0f, w / 2.0f, h / 2.0f);
    g2.setClip(e);

    g2.setColor(Color.red);
    g2.fillRect(0, 0, w, h);

  }
}