The Java Graphics Coordinate System
To draw an object on the screen you call one of the drawing methods available in the Java Graphics class. All methods have arguments that represent coordinates in the applet coordinate system. The applet below draws a grid in a 301x301 pixel graphics window. As you can see the grid starts at (0,0) and winds up at (300,300). It differs from the cartesian coordinate system in that increasing positive y values will be located further down the chart.
The code extends the java applet class to create an applet. Java is an object-oriented programming language and a class is a template for multiple objects with similar features. The graphics class embodies all the features of a particular set of graphics. In the code, g is an instance of the class graphics or in other words, an object belonging to the generic class graphics. All of the code contained in the graphics class need not be rewritten to program g. The instance or object, g, inherits the attributes or behavior from the graphics class. The object g uses the method drawLine to draw the grid in the applet pictured below.
| 0..................................x....................................300 | |
| 0 y 300 |
The code that produces the grid is listed below. Copy it in a text editor and place it in a file called "graphics.java".
import java.awt.Graphics;
public class graphics extends java.applet.Applet {
public void paint(Graphics g) {
for (int x=0;x<=300;x+=10)
g.drawLine(x,0,x,300);
for (int y=0;y<=300;y+=10)
g.drawLine(0,y,300,y);
}
}
|
This allows us to use the Graphics methods of the
Java Abstract Windowing toolkit. We want to generate an applet . The paint method is how an applet draws objects on the screen. These loops draw the vertical and Horizontal lines on the screen |
After compiling this program we need to create an HTML page with a reference to the class file. It must run in a graphic window that is large enough to accomodate the pixels in the applet. Be sure to replace the line applet code="Hello.class" with applet code="graphics.class"
Save the HTML code in the same directory as the class file.
When you load the HTML file in your browser the applet will execute within the window.
The results should resemble what you see below.
View of the applet's output
We will use this generic HTML page to display the next group of applets.
Go to the next topic: Placing Text on an Applet