Home Java Example Java Swing Graphics2D Draw Ellipse in Rectangle



Draw Ellipse in Rectangle
Posted on: October 16, 2008 at 12:00 AM
To draw an Ellipse inside the rectangle, we have defined two classes Rectangle2D and Ellipse2D of package java.awt.geom.*.

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

Related Tags for Draw Ellipse in Rectangle:
javacideclassclasses2dipviawtidpackagedefineirctorectangledrawrawsseciangleecircledeslipeinasmpssidsidejpackclesellipsespecagercproackgeodefinedsrespectrectspesppackirhallivandwtvatwssthciravfinprndomo


More Tutorials from this section

Ask Questions?    Discuss: Draw Ellipse in Rectangle  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.