Draw Ellipse in Rectangle

To draw an Ellipse inside the rectangle, we have defined two classes Rectangle2D and Ellipse2D of package java.awt.geom.*.

Draw Ellipse in Rectangle

To draw an Ellipse inside the rectangle, we have defined two classes Rectangle2D and Ellipse2D of package java.awt.geom.*.

Draw Ellipse in Rectangle

Draw Ellipse in Rectangle

     

This section illustrates you how to draw ellipse inside the rectangle.

To draw an Ellipse inside the rectangle, we have defined two classes Rectangle2D and Ellipse2D of package java.awt.geom.*. These classes provides a rectangle and a circle respectively. 

By using draw() method of class Graphics2D, we can pass the values for the rectangle and the ellipse in the constructor of class Rectangle2D and Ellipse2D respectively to draw them.

To give the impressive and stylistic way to the outline of the specified shapes, we have used BasicStroke class. The method setStroke() sets the stroke for the Graphics2D context.

 

Here is the code of DrawRectangleAndEllipse.java 

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

public class DrawRectangleAndEllipse extends JApplet {
  final static BasicStroke stroke = new BasicStroke(2.0f);
  public void init() {
  setBackground(Color.white);
  setForeground(Color.white);
  }
  public void paint(Graphics g) {
  Graphics2D g2 = (Graphics2D) g;
  g2.setPaint(Color.red);
  int x = 6;
  int y = 8;
  g2.setStroke(stroke);
  g2.draw(new Rectangle2D.Double(x, y, 150150));
  g2.draw(new Ellipse2D.Double(x, y, 150150));
  }
  public static void main(String args[]) {
  JFrame frame = new JFrame("Draw Ellipse inside Rectangle");
  JApplet applet = new DrawRectangleAndEllipse();
  frame.getContentPane().add("Center", applet);
  applet.init();
  frame.setSize(250200);
  frame.show();
  }
}

Output will be displayed as:

Download Source Code