Create Software Components 

Using Java Level 2

 

 

Course Info

Scheme

Resources

Tutorials

Java Demos

Utilities

Links


 

   Lecture 7

Graphics Methods 

Read on for an introduction to the Java Graphics class.

Graphics Class

Paint Method

Coordinate System

Drawing Lines

Drawing Rectangles

Drawing Arcs

Drawing Circles

Drawing Text

Font Class - changing the default font

Color Class - changing the current color

 


Graphics Class 

The Graphics class contains methods for drawing various graphical objects including:

  • Lines (drawLine)

  • Circles and Ellipses (drawOval and fillOval))

  • Arcs (drawArc and fillArc)

  • Polygons  (drawPolygon, fillPolygon and drawPolyLine.)

  • Rectangles (drawRect and fillRect)

  • Rounded Rectangles (drawRoundRect and fillRoundRect)

  • Raised or Lowered Rectangles (draw3DRect and fill3DRect)

  • Text (drawString)

Have a look at the Java demos below which use some of the methods of the Graphics class.

The Graphics class is extended by the Graphics2D and Graphics3D classes which can help you create some powerful applets and applications as illustrated by the The Java2D demo.

The Graphics class is contained within the awt package which is why we use the statement:-

import java.awt.Graphics;

to import the Graphics class or:-

import java.awt.*;

to import all the class held in the awt package including the Graphics class..


Paint Method

The paint method is used by applets to paint in the applet window.  Do you recall the paint method?  You used this to draw the string "Hello World Applet" to an applet window in a previous exercise. The syntax of the paint method is:-

public void paint(Graphics g) 

When you place code in the paint method you are overriding the inherited paint method.  Since the method is never explicitly called by you to be executed, you may wonder how and when it is executed.  

First, consider what the paint method is for.  You have an applet window that needs to be drawn, perhaps you have shapes in applet's drawing area too.  Each pixel in the applet window must be colored.  Say the applet window is covered up by another window.  When the applet window is shown again, all the pixels in the applet's drawing area need to be redrawn again.  

The paint method is executed to redraw all the shapes you may have in the applet's drawing area.  The paint method is executed whenever the browser decides the applet needs to be redrawn.  

You can force an applet to be redrawn by using the repaint method.  I.e.

repaint (); 

This line would force execution of your paint method.

What about the Graphics g part of the paint method?   The paint method is passed an instance of the Graphics class and by convention g is a name we give the variable that references this Graphics instance in memory.  g is a reference variable.  You can call your Graphics object reference variable something else rather than g if you choose.  Once we have a reference to a Graphics object, we can use all of the methods of that object:-.

g.drawString ....

g.drawLine...

Notice, we must use the reference variable g before the method name.  Say you call your Graphics object reference variable something other than g, say fred, then you would access the methods of fred by...

fred.drawString ....

fred.drawLine...


Coordinate System

The coordinate system in Java is a Cartesian (x, y) system.  The upper left of the screen is the point (0,00.  x is the number of pixels from the left side of the screen and y is the number of pixels from the top of the screen.  You should note that y increases as you proceed down the screen.  This is a normal coordinate system for graphics systems used in many programming languages.

Have a look at the example of a rectangle below.

Note: --  Remember, different users will have different screen resolutions, (the maximum number of pixels across and down the screen ).  Don't assume that because your graphics applet works well on your system that it will work on someone else's.  A fairly safe bet is to assume a screen resolution of 640 * 480, or write code that can adapt to different screen resolutions.

         

 


Drawing Lines

It is fairly simple to draw lines in Java using the drawLine method.  The syntax is: -

g.drawLine(int x1, int y1, int x2, int y2);

The parameters x1, y1 and x2, y2 define the end points of the line.

Let's draw part of a house.  Don't forget to name your file the same as the class name, compile the code and create a html file for the applet.  I would recommend using appletviewer rather than the browser for displaying the applet.

 

//  This applet draws part of a house
import java.awt.*;
import java.applet.*;
public class House extends Applet  {
    public void paint (Graphics g) {
        int roofx1 = 10, roofy1 = 100;
        int roofx2 = 80, roofy2 = 50;
        int roofx3 = 150, roofy3 = 100;
        g.drawLine ( roofx1, roofy1, roofx2, roofy2);
        g.drawLine ( roofx2, roofy2, roofx3, roofy3);
        g.drawLine ( roofx1, roofy1, roofx3, roofy3);
    }
}

It seems we have drawn part of a roof!

If the applet doesn't display properly, 

click the refresh button on the browser toolbar.


Drawing Rectangles

It is also fairly simple to draw rectangles  in Java using the drawRect method.  The syntax is: -

g.drawRect(int x1, int y1, int width, int height);

The parameters x1, y1 define the upper left corner of the rectangle and  width and height should be obvious.

Let's draw the next part of our house.  Add the following lines to the end of your paint method from the previous exercise.  Don't forget to recompile the code.

 int mainRectx = roofx1 + 5, mainRecty = roofy1;
 int width = roofx3 - roofx1 - 10, height = 80;
 g.drawRect ( mainRectx, mainRecty, width, height);

It's starting to look like a house, don't you think!

If the applet doesn't display properly, 

click the refresh button on the browser toolbar.

 

However, I think I would like to add fill color to my house rectangle.  All I have to do is use the fillRect method instead of the drawRect method.

g.fillRect(int x1, int y1, int width, int height);

You can see the difference below.  You will see later how to change the fill color.

If the applet doesn't display properly, 

click the refresh button on the browser toolbar.

 

Now let's add some windows and a door.  I think I will use some 3D rectangles for a change. 

The method for drawing a 3D rectangle is

g.draw3DRect(int x1, int y1, int width, int height, boolean raised);

or, if you want fill as well:-

g.fill3DRect(int x1, int y1, int width, int height, boolean raised);

To add the windows and the door, add the following lines to your paint method from the previous exercise.  The lines in bold are the ones you should concentrate on understanding.

int windowHeight = 20, windowWidth = 25;

int leftWindowx = mainRectx + 10;
int rightWindowx = mainRectx + width - windowWidth - 10;
int topWindowy = mainRecty + 10;
int lowerWindowy = mainRecty + height - windowHeight - 10;
int doorWidth = 20;
int doorHeight = 35;
int doorx = mainRectx + (width - doorWidth)/2;
int doory = mainRecty + height - doorHeight;
//draw the top left window
g.setColor(Color.yellow);
g.fill3DRect(leftWindowx,topWindowy, 
               windowWidth,windowHeight,false); 
 
//draw the top right window
g.setColor(Color.blue);
g.fill3DRect(rightWindowx,topWindowy,
               windowWidth,windowHeight,false); 
 
//draw the lower left window
g.setColor(Color.blue);
g.fill3DRect(leftWindowx,lowerWindowy,
                windowWidth,windowHeight,false); 
        
//draw the lower right window
g.fill3DRect(rightWindowx,lowerWindowy,
                 windowWidth,windowHeight,false); 
//draw the door
g.setColor(Color.gray); 
g.fill3DRect(doorx,doory,doorWidth,doorHeight,true); 

What do you think?

If the applet doesn't display properly, 

click the refresh button on the browser toolbar.

 

This time I changed the fill color of the windows and the door using the setColor method.  The method syntax is:-

g.setColor(Color c);

Where the c inside the parentheses must be a valid Color object.  You will see later how to define your own colors but for now try using some of the common colors defined by Java - Color.lightGray, Color.darkGray, Color.gray, Color.black, Color.red, Color.pink, Color.orange, Color.yellow, Color.green, Color.magenta, Color.cyan, and Color.blue.


Drawing Arcs

How about drawing a moon?  To draw an arc the drawArc or fillArc method is used,  The syntax of these methods is:- 

g.drawArc(int x1,int y1,int width,int height,int startArc,int arcAngle);

or, if you want fill:-

g.fillArc(int x1,int y1,int width,int height,int startArc,int arcAngle);

 

So if we add the following code, we should something that looks like a moon.  You may have to change your moon color from white to another color unless you change the background color of your applet.

 

int moonx = 1, moony = 10;
int moonWidth = 30, moonHeight = 30;
int arcStart = -125; int arcAngle = 200;
g.setColor (Color.white);
g.fillArc (moonx,moony,moonWidth,moonHeight,arcStart,arcAngle);

If the applet doesn't display properly, 

click the refresh button on the browser toolbar.

 

Examine the diagram below for details of the parameters of the arc methods, x1, y1, etc. 

 

 


Drawing Circles

I could have chosen to draw a sun instead of a moon shape.  The drawOval and fillOval methods can be used to draws ovals or circles.  The syntax for these methods is:-

g.drawOval(int x1, int y1, int width, int height);

or, if you want fill as well:-

g.fillOval(int x1, int y1, int width, int height);

Let's draw a sun.

 

 int sunx = 1, suny = 10;
 int sunWidth = 30, sunHeight = 30;
 g.setColor (Color.orange);
 g.fillOval ( sunx, suny, sunWidth, sunHeight );

If the applet doesn't display properly, 

click the refresh button on the browser toolbar.

 

Examine the diagram below for details of the parameters of the oval methods, x1, y1, etc. 

 


Drawing Text

I should think you are familiar with drawing text on an applet window using the drawString method. The method has the syntax-

g.drawString(String str, int x1, int y1);

Let's draw some text.

 

  g.setColor( Color.black);
  g.drawString("This is my house at night", 10,200);

If the applet doesn't display properly, 

click the refresh button on the browser toolbar.


Font Class

Perhaps you think the default font for applets is not very interesting.  Luckily we can choose some different fonts.  To do this you have to create an instance of the Font class, specifying the font name, font style and point size.  The declaration syntax for creating an instance of the Font class is;-

Font instanceName = new Font(String fontName, int style, int size);

We have...

  • instanceName which is the name of the variable that references your Font object

  • fontName which is the name of the font (i.e. 'TimesRoman')

  • style which specifies a font style such as Font.PLAIN, Font.BOLD, and Font.ITALIC

  • size which specifies the point size (how many pixels make a point depends on screen resolution)

 

Note: --  You can add the styles  Fand Font.ITALIC together to make a font both bold and italic. I.e.  Font.BOLD + Font.ITALIC

         

 

So, if I wanted my font to be 14 point, 'Arial', bold and italic I might create my Font object as follows:-

 

Font myFont = new Font("Arial",Font.BOLD + font.ITALIC, 14);

 

Once you have created a Font object you can refer to this object in your code.  The setFont method can be used to set a font.  All you have to do is give the method a reference to the Font object you created earlier.  The syntax is:-

setFont(Font aFont);

Where aFont is a reference to a font object you have create.  So, using my Font object which I created earlier, I would type:-

setFont(myFont);

 

Let's try adding the code in bold to my house code.

 

 Font myFont = new Font("Arial", Font.BOLD + Font.ITALIC, 14); 
 g.setFont (myFont);       
 g.setColor( Color.black);
 g.drawString("This is my house at night", 1,200);

If the applet doesn't display properly, 

click the refresh button on the browser toolbar.


Color Class

Do you recall at school, learning a bout the primary pigments, red, yellow and blue?  Mixing pigments gave other pigments.  A red and yellow mix would give orange; red and blue would give purple, and so on.  

There are three primary colors of light but they are red green and blue.  Just remember the term RGB.  We can get different colors by mixing these three primary colors.  Let's say we want a bright red color.  We can specify how much red, green or blue as follows by choosing a number between 0 and 255 for each color.  The number 0 specifies none of that color, the number 255 specifies the most intense amount of that color.  Let's have a few examples:-

 

255, 0, 0

means a full amount of red, no green and no  blue.  This would be bright red.

0, 255, 0

means no red, a full amount of green and no  blue.  This would be bright green

0, 0, 255

means a no red, no green and a full amount of blue.  This would be bright blue

100, 100, 0

means an amount of red, an amount of green and no blue.  This would be a yellow shade

0, 0, 0

means no red, no green and no  blue.  This would be black

255, 255, 255

means a full amount of red, a full amount of green and a full amount of blue.  This would be white

100, 100, 100

all the numbers are equal you will get some shade of gray.

This simple RGB application illustrates color numbers. 

The browser will ask you if you want to Open or Save this application.  Just open it.

 

We have seen earlier that Java comes with some pre-defined colors.  To use these pre-defined colors, just specify one of the following.

  • Color.white

  • Color.black

                          
  • Color.lightGray

  • Color.gray

  • Color.darkGray

  • Color.red

  • Color.orange

  • Color.pink

  • Color.yellow

  • Color.green

  • Color.magenta

  • Color.cyan

  • Color.blue

If find the predefined colors dull and you want to specify your own custom color, there are a few different ways. We could use the setColor method, which allows us to set the default color.  This has the syntax:-

setColor(Color c);

However, the argument requires a Color object.  So we must create a Color object - an instance of the Color class first.  The syntax for creating a Color object is;-

Color yourNameForColor = new Color(int red, int green, int blue);

Where...

  • yourNameForColor is the name of the variable that references the Color object.

  • red, green and blue are color numbers between 0 and 255

Let's create some custom colors and set each as the default in turn using lines of code like the following:-

Color myColor = new Color(100, 200, 150);

g.setColor(myColor);

 

//  This applet draws circles in different colors
import java.awt.*;
import java.applet.*;

public class Colors extends Applet  {
    public void paint (Graphics g) {
        
        Color myColor = new Color(100, 200, 150);
        g.setColor(myColor);
        g.fillOval ( 0, 10, 30, 30 );

        Color myColor2 = new Color(200, 20, 100);
        g.setColor(myColor2);
        g.fillOval ( 40, 10, 30, 30 );        
        
        Color myColor3 = new Color(100, 0, 150);
        g.setColor(myColor3);
        g.fillOval ( 80, 10, 30, 30 );

        Color myColor4 = new Color(250, 250, 0);
        g.setColor(myColor4);
        g.fillOval ( 120, 10, 30, 30 );
    }
}

 

 

If the applet doesn't display properly, 

click the refresh button on the browser toolbar.

 

Copy this code and try playing with the color numbers to see what you get.

 


That is folks!!

Now try the Graphics Methods exercise

 

  Site Home 

Java Home   

  Forum  

Course Info

Welcome

Overview

Assessment

Qualification

Scheme of Work

Assignments

Resources

Information

Blackboard

Learning Center

Web Materials

Reading

Java Demos

Utilities

Links

Lecture Materials

Tutorials & Notes

Exercises

Activities

Quizzes

 

Site Home

Top

Unit Home

ADR 2002