Java Game Development Tutorial #1
Applets
Introduction to Applets
We have all seen the first program in DOS text mode...
/* Hello.java */
public class Hello {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
...but how would you like to see the classic "Hello World!" in graphic mode!
/* HelloApplet.java */
import java.applet.*;
import java.awt.*;
public class HelloApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World!", 30, 30);
}
}
Unfortunately, you can't run this with the traditional "java HelloApplet" command. This is an applet, after all, not an application. Instead, we will embed this applet in an HTML document using the following tag:
<applet code="HelloApplet.class" width="300" height="200">
</applet>
You can open this HTML file in any browser that supports the Java plug-in to view the applet, or you can use "appletviewer
[HTML file]", where
[HTML file] is the name of the file that has the applet tag. Here's what your applet should look like:

Now, to tell you how this applet works:
extends Applet - all Applets are derived from the superclass Applet
public void paint(Graphics g) - "painting" is a term that means to fill in your applet with graphics. It is called every time your applet needs to be drawn or redrawn. The Graphics object is the object that you give commands to create various shapes, pictures or words.
g.drawString("Hello, World!", 30, 30) - the drawString() method invoked on the Graphics g object. The general form of this method is "drawString(String str, int x, int y)". Thus, we see that this line draws the text "Hello, World!" at (30, 30).
NOTE: Coordinates are measured with the origin at the top-right corner of the screen, with x increasing to the right and y increasing downward.
Drawing Shapes
Hopefully, by now, you should understand how your first applet works. However, that's not all that applets can do. Here are other methods on the Graphics object that you can use to draw other things:
- void drawRect(int x, int y, int width, int height)
- void fillRect(int x, int y, int width, int height)
- void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
- void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
- void draw3DRect(int x, int y, int width, int height, boolean raised)
- void fill3DRect(int x, int y, int width, int height, boolean raised)
- void drawOval(int x, int y, int width, int height)
- void fillOval(int x, int y, int width, int height)
- void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
- void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
- void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
- void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)
- void drawLine(int x1, int y1, int x2, int y2)
- void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)
- void drawString(String str, int x, int y)
Most of these functions should be self-explanatory. If not, going to the Sun Java API documentation or a little experimentation should solve any and all questions. In any case, here's some sample code to show off some of these functions:
/* DrawDemo.java */
import java.applet.*;
import java.awt.*;
public class DrawDemo extends Applet {
public void paint(Graphics g) {
int x[] = {410, 450, 490};
int y[] = {10, 110, 10};
int y2[] = {230, 130, 230};
g.drawRect(10, 10, 80, 100);
g.fillRect(10, 130, 80, 100);
g.drawRoundRect(110, 10, 80, 100, 40, 40);
g.fillRoundRect(110, 130, 80, 100, 40, 40);
g.drawOval(210, 10, 80, 100);
g.fillOval(210, 130, 80, 100);
g.drawArc(310, 10, 80, 100, 45, 90);
g.fillArc(310, 130, 80, 100, 45, 90);
g.drawPolygon(x, y, 3);
g.fillPolygon(x, y2, 3);
g.drawLine(10, 250, 490, 290);
}
}
Running this in a 500x300 applet HTML object will get you output that looks something like:
Color
This is great and all, but it seems kinda... monochrome. So, let's jazz it up with some color!
Java has a class in the AWT package called Color, which supports many different colors. It comes with tons of predefined colors that you can access by calling Color.BLACK, Color.RED, Color.GREEN, and the like.
In addition, Color has 2 constructors:
- Color(int red, int green, int blue)
- Color(float red, float green, float blue)
Note that for the integer Color constructor, each color only goes from 0 to 255. Using combinations of these, we can make millions of colors!
Color green = new Color(0, 255, 0);
Color purple = new Color(255, 0, 255);
Color pink = new Color(255, 175, 175);
Two more constructors give us the alpha channel, aka, the transparency channel:
- Color(int red, int green, int blue, int alpha)
- Color(float red, float green, float blue, float alpha)
Lower alpha means more transparent. Higher alpha means more opaque.
Now, in order to use these colors, we'll need a few new functions:
setBackground(Color bgcolor) - this sets the background color of the applet; this is a member function of the Applet class
setColor(Color color) - this sets the current color to the given color.
All subsequent draw or fill commands will use this color; this is a member function of the Graphics class
Now, let's use these methods to Color up our drawing demo:
/* ColorDemo.java */
import java.applet.*;
import java.awt.*;
public class ColorDemo extends Applet {
Color aqua = new Color(0.0f, 0.75f, 0.75f);
Color darkyellow = new Color(0.75f, 0.75f, 0.0f);
Color cellophane = new Color(1.0f, 0.0f, 1.0f, 0.5f);
public void init() {
setBackground(Color.black);
}
public void paint(Graphics g) {
int x[] = {410, 450, 490};
int y[] = {10, 110, 10};
int y2[] = {230, 130, 230};
g.setColor(Color.RED);
g.drawRect(10, 10, 80, 100);
g.fillRect(10, 130, 80, 100);
g.setColor(Color.GRAY);
g.drawRoundRect(110, 10, 80, 100, 40, 40);
g.fillRoundRect(110, 130, 80, 100, 40, 40);
g.setColor(Color.PINK);
g.drawOval(210, 10, 80, 100);
g.fillOval(210, 130, 80, 100);
g.setColor(aqua);
g.drawArc(310, 10, 80, 100, 45, 90);
g.fillArc(310, 130, 80, 100, 45, 90);
g.setColor(darkyellow);
g.drawPolygon(x, y, 3);
g.fillPolygon(x, y2, 3);
g.setColor(Color.WHITE);
g.drawLine(10, 250, 490, 290);
g.setColor(cellophane);
g.fillRect(5, 60, 490, 120);
}
}
And our output (again, 500x300):

Much better, yes?
(Some of you might be wondering what that init() method is. Where did it come from? What does it do? It turns out that our ColorDemo class inherited this method from Applet. init(), like paint(), is automatically called by the browser. Unlike paint(), init() is generally only called once, when the applet is first loaded. Usually, you put code that you'd put in the constructors of other objects into the init() function.)
Fonts
We can manipulate colors, but often times, for text, that's not enough. Consider our Hello World example. If our text had to always look like that, it'd be incredibly dull. Fortunately, there exists the class Font, which allows us to set the fonts for our text, with this constructor:
- Font(String name, int style, int size)
Some things to note: the name argument takes the name of the font. In this case, we should use "Serif", "SansSerif", "Monospaced", "Dialog", or "DialogInput". Granted, we
could name a specific font, like "comic sans", but that's generally risky because if the font doesn't exist on the computer that's running the applet, then you cannot predict the behavior of that particular applet.
As for the style field, the options are Font.PLAIN, Font.ITALIC, and Font.BOLD. Note that these are all bitmasks, so you can use bitwise operations to combine them. For example, if you want a font that's both italicized and bolded, you can use Font.ITALIC|Font.BOLD. (Note that it doesn't make any logical sense to try to combine Font.PLAIN another font style.)
There are two methods that can be used to set a font (incidentally, they both have the same name): setFont(Font font). Applet has inherited one of these functions, and Graphics has the other. If you call Applet's version (usually in the init() method) it'll set that to the default font of the entire applet. On the other hand, if you call Graphics' version (usually in the form g.setFont(nameOfFont)), it'll use that font for the rest of the paint() method, but the next call to paint() will reset the font to the default font. Although both methods do nearly the same thing, the biggest difference between them is stylistic.
Here's an example that illustrates the use of fonts:
/* FontDemo.java */
import java.applet.*;
import java.awt.*;
public class FontDemo extends Applet {
public void init() {
setFont(new Font("Serif", Font.PLAIN, 12));
}
public void paint(Graphics g) {
g.drawString("Serif", 20, 30);
g.setFont(new Font("SansSerif", Font.PLAIN, 12));
g.drawString("SansSerif", 20, 60);
g.setFont(new Font("Monospaced", Font.PLAIN, 12));
g.drawString("Monospaced", 20, 90);
g.setFont(new Font("Dialog", Font.PLAIN, 12));
g.drawString("Dialog", 20, 120);
g.setFont(new Font("DialogInput", Font.PLAIN, 12));
g.drawString("DialogInput", 20, 150);
g.setFont(new Font("Serif", Font.PLAIN, 12));
g.drawString("Plain", 120, 30);
g.setFont(new Font("Serif", Font.BOLD, 12));
g.drawString("Bold", 120, 60);
g.setFont(new Font("Serif", Font.ITALIC, 12));
g.drawString("Italic", 120, 90);
g.setFont(new Font("Serif", Font.BOLD|Font.ITALIC, 12));
g.drawString("Bold+Italic", 120, 120);
for (int i = 1; i <= 7; i++) {
int size = 6+2*i;
g.setFont(new Font("Serif", Font.PLAIN, size));
g.drawString("Size " + size, 220, 30*i);
}
}
}
And if you run this as a 300x300 applet, you'll get this:
Applet Parameters
You know the prototype for the main() function, right? How it looks like "public static void main(String[] args)"? Yeah, we remember what that String[] args is for. It's to pass command-line arguments to your program. But there's no main() function in an applet! So what do we do? First, let's introduce a new HTML tag:
- <param name="myParam" value="foo">
Put this tag between the <applet> and </applet> tags to make it work. This tag basically creates a parameter called "myParam" with the value "foo".
This is used in conjunction with the follow method in Applet:
- String getParameter(String paramName)
In our example, if you called getParameter("myParam"), it would return "foo".
Note that all parameter names and values are Strings. If this is the case, then, how do you pass a numerical parameter? With the parse() function, of course!
int num = Integer.parseInt(getParameter("numericParam"));
The following example demonstrates one use for Applet Parameters:
/* SecretMessage.java */
import java.applet.*;
import java.awt.*;
public class SecretMessage extends Applet {
Color backColor, textColor;
Font textFont;
String message, fontName;
int fontSize, bgRed, bgGreen, bgBlue, fgRed, fgGreen, fgBlue;
public void init() {
fontName = getParameter("fontName");
fontSize = Integer.parseInt(getParameter("fontSize"));
textFont = new Font(fontName, Font.PLAIN, fontSize);
setFont(textFont);
bgRed = Integer.parseInt(getParameter("bgRed"));
bgGreen = Integer.parseInt(getParameter("bgGreen"));
bgBlue = Integer.parseInt(getParameter("bgBlue"));
backColor = new Color(bgRed, bgGreen, bgBlue);
setBackground(backColor);
fgRed = Integer.parseInt(getParameter("fgRed"));
fgGreen = Integer.parseInt(getParameter("fgGreen"));
fgBlue = Integer.parseInt(getParameter("fgBlue"));
textColor = new Color(fgRed, fgGreen, fgBlue);
setForeground(textColor);
message = getParameter("message");
}
public void paint(Graphics g) {
g.drawString(message, 50, 50);
}
}
And it's accompanying HTML:
<!--SecretMessage.html-->
<applet code="SecretMessage.class" width="350" height="100">
<param name="fontName" value="Serif">
<param name="fontSize" value="20">
<param name="bgRed" value="255">
<param name="bgGreen" value="255">
<param name="bgBlue" value="255">
<param name="fgRed" value="192">
<param name="fgGreen" value="0">
<param name="fgBlue" value="0">
<param name="message" value="This is a not-so-secret message!">
</applet>
And the output for this set of tags:

You should definitely play around with the tags to get a feel of this applet.
Conclusion
You've learned about Applets and painting. It's not quite enough to make games yet, but it's a start. As with any kind of graphics programming, the first step to doing
anything with graphics is to draw something. And now we know how to do exactly that.
Except, um, all we can draw right now are geometric figures and text. I'm sure you're eager to learn how to draw images. We'll get there in
Tutorial #3. I promise. For now, the more important thing is to learn the other important half of programming computer games: user interactivity. Next time, we're going to cover user interactivity through
keyboard and mouse events.
Homework Assignment!
(Yes, we're assigning homework. You don't have to do it if you don't want. We're not going to check. But we think the best way to learn things--especially in programming--is to get your hands dirty (figuratively speaking, of course) and just try stuff out. So you should do it anyway.)
- Modify the example in "Applet Parameters" so that instead of drawing a string, it draws a shape. Be sure to include applet parameters for the type of shape, the coordinates, the size, and whether or not it's filled.
- Create a nifty little graphic using a Java Applet that consists of shapes, text, and color. Creativity counts!