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:
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Change your width to be smaller than your height. Think of it as stretching your circle vertically without changing the width.
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.