Chapter 6: Graphics.

The Graphicsclass lets us display graphics – lines, 3 kinds of rectangles, ovals, arcs, polygons and polylines as well as text. By default, everything is displayed in black. We could use the colorclass to change the color. Also we could use the font class to change the size of text and the FontMetrics class to return the size of characters and thus align text of different size.

The AWT (Abstract Window Toolkit) provides the classes to be used to build graphics. This is the java.awt package. This package contains the Graphics class with methods to do all of the above.

An instance of the Graphics class is a rectangular area called a graphics context, in which we would store an image. This area is made up tiny squares called pixel, which are either in black or white or could be colored. The pixels are arranged in rows and columns, hence each pixel can be identified by a pair of coordinates – the x coordinate being the column and the y coordinate being the row. The arrangement is (x,y) – the x coordinate coming first followed by the y coordinate. The coordinate (0,0) is the upper left corner of the graphics context.

We would call a drawing method that exists in the Graphics class to draw a shape. We could either draw a filled shape or an unfilled shape. For example, the method for drawing an unfilled oval is:

void drawOval(int x, int y, int width, int height)

Whereas the method to draw a filled shape is:

void fillOval(int x, int y, int width, int height)

But before we start drawing, we need to have a graphics context. In fact, we need to follow the following steps in this order to draw an object:

  1. Import the java.awt.* package.
  2. Import the jpb.* package.
  3. Create an object of type DrawableFrame – the Frame is created.
  4. Call the show() method with the DrawableFrame object – to display the Frame.
  5. Call the setSize(int, int) method with the DrawableFrame object – to give the Frame a size that we desire in pixels.
  6. Create a graphics context by first creating a Graphics variable and the assign it the DrawableFrame object invoking the getGraphicsContext() method.
  7. Call your method to create the drawing with the Graphics variable.
  8. Call the repaint() method from the DrawableFrame package to make sure that the user will see the image.

The following is a program that shows the implementation of the above steps in the specified order.

import java.awt.*;

import jpb.*;

public class DrawACircle

{

public static void main(String[] args)

{

DrawableFrame df = new DrawableFrame(“A Filled Circle”);

df.show();

df. setSize(200, 200);

Graphics cir = df.getGraphicsContext();

cir.fillOval(50, 50, 75, 75); //50 & 50 are the x,y coord. 75 & 75 the width &

//height of an imaginary rectangle to enclose the circle.

df.repaint();

}

}

We could use the Graphics class to draw 3 different types of rectangles – ordinary rectangles, rounded rectangles and 3-D rectangles.

Using the method to draw an ordinary rectangle:

rec.drawRect(x, y, width, height);

The x and y are the coordinates from where to start to draw the rectangle. This point is the upper left corner of the rectangle. The width and height will give the size of the rectangle. Note: every thing must be given in pixels and must be within the bounds of the graphics context.

Using the method to draw rounded rectangle:

rec.drawRoundRect(x, y, width, height, arcWidth, arcHeight);

The x and y are the coordinates from where to start to draw the rounded rectangle. This point is the upper left corner of the rounded rectangle. The width and height will give the size of the rounded rectangle. The arcWidth is the horizontal diameter of the arc and the arcHeight is the vertical diameter of the arc. Note: every thing must be given in pixels and must be within the bounds of the graphics context.

Drawing Arcs.

Useful if we are doing pie charts. Use the method:

arc.drawArc(x, y, width, height, startAngle, arcAngle)

The first 4 parameters are similar to that for a circle (oval). The last 2 values must be given in terms of angles. They could range from 0 to 360.

Drawing Polygons:

Drawing polygons is a little bit more involved. We need to create two arrays, one containing the x coordinates and the other containing the y coordinates.

int[] xCoord = {25, 100, 250);

int[] yCoord = {100, 50, 225);

Now we call the draw method with the arrays as parameters:

cir.drawPloygon(xCoord, yCoord, xCoord.length);

Another way to achieve the same result is to invoke the Polygon class from the java.awt package in the following manner:

Polygon p = new Polygon (xCoord, yCoord, xCoord.length);

cir.drawPolygon(p);

Drawing Polylines:

This is similar to drawing a polygon but with one difference in that the last line is not connected back to the first to close the figure. It requires the use of arrays and the same amount of parameters as the polygon.

Using Colors:

All drawings are done using the default color – black. To change the color, we need to call the setColor() method with one parameter and with the object whose color needs to be changed. If you set a color at point x in your program, that color becomes the default color for the rest of the program, unless you reset it to black or something else.

When setting the color, we follow the following call:

cir.setColor(Color.red);

Java have a number of colors expressed in words such as “red”, “green”, “blue”, etc. pp 234. However, you may want to create your own color. You can do so by creating a Color object and then set the parameter with integer numbers ranging from 0 – 255 for Red, Green and Blue. Example:

Color newColor = new Color(75, 195, 200);

cir.setColor(newColor);

OR

cir.setColor(new Color(75, 195, 200));

Displaying Text:

The drawString() method lets us display text alongside shapes. It takes three arguments:

  1. The first is a string enclosed in double quotes that is to be displayed.
  2. The second is the x coordinate.
  3. The third is the y coordinate.

cir.drawString(“A Red triangle”, 310, 100);

We can also change the font face and size. The method to do this exist in the Font class – setFont(). There is only one parameter and it must be a Font object. We have a choice – either declare an object of type Font and create a new Font:

Font fancyFont = new Font(“Comic Sans MS” Font.BOLD, 18);

cir.setFont(fancyFont);

cir.drawString(“Comic Sans MS Characters look like this!”, 250, 300);

OR

cir,setFont(new Font(“Comic Sans MS” Font.BOLD, 18);

cir.drawString(“Comic Sans MS Characters look like this!”, 250, 300);

When we are creating a new font we use the new Font call with the following structure:

new Font (font name in double quote, font style, font size).

Font Name: The most universal are “Monospaced”, “Serif” or “SansSerif”. However,

others could be used but they may or may not show up. Experiment with this

to see what your computer will give you. Also note that while your

computer may give a particular font, another computer may not. If a

computer does not support a font, java will provide one of the default

fonts(mentioned above).

Font Style: There are three styles – Bold, Italics and Plain. These could be combined

with the use of the + for example Font.BOLD + Font.ITALIC.

Font Size: Font size aremeasured in points – 1 point approximately equal to 1/72 inch.

or .35 mm.

Combining Text with Graphics:

To combine Text and Graphics, you have to work on the coordinates. This might be a bit tricky and may require several trial and errors to get the position (coordinates) correct. Furthermore, if you want to display text of a filled figure, you must draw the figure first, and then write the text. If it is done in the opposite manner, the text would be hidden by the filled figure. The book gives a good example on page 238.

The FontMetrics Class:

This class is used mainly to extract data about fonts – the size (including their width, height, etc). It could be useful if you want to place text of varying size alongside each other, but you are unsure about the coordinates to use. The methods that exist in this class will return an integer value which could be used to help in this calculation.

1