Section 5.1
The Basic Java Applet

JAVA APPLETS ARE SMALL PROGRAMS that are meant to run on a page in a Web browser. Very little of that statement is completely accurate, however. An applet is not a complete program. It doesn't have to be small. And while many applets are meant to be used on Web pages, there are other ways to use them and good reasons to do so. A technically more correct, but not very useful, definition would say that an applet is an object that belongs to the class java.applet.Applet or to one of its subclasses. Either definition still leaves us a long way to go to really understand applets.

The Applet class, defined in the package java.applet, is really only useful as a basis for making subclasses. An object of type Applet has certain basic behaviors, but doesn't actually do anything useful. To create a useful applet, a programmer must define a subclass of the Applet class. A number of methods in Applet are defined to do nothing at all. The programmer must override at least some of these methods and give them something to do.

An applet is inherently part of a graphical user interface. It is a type of graphical component that can be displayed in a window (whether belonging to a Web browser or to some other program). When shown in a window, an applet is a rectangular area that can contain other components, such as buttons and text boxes. It can display graphical elements such as images, rectangles, and lines. And it can respond to certain "events", such as when the user clicks on the applet with a mouse. Some of the applet's behaviors -- what components it contains, what graphics it displays -- are determined by methods in the Applet class. The programmer overrides these methods in a subclass of Applet in order to make a genuinely useful applet. Methods for responding to events are defined in certain "interfaces" (see Section 4.3) that can be implemented by the applet itself or by some other object used in the applet. These methods are called to respond to events generated by user actions.

Back in Section 2.1, when you read about Java programs, you encountered the idea of a main() routine, which is never called by the programmer. The main() routine of a program is there to be called by "the system" when it wants to execute the program. The programmer writes the main routine to say what happens when the system runs the program. An applet needs no main() routine, since it is not a stand-alone program. However, many of the methods in an applet are similar to main() in that they are meant to be called by the system, and the job of the programmer is to say what happens in response to the system's calls.

An applet, just like any other object, has a "life cycle." It is created, it exists for a time, and it is destroyed. During the time it exists, its methods can be called. In the case of an applet, there are certain methods that are meant to be called at certain points during its life cycle.

An applet class does not use a constructor to do initialization. (More exactly, a constructor would not be a good place to do initialization, since some aspects of the applet, such as its height and width, have not been determined at the time the constructor is called.) Instead, just after an applet object is created, the system calls that object's init() method, which has the form

public void init() { . . . }

This method can do the task usually performed by a constructor, that is, to initialize the applet's instance variables. The init() method is also the place where other components, such as buttons, are added to the applet. There is also a complementary method called destroy() that is called by the system just before the applet object is disposed of. It takes the form

public void destroy() { . . . }

This method is called to give the applet a chance to clean up before it ceases to exist. Because of Java's automatic garbage collection, a lot of cleanup is done automatically. There are a few cases, however, where destroy() might be useful. For example, it is possible for an applet to create a separate window on the screen. You could use the applet's destroy method to close such a window.

An applet also has start() and stop() methods, which play similar roles to init() and destroy(). One difference is that while init() and destroy() are each called exactly once during the life cycle of an applet, start() and stop() can be called many times. The start() method is called once when the applet object is first created, immediately after the init() method is called. The system can choose to stop the applet by calling its stop() method and then later restart it by calling its start() method again. For example, a Web browser will typically stop an applet if the user leaves the page on which the applet is displayed, and will restart it if the user returns to that page. The stop() method will be called at least once, before the applet is destroyed. An applet that has been stopped will not receive any other events until it has been restarted. The start() and stop() methods take the form

public void start() { . . . }


public void stop() { . . . }

It is not always clear what initialization should be done in init() and what should be done in start(). Things that only need to be done once should ordinarily be done in init(). If the applet creates a separate thread to carry out some task, it is a good idea to start that thread in the start() method and stop it in the stop() method. If the applet uses a large amount of some computer resource such as memory, it might be reasonable for it to allocate that resource in its start() method and release it in its stop() method, so that the applet will not be hogging resources when it isn't even running. On the other hand, sometimes this is impossible because the applet needs to retain the resource for its entire lifetime. You'll see some examples of using start() and stop() later in this chapter.

By the way, all these methods must be declared to be public, since they are meant to be called by the system, from outside the applet. Similarly, the applet class itself should be declared to be a public class.

One of the important applet methods is paint(). The job of this method is to draw the graphical elements such as lines and rectangles displayed in the applet -- which is, remember, just a rectangular area in a window. (It does not, by the way draw GUI components such as buttons and text input boxes -- those are responsible for drawing themselves, in their own paint methods.) The paint() method in the Applet class doesn't draw anything at all, so paint() is another of those methods that the programmer can override in a subclass. The definition of this method must have the form:

          public void paint(Graphics g) {
              // draw some stuff

The parameter g of type Graphics is provided by the system when it calls the paint() method. In Java, all drawing to the screen must be done using methods provided by a Graphics object. There are many such methods. I will give a few examples as we go along, and I will discuss graphics in more detail in Section 5.

As an example, let's go the traditional route and look at an applet that displays the string "Hello World!". We'll use the paint() method to display this string. No initialization or cleanup is necessary, so none of the other methods described above are needed. The import statements at the beginning make it possible to use the short names Applet and Graphics instead of the full names of the classes java.applet.Applet and java.awt.Graphics.

         import java.awt.*;
         import java.applet.*;
         public class HelloWorldApplet extends Applet {
            // An applet that simply displays the string Hello World!
            public void paint(Graphics g) {
               g.drawString("Hello World!", 10, 30);
         }  // end of class HelloWorldApplet

The drawString() method, defined in the Graphics class, actually does the drawing. The parameters of this method specify the string to be drawn and the point in the applet where the string is to be placed. More about this later.

Now, an applet is an object, not a class. So far we have only defined a class. Where does an actual applet object come from? It is possible, of course, to create such objects:

Applet hw = new HelloWorldApplet();

This might even be useful if you are writing a program and would like to add an applet to a window you've created. Most often, however, applet objects are created by "the system." For example, when an applet appears on a page in a Web browser, it is up to the browser program to create the applet object. For an applet to appear on a Web page, the document that the browser is displaying must specify the name of the applet and its size. This specification, like the rest of the document, is written in a language called HTML. I will discuss HTML in more detail in Section 3. Here is some HTML code that will display a HelloWorld applet:

      <applet code="HelloWorldApplet.class" width=200 height=50>
         <font color="#E70000">Sorry, but your browser<br>
            doesn't support Java.</font>

and here is what this code displays:

Sorry, but your browser
doesn't support Java.

If the browser you are using does not support Java, or if you have turned off Java support, then you see the message "Sorry, but your browser doesn't support Java." Otherwise, you should see the message "Hello world!". The message is displayed in a rectangle that is 200 pixels in width and 50 pixels in height. You might not be able to see the rectangle as such, depending on the background color that your version of Java uses for the applet. But it's the rectangle that is the applet.

The applet's paint() method is called by the system just after the applet is created. It can also be called at other times. In fact, it is called whenever the contents of the applet need to be redrawn. This might happen if the applet is covered up by another window and is then uncovered. It can even happen when you scroll the window of a browser, and the applet scrolls into view. This means that outside the paint() method, you can't simply draw something on an applet and expect it to stay there! If the contents of an applet can change, then you have to use instance variables to keep track of the contents, and the paint() method must use the information in those instance variables to correctly reconstitute the contents of the applet. Otherwise, if the user scrolls your applet out of view and back, the stuff you've drawn will be gone!

As an example, let's modify the Hello World applet so that it can display the "Hello World!" message in different colors. I also want to draw the message in a big bold font. In order to do this, I'll need to work with variables of type Color and Font. The Color and Font classes will be covered in detail in Section 5. Also, the applet needs a button that the user can click on to change the color of the message. This requires an object of class Button and a way to handle the event when the button is clicked. Here's the applet:

Sorry, but your browser
doesn't support Java.

And here's the source code. The applet uses two instance variables, textColor and textFont to store the color and font to be used for the "Hello World" message. There is also an int variable, colorNum, which is used to keep track of which color is currently selected. These variables are initialized in the init() method, which also sets up the button labeled "Change Color". The actionPerformed() method is called when the user clicks on the button. (This method is part of the ActionListener interface, which is implemented by the ColoredHelloWorld1 class. This interface is in turn part of the package java.awt.event.) Here, the actionPerformed() method selects a new textColor, depending on the current value of colorNum. It then calls repaint(), a method from the Applet class that tells the system that the applet needs to be redrawn. If repaint() were not called, the color change would have no visible effect -- at least not until the applet is drawn for some other reason, such as because the user has covered it up and uncovered it again. Parts of this which seem mysterious to you now should be clear after you read the next section.

     // An applet that says "Hello World" in a big bold font, with a button to change
     // the color of the message.
     import java.awt.*;
     import java.awt.event.*;
     import java.applet.Applet;
     public class ColoredHelloWorldApplet1 extends Applet implements ActionListener {
        Color textColor;  // Color in which "Hello World" is displayed;
                          //     this changes when the user clicks on a button.     
        int colorNum;     // Keeps track of which color is displayed;
                          //     1 for red, 2 for blue, 3 for green.
        Font textFont;    // The font in which the message is displayed.
        public void init() {
               // This routine is called by the system to initialize the applet.
               // It sets up the font and initial color for the message and 
               // it adds a button to the apple for changing the message color.
            textColor =;
            colorNum = 1;
            textFont = new Font("Serif",Font.BOLD,24);
            Button bttn = new Button("Change Color");  // Create a new button.
            bttn.addActionListener(this);  // Set up the bttn to send an "action event"
                                           // to this applet when the user clicks the button.
            add(bttn);  // Add button to applet, so that it will appear on the screen.
        }  // end init()
        public void paint(Graphics g) {
              // This routine is called by the system whenever the content of the
              // applet needs to be drawn or redrawn.  It displays the message
              // "Hello World" in the proper color and font.
           g.drawString("Hello World!", 20,70);
        }  // end paint()
        public void actionPerformed(ActionEvent evt) {
              // This routine is called by the system when an "action" is performed
              // by the user, provided that the applet has been set as a "listener"
              // for such events.  This applet listens only for events from the
              // "Change Color" button, so I assume that the user has clicked
              // on that button.  The routine changes the drawing color and
              // tells the system that the applet has to be repainted.
           if (colorNum == 1) {
              colorNum = 2;
              textColor =;
           else if (colorNum == 2) {
              colorNum = 3;
              textColor =;
           else { // colorNum must be 3
              colorNum = 1;
              textColor =;
           repaint();  // Tells system that this applet needs to be redrawn
        }  // end init()
     } // end class ColoredHelloWorldApplet1

[ Next Section | Previous Chapter | Chapter Index | Main Index ]