9 Graphics





AWT package provided in Java allows drawing graphics.  Graphic classes provided in AWT package has a rich collection of methods.  These methods are used to draw any graphical figure like:-

Ø  Oval
Ø  Rectangle
Ø  Square
Ø  Circle
Ø  Lines
Ø  Text using different fonts.

While drawing these figures, we can use different colors; we can paint the figures and so on.  Frame, applet and canvas are possible medium for graphics rendering.  To draw any figure, a graphic background is required.  Graphic background can be obtained by getGraphic ( ) method or when any of the following three methods are called.

Ø  repaint( ):  it is called anytime when there is need to repaint the drawing object.
Ø  update(Graphic g):  it is called automatically by the repaint ( ) method.  update method clears the drawing object and calls paint ( ) method by passing it to an object of Graphics.
Ø  paint(Graphics g):  it is called by update( ) method.  the graphics context passed to this method is used for drawing.  paint ( ) method actually draws different graphical figures.

Drawing Strings, characters and bytes
To draw or print string on to frame, drawstring ( ) method is provided in the Graphics class.  This method accepts 3 parameters.  They are:-

  • The String to be drawn.
  • x co-ordinate on the frame where string to be drawn.
  • y co-ordinate on the frame where string to be drawn.

To draw or print characters on the frame, drawChars ( ) method is provided in the Graphics class.  This method accepts 5 parameters.  They are:-

  • character array
  • offset position or starting position from where characters are to be drawn.
  • no of characters to be drawn from array.
  • x co-ordinate, where drawing to be started.
  • y co-ordinate, where drawing to be started.

To draw or print characters on the frame, drawBytes( ) method is provided in the Graphics class.  This method accepts 5 parameters.  They are:-

  • byte array
  • offset position or starting position from where bytes are to be drawn.
  • no bytes to be drawn from array.
  • x co-ordinate, where drawing to be started.
  • y co-ordinate, where drawing to be started.

Example 1 (Drawings Characters, Strings and Bytes)
import java.awt.*;
public class DrawString1 extends Frame
{
public DrawString1( )
{
super("Draw Strings, Characters,Bytes,Figures");
setSize(300,300);
setVisible(true);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Good Morning",50,150);
g.drawString("Good Afternoon",50,170);
g.drawString("Good Night",50,190);
char ch[ ] = {'a','b','c','d','e','f'};
g.drawChars(ch,2,4,100,125);
byte b[ ] ={100,101,102,103,104,105,106,107};
g.drawBytes(b,1,6,50,125);
}
public static void main(String args[])
{
new DrawString1( );
}
}

Drawing Lines and Ovals
To draw a lines we have the method called drawLine( ) it accepts 4 parameters.  They are:-
  • x-coordinate, where drawing to be started(x1).
  • y-coordinate, where drawing to be started(y1).
  • x-coordinate, where drawing to be completed(x2).
  • y-coordinate, where drawing to be completed(y2).

We can draw the colorful lines by setting required color.  The setColor( ) method is provided to set color for graphical figures.

To draw the oval drawOVal ( ) method is provided.  It accepts four parameters.  They are:-

  • x-coordinate, where drawing to be started.
  • y-coordinate, where drawing to be started.
  • Width of the oval.
  • Height of the oval.

Example2 (Drawings Lines and Ovals)
import java.awt.*;
public class DrawFigure extends Frame
{
public DrawFigure( )
{
super("Lines and Ovals");
setSize(300,300);
setVisible(true);
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.drawLine(75,75,125,75);
g.drawLine(100,50,100,100);
g.drawLine(112,55,112,95);
g.drawOval(100,150,70,40);
g.setColor(Color.cyan);
g.fillOval(200,150,50,100);
}
public static void main(String args[])
{
new DrawFigure( );
}
}
Drawing Rectangles and Rounded Rectangles
The drawRect( )method is used to draw a simple rectangle.  This method accepts four parameters.  They are:
  • x-coordinate
  • y-coordinate
  • width of the rectangle
  • height of the rectangle.
  •  
The method drawRoundRect ( ) is provided to draw the rounded rectangles.  This method takes six parameters, where first four parameters are same as drawRect( ) method the additional two parameters are:-
  • arcwidth of the rectangle
  • archeight of the rectangle.

Example3 (Drawings Rectangles and Rounded Rectangles )
import java.awt.*;
public class DrawRect extends Frame
{
public DrawRect( )
{
super("Rectanlges");
setSize(500,500);
setVisible(true);
}
public void paint(Graphics g){

g.setColor(Color.green);
g.drawRect(50,50,60,60);
g.drawRoundRect(150,50,50,50,20,40);
g.setColor(Color.red);
g.fillRect(250,140,60,60);
g.fillRoundRect(150,140,50,50,20,20);
}
public static void main(String args[])
{
new DrawRect( );
}
}

Drawing 3D rectangles and arcs
With draw3Drect( ) method we can draw 3D rectangle.  It accepts five parameters.  Where first four parameters are same as drawRect( ) method, but value of the fifth parameter decides whether rectangle to be drawn should be 3D or not.  The fifth parameters is of type Boolean, true value indicates rectangle should be 3D figure and false value indicates that it should not be a 3D figure.

The drawArc( ) method is used to draw arcs and fills it.  The drawArc( ) method accepts six parameters.  They are:-
  • x-coordinate, where drawing to be started.
  • y-coordinate, where drawing to be started.
  • Width of the arc.
  • Height of the arc.
  • Beginning of an angle.
  • Angular extent of the arc, relative to the beginning of an angle.

Drawing Polylines
The drawPolyline( ) method is used to draw Poly lines.  It accepts three parameters.  as:
  • array storing x-coordinate of the points
  • array storing y-coordinate of the points
  • total number of points to draw line.

Drawing and Filling Polygons
There are two methods provided in the Graphics class to draw polygons.  First method accepts object of polygon class and another method takes two arrays of points and total number of points.  The method drawPolygon accepts three parameters like the drawpolyline( ) method.  They are :-
  • array storing x-coordinate of the points
  • array storing y-coordinate of the points
  • total number of points to draw line.

Color control
Color control in Java is achieved through three primary colors- Red, Green and Blue.  These are primary colors of light.  Java uses RGB color model.  Object of color contains three integer or float values for three parameters. i.e. Red, Green, Blue and in range from 0-255.  Using these values we can also create our own custom colors.  Following table shows RGB values of common colors.

Color
Red
Green
Blue
White
255
255
255
Light Grey
192
192
192
Gray
128
128
128
Dark Gray
64
64
64
Black
0
0
0
Pink
255
175
175
Orange
255
200
0
Yellow
255
255
0
Magenta
255
0
255

With these color values we can create color object and set that color to draw or fill any graphical figure. For example to create pink color the syntax is:
color c = new color(255, 175, 175);

Creation of custom color is not so easy. To create a color according to your wish, we have to try many combinations of RGB values.  Hence color class has provided some predefined colors.  These color constants are used with classname prefixed to it.  they:-

color.white                  color.black                   color.orange                color.gray
color.lightgray             color.darkgray             color.red                      color.green
color.blue                    color.pink                    color.cyan                    color.magenta
color.yellow

Font Control
Fonts are used to display the text in different form.  Fonts are supported by the system.  The font class provided in the Java.awt package allows us to use various fonts to display text.  This class includes several methods.  The method getAllFont( ) returns all font supported by the system and getFontList( ) returns font names in string form which are present in the toolkit.  Toolkit class is provided by the language, which gives a platform dependent information like fonts available, screen size etc.

Class FontMetrics
This class is provided to measure various characters present in different fonts.  Measurement includes height, baseline, ascent and descent leading of a font.  This is essential, as all the characters do not occupy same space when printed, in case of characters of the same font as well as different fonts.  So the space required to print those characters need to be found out to avoid overlapping or overwriting of characters.  Thus:-
Ø  Height refers to the size of tallest character of the font.
Ø  Ascent refers to the distance from baseline to the top of the characters.
Ø  Descent refers to the distance from baseline to the bottom of the characters.
Ø  Leading refers to the extra forward spaces required to position the next character.

Paint Mode
Objects are drawn using the paint mode set.  Wherever a new object is drawn, it overwrites the original contents of the drawing object.  Similarly, when objects are drawn repeatedly, it erases previous contents of the drawing object and only new contents are visible.  To make old as well as new contents visible on the screen, a method setXORMode(Color c ) is provided in the Graphics class.

Practical Examples

Example 1( Drawing 3D Rectangles and Arcs)
import java.awt.*;
public class DrawRectArc extends Frame
{
public DrawRectArc( )
{
super("Arc and Rectangles");
setSize(300,300);
setVisible(true);
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.draw3DRect(100,230,60,30,true);
g.drawArc(200,200,100,70,30,80);
g.fillArc(210,250,260,70,30,80);
}
public static void main(String args[])
{
new DrawRectArc( );
}
}

Example2( Drawing Poly Lines)
import java.awt.*;
public class PolyLines extends Frame
{
int x1[]={50,65,95,115,135};
int y1[]={50,60,60,75,60};
int x2[]={67,82,95,120,135};
int y2[]={150,130,160,155,180};
public PolyLines( ){
super("Poly Lines");
setSize(300,300);
setVisible(true);
}
public void paint(Graphics g)
{
g.drawPolyline(x1,y1,5);
g.setFont(new Font("Times New Roman",Font.BOLD,15));
g.drawString("Poly Lines Drawing",50,180);
g.setColor(Color.red);
g.drawPolyline(x2,y2,5);
}
public static void main(String args[] ){
new PolyLines( );
}
}

Example3( Drawing Polgons)
import java.awt.*;
public class PolyFig extends Frame
{
int x1[]={50,25,40,100,80};
int y1[]={50,70,120,120,80};
int x2[]={80,30,50,150,100,170};
int y2[]={150,170,200,220,240,190};
public PolyFig( )
{
super("Poly Figures");
setSize(300,300);
setVisible(true);
}
public void paint(Graphics g)
{
g.drawPolygon(x1,y1,5);
g.setColor(Color.green);
g.fillPolygon(x2,y2,6);
}
public static void main(String args[])
{
new PolyFig( );
}
}

Example4( Color Control)
import java.awt.*;
public class ColorControl extends Frame
{
public ColorControl( )
{
super("Color Control");
setSize(300,300);
setVisible(true);
}
public void paint(Graphics g)
{
Color C1 = new Color (230,140,60);
Color C2 = new Color(30,170,150);
Color C3 = new Color(120,60,200);
Color C4 = new Color(90,210,130);
g.setColor(C1);
int red   =C1.getRed( );
int green =C1.getGreen( );
int blue  =C1.getBlue( );
g.drawString("Sandhyashree Sports Group",50,70);
String str="red :-" +String.valueOf(red);
str += ", green :-" +String.valueOf(green);
str += ", blue  :-" +String.valueOf(blue);
g.drawString(str,50,100);
C1=C1.darker( );
g.setColor(C1);
g.drawString("Sandhyashree Sports Group",50,125);
g.setColor(C2);
g.drawString("Sandhyashree Sports Group",50,150);
C2=C2.brighter( );
g.setColor(C2);
g.drawString("Sandhyashree Sports Group",50,175);
g.setColor(C3);
g.drawString("Sandhyashree Sports Group",50,200);
g.setColor(C4);
g.drawString("Sandhyashree Sports Group",50,225);
}
public static void main(String args[])
{
new ColorControl( );
}
}

Example5(Using Font)
import java.awt.*;
class FontUse extends Frame
{
public FontUse( )
{
super("Different Fonts");
setSize(400,300);
setVisible(true);
}
public void paint(Graphics g)
{
Font f=g.getFont( );
g.drawString("Default Font is ",30,50);
g.drawString(String.valueOf(f),50,75);
Font f1 = new Font("DialogInput",Font.BOLD,14);
g.setFont(f1);
g.drawString("Leena's Software ",30,125);
Font f2 = new Font("SansSerif",Font.ITALIC,16);
g.setFont(f2);
g.drawString("Leena's Software ",30,150);
Font f3 = new Font("Monospaced",Font.ITALIC+Font.BOLD,20);
g.setFont(f3);
g.drawString("Leena's Software ",30,200);
}
public static void main(String args[]){
new FontUse( );
}
}

Example6(Moving Rectangle)
import java.awt.*;
import java.applet.*;
public class RectMover extends Applet
{
public void paint(Graphics g)
{
int x=20;
for( ; x<240;x++)
{
g.setColor(Color.white);
g.drawRect(x-1,x-1,60-x,40-x);
g.setColor(Color.red);
g.drawRect(x,x,60+x,40+x);
for(int u=0;u<10000000;u++);
}
}
}

RectMover.html
<HTML>
<HEAD>
<TITLE>Moving Rectanlge</TITLE>
</HEAD>
<BODY>
<APPLET CODE = "RectMover.class" WIDTH = 400 HEIGHT =550>
</APPLET
</BODY>
</HTML>

No comments:

Post a Comment