Credits

Wednesday, March 17, 2010

Creating Java's Shapes and Lines

Apart from setting background colors and font styles, lines and polygons can be created through Graphics class.


The following are the methods that can be used to draw lines, rectangles, ovals, circles and polygons.  The x,y are the coordinates for a given starting or ending point.


drawLine(x1,y1,x2,y2) - to draw a line from beginning point to ending point;


drawRect(x,y,width,height)- to draw an outline of a rectangle at given starting point with width and height in pixels;


fillRect(x,y,width,height)- to draw a filled and solid rectangle at given starting point with width and height in pixels;


clearRect(x,y,width,height)- to draw an "empty" rectangle at given starting point with width and height in pixels but follows  the background color unlike other commands that follow the set colors;


drawOval(x,y,width,height)- to draw an outline of a oval at given starting point with width and height in pixels;


fillOval(x,y,width,height)- to draw a filled and solid oval at given starting point with width and height in pixels;


If the width and height are the same for rectangles, then a square is formed. On the other hand, a circle is formed if same dimensions are set for ovals.


drawRoundRect(x,y,width,height,arc_width,arc_height) - to draw a round corner edge for a rectangle or square.


See the program below for given illustration.



[+/-] show/hide




import java.applet.*;
import java.awt.*;

public class GraphicsRectsCircles extends Applet {

public void paint(Graphics g)
{
//these set of lines draws a square
g.setColor(Color.blue);
g.drawLine(5,5,50,5);
g.drawLine(5,50,50,50);
g.drawLine(5,5,5,50);
g.drawLine(50,5,50,50);

g.setColor(Color.black);
g.drawRoundRect(20,20,80,80,0,0);  //draws a square 
g.drawRoundRect(120,20,80,80,10,10); //draws a square with small round corner 
g.drawRoundRect(220,20,80,80,40,40);  //draws a square with big round corner
g.drawRoundRect(320,20,80,80,80,80);  //draws a circle 

g.setColor(Color.blue);
setBackground(Color.pink);
g.fillRect(20, 160, 80, 80);   //draws a solid rectangle 
g.clearRect(40, 180, 50, 50); //draws a clear  or empty rectangle 


}

AddThis