UserPreferences

GettingWiredWithJavaLinuxChapter9


http://dangermouse.brynmawr.edu/cs110/manual/Chapter6-10_html_m37b1c704.gif

The paint() method of an applet is specified as follows:

        public void paint (Graphics g) {

                // Put all drawing code here

        } // end of paint

The paint() method is inherited from the java.awt.Component class, since an Applet is an extension of the Component class and all objects of the Component class have a paint() method. Notice that the method has a parameter of type Graphics that is passed to it. All drawing on the applet is then done using this parameter. For instance, the command:

        g.drawString("Hello There.", 20, 50);

draws the string "Hello There" in the applet window at coordinates <20, 50>. When the system calls the paint() method (as described in the previous Chapter), it supplies a Graphics object belonging to the applet as a parameter. This object represents the graphics context that is managed by the computer's native window system. If all this sounds a bit complicated, it is.

However, from a beginner's point of view, you only need to be concerned with the fact that there is a Graphics object that paint() gets, and you can then make use of the numerous drawing operations described in the java.awt.Graphics class to draw on the applet. For the time being, just let the system worry about graphics contexts etc.

In some instances, you will need to explicitly invoke the paint() method so as to redraw an updated view of the applet. However, if you were to use the paint() method directly, you will have to supply the graphics context. While there are ways of doing this, there is a more convenient way around that you will use in this course. Any time you need the applet explicitly redrawn, just call the method, repaint().

repaint() does just that! It will clear the old contents of the applet's drawing area and then execute paint(), thereby achieving the result.

Technically speaking, and this will come in useful much later, repaint() actually identifies the graphics context, sends it to another method called, update() which in turn clears the applet's drawing area, sets the default background color, and then calls paint() with the proper Graphics object specified.

You will make extensive use of repaint() once your applet has GUI interaction. Each time following a user-event, your applet will do some processing, and then will need to respond to the user by redrawing an updated state of the applet.