> ### Section 6.1
> The Basic Java Applet and JApplet

> 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 applets are generally meant to be used on Web pages, there are other ways to use them. A technically more correct, but not very useful, definition would say simply 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.

> 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.

> 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. It's just a blank area on the screen that doesn't respond to any events. To create a useful applet, a programmer must define a subclass that extends the `Applet` class. There are several methods in the `Applet` class that are defined to do nothing at all. The programmer must override at least some of these methods and give them something to do.

> Back in Section 2.1, when you first learned about Java programs, you encountered the idea of a `main()` routine, which is not meant to be called by the programmer. The `main()` routine of a program is there to be called by "the system" when it needs 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.

> In this section, we'll look at a few of the things that applets can do. We'll spend the rest of this chapter and the next filling in the details.

> One of the methods that is defined in the `Applet` class to do nothing is the `paint()` method. You've already encountered this method briefly in Section 3.7. The `paint()` method is called by the system when the applet needs to be drawn. In a subclass of `Applet`, the `paint()` method can be redefined to draw various graphical elements such as rectangles, lines, and text on the applet. 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 of any kind is done using methods provided by a `Graphics` object. There are many such methods. I will discuss graphics in more detail in Section 3.

> As a first example of an applet, 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. 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`. (See Section 4.5 for a discussion of "packages," such as `java.awt` and `java.applet`.)

>              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, "the system" means the Web browser. It is up to the browser program to create the applet object and to add it to a Web page. The Web browser, in turn, gets instructions about what is to appear on a given Web page from the source document for that page. For an applet to appear on a Web page, the source document for that page 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 2. Here is some HTML code that instructs a Web browser to display a `HelloWorldApplet`:

>           <center>
>           <applet code="HelloWorldApplet.class" width=200 height=50>
>           </applet>
>           </center>

> and here is the applet that this code displays:

> (Applet "HelloWorldApplet" would be displayed here
> if Java were available.)

> If you are viewing this page with a web browser that supports Java, 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 shouldn't be able to see the rectangle as such, since by default, an applet has a background color that is the same as the color of the Web page on which it is displayed. (This might not actually be the case in your browser.)

> The Applet class defines another method that is essential for programming applets, the `init()` method. This method is called just after the applet object has been created and before it appears on the screen. Its purpose is to give the applet a chance to do any necessary initialization. Again, this method is called by the system, not by your program. Your job as a programmer is just to provide a definition of the `init()` method. The definition of the method must have the form:

>              public void init() {
>                 // do initialization
>              }

> (You might wonder, by the way, why initialization is done in the `init()` method rather than in a constructor. In fact, it is possible to define a constructor for your applet class. To create the applet object, the system calls the constructor that has no parameters. You can write such a constructor for an applet class and can do initializations in the constructor as well as in the `init()` method. The most significant difference is that when the constructor is called, the size of the applet is not available. By the time `init(),` is called, the size is known and can be used to customize the initialization according to the size. In general, though, it is customary to do applet initialization in the `init()` method.)

> Suppose, for example, that we want to change the colors used by the HelloWorldApplet. An applet has a "background color" which is used to fill the entire area of the applet before any other drawing is done, and it has a "foreground color" which is used as the default color for drawing in the applet. It is convenient to set these colors in the `init()` method. Here is a version of the HelloWorldApplet that does this:

> (Applet "HelloWorldApplet2" would be displayed here
> if Java were available.)

> and here is the source code for this applet, including the `init()` method:

>              import java.awt.*;
>              import java.applet.*;

>              public class HelloWorldApplet2 extends Applet {

>                 public void init() {
>                        // Initialize the applet by setting it to use blue
>                        // and yellow as background and foreground colors.
>                    setBackground(Color.blue);
>                    setForeground(Color.yellow);
>                 }

>                 public void paint(Graphics g) {
>                    g.drawString("Hello World!", 10, 30);
>                 }

>              }  // end of class HelloWorldApplet2

> ### JApplets and Swing

> The AWT (Abstract Windowing Toolkit) has been part of Java from the beginning, but, almost from the beginning, it has been clear that the AWT was not powerful or flexible enough for writing complex, sophisticated applications. This does not prevent it from being useful -- especially for applets, which are generally not as complex as full-scale, independent applications. The Swing graphical user interface library was created to address the problems with the AWT. With the release of Java version 1.2, Swing became an official part of Java. (Versions of Java starting with 1.2 are also called, rather confusingly, "Java 2.") There are still good reasons to write applets based on the AWT, such as the lack of support in many Web browsers for Java 2. However, at this point, anyone writing a stand-alone graphical application in Java should almost certainly be using Swing, and it is Swing that I will concentrate on in this book. If you want to write applets using the AWT, you might want to look at the previous version of this book, which can be found on the web at http://math.hws.edu/eck/cs124/javanotes3/.

> The classes that make up the Swing library can be found in the package `javax.swing`. Swing includes the class `javax.swing.JApplet` to be used as a basis for writing applets. `JApplet` is actually a subclass of `Applet`, so JApplets are in fact Applets in the usual sense. However, JApplets have a lot of extra structure that plain Applets don't have. Because of this structure, the painting of a JApplet is a more complex affair and is handled by the system. So, when you make a subclass of `JApplet` you should not write a `paint()` method for it. As we will see, if you want to draw on a JApplet, you should add a component to the applet to be used for that purpose. On the other hand, you can and generally should write an `init()` method for a subclass of JApplet.

> In this book, I will use a plain Applet in only a few examples. In almost all cases, I will use a JApplet even where a plain applet might make more sense (that is, when the applet is just being used as a simple drawing surface).

> Let's take a look at a simple JApplet that uses Swing. This applet demonstrates some of the basic ideas of GUI programming. Although you won't understand everything in it at this time, it will give you a preliminary idea of how things work.

> GUI programs use "components" such as buttons to allow interaction with the user. Our sample applet contains a button. In fact, the button is the only thing in the applet, and it fills the entire rather small applet. Here's our sample JApplet, which is named `HelloSwing`:

> (Applet "HelloSwing" would be displayed here
> if Java were available.)

> If you click this button, a new window will open with a message and an "OK" button. Click the "OK" button to dismiss the window.

> The button in this applet is an object that belongs to the class `JButton` (more properly, `javax.swing.JButton`). When the applet is created, the button must be created and added to the applet. This is part of the process of initializing the applet and is done in the applet's `init()` method. In this method, the button is created with the statement:

>                 JButton bttn = new JButton("Click Me!");

> The parameter to the constructor specifies the text that is displayed on the button. The button does not automatically appear on the screen. It has to be added to the applet's "content pane." This is done with the statement:

>                 getContentPane().add(bttn);

> Once it has been added to the applet, a `JButton` object mostly takes care of itself. In particular, it draws itself, so you don't have to worry about drawing it. When the user clicks the button, it generates an event. The applet (or, in fact, any object) can be programmed to respond to this event. Event-handling is the major topic in GUI programming, and I will cover it in detail later. But in outline, it works like this: The type of event generated by a button is called an `ActionEvent`. For the applet to respond to an event of this type, it must define a method

>                 public void actionPerformed(ActionEvent evt) { . . . }

> Furthermore, the button must be told that the applet will be "listening" for action events from the button. This is done by calling one of the button object's instance methods, `addActionListener()`, in the applet's `init()` method.

> What should the applet do in its `actionPerformed()` method? When the user clicks the button, we want a message window to appear on the screen. Fortunately, Swing makes this easy. The class `swing.javax.JOptionPane` has a static method named `showMessageDialog()` that can be used for this purpose, so all we have to do in `actionPerformed()` is call that method.

> Given all this, you can understand a lot of what goes on in the source code for the `HelloSwing` applet. This example shows several aspects of applet programming: An `init()` method sets up the applet and adds components, the components generate events, and event-handling methods say what happens in response to those events. Here is the source code:

>        // An applet that appears on the page as a button that says
>        // "Click Me!".  When the button is clicked, an informational
>        // dialog box appears to say Hello from Swing.

>        import javax.swing.*;    // Swing GUI classes are defined here.
>        import java.awt.event.*; // Event handling class are defined here.

>        public class HelloSwing extends JApplet implements ActionListener {

>           public void init() {
>                 // This method is called by the system before the applet
>                 // appears.  It is used here to create the button and add
>                 // it to the "content pane" of the JApplet.  The applet
>                 // is also registered as an ActionListener for the button.

>              JButton bttn = new JButton("Click Me!");
>              bttn.addActionListener(this);
>              getContentPane().add(bttn);

>           } // end init()

>           public void actionPerformed(ActionEvent evt) {
>                 // This method is called when an action event occurs.
>                 // In this case, the only possible source of the event
>                 // is the button.  So, when this method is called, we know
>                 // that the button has been clicked.  Respond by showing
>                 // an informational dialog box.  The dialog box will
>                 // contain an "OK" button which the user must click to
>                 // dismiss the dialog box.

>              String title = "Greetings";  // Shown in title bar of dialog box.
>              String message = "Hello from the Swing User Interface Library.";
>              JOptionPane.showMessageDialog(null, message, title,
>                                             JOptionPane.INFORMATION_MESSAGE);
>           } // end actionPerformed()

>        } // end class HelloSwing

> In this source code, I've set up the applet itself to listen for action events from the button. Some people don't consider this to be very good style. They prefer to create a separate object to listen for and respond to events. This is more "object-oriented" in the sense that each object has its own clearly defined area of responsibility. The most convenient way to make a separate event-handling object is to use a nested anonymous class. These classes were introduced in Section 5.6. We will see more examples of this in the future, but here, for the record, is a version of `HelloSwing` that uses an anonymous class for event handling. This applet has exactly the same behavior as the original version:

>        import javax.swing.*;    // Swing GUI classes are defined here.
>        import java.awt.event.*; // Event handling class are defined here.

>        public class HelloSwing2 extends JApplet {

>           public void init() {
>                 // This method is called by the system before the applet
>                 // appears.  It is used here to create the button and add
>                 // it to the "content pane" of the JApplet.  An anonymous
>                 // class is used to create an ActionListener for the button.

>              JButton bttn = new JButton("Click Me!");

>              bttn.addActionListener( new ActionListener() {
>                       // The "action listener" for the button is defined
>                       // by this nested anonymous class.
>                    public void actionPerformed(ActionEvent evt) {
>                          // This method is called to respond when the user
>                          // presses the button.  It displays a message in
>                          // a dialog box, along with an "OK" button which
>                          // the user can click to dismiss the dialog box.
>                       String title = "Greetings";  // Shown in box's title bar.
>                       String message = "Another hello from Swing.";
>                       JOptionPane.showMessageDialog(null, message, title,
>                                             JOptionPane.INFORMATION_MESSAGE);
>                    } // end actionPerformed()
>                 });

>              getContentPane().add(bttn);

>           } // end init()

>        } // end class HelloSwing2

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