How do I draw an ellipse in Java 2D?

The Ellipse2D class define an ellipse that is defined by a framing rectangle. You can create an ellipse using a double or float values. When creating an ellipse using double values use the Ellipse2D.Double class. And for the float values you can use the Ellipse2D.Float class.

package org.kodejava.awt.geom;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;

public class DrawEllipse extends JComponent {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Draw Ellipse Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(new DrawEllipse());
        frame.pack();
        frame.setSize(new Dimension(420, 400));
        frame.setVisible(true);
    }

    @Override
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        g2.setPaint(Color.RED);
        g2.setStroke(new BasicStroke(5.0f));
        g2.draw(new Ellipse2D.Double(50, 50, 250, 250));

        g2.setPaint(Color.BLUE);
        g2.fill(new Ellipse2D.Double(10, 10, 40, 40));

        g2.setPaint(Color.YELLOW);
        g2.fill(new Ellipse2D.Double(10, 300, 40, 40));

        g2.setPaint(Color.GREEN);
        g2.fill(new Ellipse2D.Double(300, 300, 40, 40));

        g2.setPaint(Color.ORANGE);
        g2.fill(new Ellipse2D.Double(300, 10, 40, 40));
    }
}

Here is the result you’ll get when you run the snippet:

Draw 2D Ellipse

Draw 2D Ellipse

Wayan

2 Comments

  1. Change your width to be smaller than your height. Think of it as stretching your circle vertically without changing the width.

    Reply
    • Yes, that’s correct. I should have said before that when we use the same value for width and height when creating an Ellipse2D it will simply give us a circle.

      Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.