Home E-Books Special Effects and Game Development in Java How to draw on the applet screen

Special Effects and Game Development in Java(TM) - How to draw on the applet screen with the paint() method (the Graphics class and the fillRect() method)

by Anibal Wainstein

2.1.3 How to draw on the applet screen with the paint() method (the Graphics class and the fillRect() method)

I said in section 2.0.2 that there was the init() method that was the first thing executed in a Java applet. The method that is called directly after init() in an applet is the paint() method:

public void paint(Graphics g)
With the paint() method you have full control over the applet screen thanks to the Graphics object that is included and that is connected to the screen. In the Graphics class there are methods to draw lines, circles, rectangles, texts, Images and more. You should always update a graphics applet by initializing the screen with a certain background color. This we can do with the fillRect() method that will draw a filled rectangle. First we must specify a color that the applet's "pen" will work with.  
Let us say that we want blue color in our applet and that the applet size must be 200x100 pixels:
import java.applet.*;
import java.awt.*; public class initbackground extends Applet { public void paint(Graphics g) { Color backgroundcolor = new Color(0,0,255); //setColor() in the Graphics class //sets the color of the pen g.setColor(backgroundcolor); //fillRect() fills a rectangular area with the //selected color. The method requires a horizontal //and vertical position (x and y position) g.fillRect(0,0,200,100); } }

Note that all the communication with the applet screen is done with the graphics object "g". In the example above we have first set the color on the pen that the Graphics object will use to draw on the screen, in this case blue. Next step is to draw a rectangle that covers the entire screen with the color we have chosen. We wanted an applet with the dimensions 200x100, therefore we need to draw a rectangle that is drawn to the left and above (position 0,0) and has the same dimensions as the applet.  

NOTE that if you increase the vertical position y then the rectangle is moved downwards. An increase of the horizontal position x moves the rectangle to the right.

The fillRect() method's functionality.

Now make a file of the code text above and your own HTML file where CODE="initbackground.class" and where WIDTH=200 and HEIGHT=100.

You can also click here to see the applet. 


Next Page >>