New to Java? We'll help you get started with our revised beginner's tutorial, or our free online textbook.
|
Get the latest Java books |
|
h t t p : / /w w w . j a v a c o f f e e b r e a k . c
o m /
|
Section 6.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 reasons to do so. 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. You will see a few examples later in this section, and I will discuss graphics in more detail in Section 3.
The paint() method of an applet does not, by the way, draw GUI components such as buttons and text input boxes that the applet might contain. Such GUI components are objects in their own right, defined by other classes. All component objects, not just applets, have paint() methods. Each component is responsible for drawing itself, in its own paint() method. Later, we'll see that many applets do not even define a paint() method of their own. Such applets exist only to hold other GUI components, which draw themselves.
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 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.
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 what this code displays:
If the browser you are using does not support Java, or if you have turned off Java support, then you won't see anything. 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 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 HelloWorldApplet is pretty boring. An applet should do something, either on its own or in response to user actions. As an example, we'll look at an applet in which a friendly greeting changes color whenever the user clicks on a button. This example demonstrates several major aspects of applet programming:
The button in this applet is an object that belongs to the class Button (more properly, java.awt.Button). 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. Unlike most objects, applets do not use constructors 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.
Once it has been added to the applet, a Button object mostly takes care of itself. In particular, it draws itself. 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? The color of the message in the applet should change. It is tempting to think that the actionPerformed() method should simply redraw the message in a new color. Unfortunately, there is a problem.
The applet's paint() method is called by the system as soon as the applet appears on the screen. But 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 happen when you scroll the window of a browser, and the applet scrolls into view. And, it is especially important to note, the applet's paint() method can be called because the program makes a request for the applet to be redrawn. Such requests are made by calling a method named repaint().
The paint() method can be called over and over, and each time it's called, it must be able to draw the correct picture in the applet. In the applet we are writing, that means drawing the message in the correct color. Suppose our actionPerformed() method simply draws "Hello World" in a new color. The paint() method must be able to redraw the message in the same color. How will the paint() method know which color to use? The only way an object "knows" anything is by having data stored in its instance variables. Our applet needs an instance variable to store information about the color of the message. The actionPerformed() method sets the value of that instance variable. The paint() method checks the value of the variable to decide which color to use for the message. In fact, the actionPerformed method doesn't have to do any drawing at all! It just sets the instance variable and calls repaint(). In response to the repaint() call, the system will call the paint() routine, and that is where the actual drawing happens.
Given all this, you can understand a lot of what goes on in the source code for our colored Hello World applet. This example shows several aspects of applet programming: An init() method sets up the applet and adds components; a paint() method draws the applet based on data stored in instance variables; and an event-handling method says what happens in response to certain user actions. I've included comments in the source code to explain other aspects of the programming, which will be covered in full later in this chapter. With this help, You should be able to follow what is going on
// An applet that says "Hello World" in a big bold font, // with a button to change the color of the message. import java.awt.*; // Defines basic classes for GUI programming. import java.awt.event.*; // Defines classes for working with events. import java.applet.*; // Defines the applet class. public class ColoredHelloWorldApplet extends Applet implements ActionListener { // Defines a subclass of Applet. The "implements ActionListener" // part says that objects of type ColoredHelloApplet are // capable of listening for ActionEvents. This is necessary // if the applet is to respond to events from the 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. // A font object represent a certain size and // style of text drawn on the screen. public void init() { // This routine is called by the system to initialize // the applet. It sets up the font and initial colors // the applet. It adds a button to the applet for // changing the message color. setBackground(Color.lightGray); // The applet is filled with the background color before // the paint method is called. The button and the message // in this applet will appear on a light gray background. colorNum = 1; // The color of the message is set to red. textFont = new Font("Serif",Font.BOLD,24); // Create a font object representing a big, bold font. Button bttn = new Button("Change Color"); // Create a new button. "ChangeColor" is the text // displayed on the button. bttn.addActionListener(this); // Set up bttn to send an "action event" to this applet // when the user clicks the button. The parameter, this, // is a name for the applet object that we are creating. add(bttn); // Add the button to the 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. switch (colorNum) { // Set the color. case 1: g.setColor(Color.red); break; case 2: g.setColor(Color.blue); break; case 3: g.setColor(Color.green); break; } g.setFont(textFont); // Set the font. g.drawString("Hello World!", 20,70); // Draw the message. } // end paint() public void actionPerformed(ActionEvent evt) { // This routine is called by the system when the user clicks // on the button. The response is to change the colorNum // which determines the color of the message, and to call // repaint() to see that the applet is redrawn with the // new color. if (colorNum == 1) // Change colorNum. colorNum = 2; else if (colorNum == 2) colorNum = 3; else colorNum = 1; repaint(); // Tell system that this applet needs to be redrawn } // end init() } // end class ColoredHelloWorldApplet
[ Next Section | Previous Chapter | Chapter Index | Main Index ]