![]() |
![]() |
Intro. to Graphics class | |
Drawing - Lines , Rectangles | |
Drawing - Circles and Ellipse | |
Drawing - Arcs | |
Drawing - Polygons | |
Drawing - Bar Charts |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
To draw a line on the applet window, java has a method called drawLine().
This method belongs to graphics class.
The line takes two pair of coordinates as (x1,y1,x2,y2). See below syntax to understand
g.drawLine(int x1,int y1,int x2,int y2);
Where x1,y1 are two starting coordinates on x and y axis and x2,y2 are ending coordinates on x and y axis.
Program to draw a ling on applet using coordinates.
g.drawLine(20,20,90,100);
import java.awt.*; import java.applet.*; /* < applet code="DrawingLine.class" width=300 height=300> < /applet> */ public class DrawingLine extends Applet { public void paint(Graphics g) { g.drawLine(20, 20, 90, 100); } }
We can draw a rectangle in 2 different ways.
Java has drawRect() and fillRect() methods to draw a Simple Rectangle.
drawRect() - This method draws a Hollow rectangle.
fillRect() - This method draws a filled rectangle with black colour.
g.drawRect(int x, int y, int Width, int Height); g.fillRect(int x, int y, int Width, int Height);
g.drawRect(20, 10, 100, 50); g.fillRect(20, 70, 100, 50);
import java.awt.*; import java.applet.*; /* <applet code="DrawRectEx.class" width=300 height=300> </applet> */ public class DrawRectEx extends Applet { public void paint(Graphics g) { g.drawRect(20, 10, 100, 50); g.fillRect(20, 70, 100, 50); } }
Java has drawRoundRect() and fillRoundRect() methods to draw and fill rectangle with rounded corner.
Hollow Rounded Rectangle - This type of rectangle draws without filling a colour
Filled Rounded Rectangle - This type of rectangle draws with filling a colour
Syntax
g.drawRoundRect(int x,int y,int width,int height,int xbendWidth,int ybendHeight); g.fillRoundRect(int x,int y,int width,int height,int xbendWidth,int ybendHeight);
These methods takes 6 parameters, first four are similar to drawRect() method. Two extra arguments represents the width and height of angle of corners.
These extra parameters indicates how much of corners will be rounded.
import java.awt.*; import java.applet.*; /* <applet code="DrawRectEx.class" width=300 height=300> </applet> */ public class DrawRectEx extends Applet { public void paint(Graphics g) { g.drawRoundRect(20, 10, 100, 50, 20, 20); g.fillRoundRect(20, 70, 100, 50, 20, 20); } }