This example draws an oval, fills the oval with red, and draws our "Hello World!" string in it in a specified font.

Let's look at the code, which can be found in Ovals.java:

Line 1 and 2 specify what classes to import. These are the, by now familiar:

        import java.awt.*;
        import java.applet.Applet;
Line 4 specifies the Ovals class as extending the Applet class. It starts by declaring a private font variable:
	public class Ovals extends Applet {
		private Font font;
The font will be used in the paint function to draw the text string.

Initializing

The init() is used to perform any one-time initialization that is necessary when the applet is first created. In this case it creates a new font of type "Helvetica", bold and point size 48:
	public void init() {
		font = new Font("Helvetica", Font.BOLD, 48);
	}

Painting

The paint method starts by painting the oval. It first draws the oval with the drawOval function, a member of the java.awt.Graphics class, which takes 4 parameters: an (x,y) coordinate and the width and height of the oval. It then sets the color of the graphics context to red. Then it fills the oval with the red color:
	public void paint(Graphics g) {
		g.drawOval(10, 10, 330, 100);
		g.setColor(Color.red);
		g.fillOval(10, 10, 330, 100);
After the oval has been drawn, the color is set back to black, the font is set to font, and the string "Hello World" is draw at coordinates (40, 75):
		g.setColor(Color.black);
		g.setFont(font);
		g.drawString("Hello World!", 40, 75);
	}
}


Back to Lecture2