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 correct definition would be that an applet is an object that belongs to the class java.applet.Applet or to one of its subclasses.
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. All of the applet's behaviors -- what components it contains, what graphics it displays, how it responds to various events -- are determined by methods. These methods are included in the Applet class, but the programmer must override these methods in a subclass of Applet in order to make a genuinely useful applet that has interesting behaviors.
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 program. However, many of the methods in the Applet class 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.
One of the important applet methods is paint(). The job of this method is to draw the graphical elements displayed in the applet -- which is, remember, just a rectangular area in a window. The paint() method in the Applet class doesn't draw anything at all, so paint() is one 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 method must be public because it will be called by the system from outside the class. 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 4.
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:
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 HelloWorldAppletThe 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. Note that I've imported the packages java.applet, which includes the Applet class, and java.awt, which includes the Graphics class and many other classes related to the graphical user interface. Almost every applet uses these two packages.
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 this reason, subclasses of Applet are almost always declared to be public. Otherwise, the system wouldn't be able to access the class, and there would be no way for it to create an applet based on that class.
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:
<center> <applet code="HelloWorldApplet.class" width=250 height=50> <p><font color="#E70000">Sorry, but your browser<br> doesn't support Java.</font></p> </applet> </center>and here is what this code displays:
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 250 pixels in width and 50 pixels in height. You might not be able to see the rectangle as such, 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 a simple example, let's modify the Hello World applet so that each time the user clicks on the applet, the message displayed by the applet will change color. Since we will want the message to be redrawn in the correct color whenever the paint() method is called, we'll need an instance variable to keep track of the current color. To keep things simple, let's use an integer variable named currentColor that takes on the values 0, 1, 2, or 3 to indicate the colors black, red, blue, and green. The paint method can then be written:
public void paint(Graphics g) { switch (currentColor) { // select proper color for drawing case 0: g.setColor(Color.black); // Color.black is a constant that break; // specifies the color black case 1: g.setColor(Color.red); break; case 2: g.setColor(Color.blue); break; case 3: g.setColor(Color.green); break; } g.drawString("Hello World!", 10, 30); }Every time that the applet needs to be redrawn, this method will be called, and it will always draw the string in the currently selected color.
Now, we have to arrange to change the value of currentColor whenever the user clicks on the applet. Whenever this happens, the system calls the applet's mouseDown() routine. This is one of those routines that ordinarily does nothing, but you can override it to specify any response that you want to a mouse click. In this case, we need to change currentColor and then see that the message is redrawn in the new color. The polite way to do this is to call the method repaint(). The repaint() method does not actually do any repainting itself. It merely notifies the system that the applet needs to be redrawn. The system can then call the paint() paint method at its convenience. So, we get:
public boolean mouseDown(Event evt, int x, int y) { currentColor++; // change the current color number if (currentColor > 3) // if it's become too big, currentColor = 0; // then reset it to zero repaint(); // ask the system to redraw the window return true; // tells the system that the mouseDown // event has been processed }You can ignore the parameters of mouseDown() for now; they carry information about the mouse click, but here we need to know only that the mouse click occurred. The boolean return value is typical of event-processing subroutines. The return value indicates whether or not the event needs further processing. As we will see later, it is possible for several objects to get a crack at handling the same event.
We can put all this together into a complete applet:
import java.awt.*; import java.applet.*; public class ColoredHelloWorld extends Applet { // displays a string "Hello World!" that changes // color when the user clicks on the applet private int currentColor = 1; // initial color is red public void paint(Graphics g) { switch (currentColor) { // select proper color for drawing case 0: g.setColor(Color.black); break; case 1: g.setColor(Color.red); break; case 2: g.setColor(Color.blue); break; case 3: g.setColor(Color.green); break; } g.drawString("Hello World!", 10, 30); } public boolean mouseDown(Event evt, int x, int y) { currentColor++; // change the current color number if (currentColor > 3) currentColor = 0; repaint(); // ask the system to redraw the window return true; } } // end of class ColoredHelloWorldAnd here is what it looks like. Try clicking on the applet to make the color change:
[ Next Section | Previous Chapter | Chapter Index | Main Index ]