In this chapter, you will write your first Java applet, from scratch, without using the Visual J++ Java Application Wizard to generate the initial skeleton program. In doing creating an applet from scratch, you will learn how to build simple applets and you'll begin to learn some of the Java language specifics as well.
Java is not a difficult language to learn. In fact, much of the skills of Java programming come from knowing which internal pre-built procedures to run. For example, when you want to print a message in color, you don't have to do much more than find the name of the pre-built procedure that first sets the color, find the name of the pre-built procedure that prints on the applet window, and then type those procedures into your Java applet code.
Once you finish this chapter, many terms that were probably new to you when you started this book will begin to make more sense. For example, you'll better understand the terms method and object-oriented programming. When you finish this chapter, you will completely understand how a Java program works and how it prints a message in color. You will even know enough to modify that program somewhat. You will then be able to change the message, add an additional message, or select another color. Any changes you make will only strengthen your Java and Visual J++ skill set.
In this chapter, you'll learn about the following:
A Java program is typically small. Java's size allows programmers to use Java in computers that don't have a lot of computing power. For example when Sun developed Java, Sun foresaw that their new language might be used in places where embedded code controls activities such as in automobiles and phones. As such, they kept the language small and the associated library files small as well.
A small size does not always translate to an easy language to understand. For instance, QBasic, one of the best learning languages for beginning programmers, has almost 4 times as many commands as the C language, yet, C is much more difficult for the novice programmer to learn. Java, however, seems to be a good middle-ground language because newcomers can learn to write simple applets without a lot of programming background.
You already saw in chapters 6, "Reviewing the Sample Code," and 7, "Reviewing Java's Nature," how one can take advantage of Java code that someone else wrote and extend that code to make the programs behave differently. This extension is one of the fundamental advantages to object-oriented programming (or OOP as it's called). An OOP language, such as Java or C++, treats data items as objects that the code operates upon. Instead of focusing on commands, the language focuses on the data itself. When you extend one program, you inherit data and data behaviors from the existing code.
You'll feel much more comfortable about Java once you finish this chapter because you'll see what all the fuss in chapter 7 was all about. Instead of entering cryptic code that changes the behavior of a pre-written program, you'll write your own program from scratch. In doing that, you'll understand that chapter 7 worked extensively with object-oriented programming to demonstrate the extensible nature of Java code. In addition to filling in parameter values at runtime, you will learn how to extend a program through inheritance to take advantage of even more powerful code already written.
How C++-Like Is Java?
By looking at an extremely simple Java program, you can familiarize yourself with the nature of all Java programs. Listing 9.1 contains an extremely simple Java program that you can enter and run from Visual J++.
So simple is listing 9.1's program that such a simple program is almost more difficult to set up in Visual J++ than a complex program because the application wizard generates so much for you when you need more extensive code. For an extremely simple, minimal program such as the one in listing 9.1, you'll see that you have to jump through hoops to enter and execute the code. The effort is useful, however, because you should begin analyzing Java code by looking at the simplest possible program before moving to more comprehensive programs.
To try this example, don't use the wizard to generate a project. Instead, perform these steps to enter the program in a project workspace:
You must insert a new class for this program.
listing 9.1 A Simple Applet
//*******************************************************************
// Simple.java: Applet
//*******************************************************************
import java.applet.*; // Requires support files
import java.awt.*;
//===================================================================
// Main Class for Simple applet
//===================================================================
public class Simple extends Applet
{
public void init()
{
resize(320, 240); // applet's window size
}
//--------------------------------------------------------------
public void paint(Graphics g)
{
// Change subsequent text color to red
g.setColor(Color.red);
// Write a simple message in the window
g.drawString("Very simple!", 75, 100);
}
}
Listing 9.2 You Can See Why Ample White Space, Comment Separation, and Indention Is
a Good Thing
// Simple.java: Applet
import java.applet.*;// Requires support files
import java.awt.*;
// Main Class for Simple applet
public class Simple extends Applet
{public void init(){resize(320, 240);// applet's window size
}public void paint(Graphics g){// Change subsequent text color to red
g.setColor(Color.red);// Write a simple message in the window
g.drawString("Very simple!", 75, 100);}}
Figure 9.2 shows the result of running the applet in the default Internet Explorer HTML page that Visual J++ automatically creates when you select Build, Execute.
A simple applet that displays a red message.
Here are few points to notice about listing 9.1's sample applet:
Import java.awt.*;
import java.awt.*;
These general coding principles apply to small as well as large Java programs. When you first begin writing Java programs, you may forget some of these coding conventions. Visual J++ lets you know what you did wrong, however, because if you violate one of these conventions, you will almost always trigger a syntax error that Visual J++ will catch during your project's compilation.
In the next chapter, you'll learn all about the details of the Java language. For now, you'll get a good overview by analyzing each of the Simple.java program's lines. The following sections explain the parts of the Simple.java program that you just entered.
The following lines appear at the top of the Simple program:
//***********************************************************************
// Simple.java: Applet
//***********************************************************************
You already know what these lines do. Actually, these lines do not do anything because they are comments. The comments describe the program to whomever looks at the program. Comments do not execute but are there for informational purposes only. These comments contain wrapper comment lines. The first and last comment, containing a row of asterisks, simply provide wrappers for the middle, informational comment that holds the program name. The asterisk lines are good comments to scatter throughout your code to separate parts of the program from each other. As you can see from listing 9.1, you can use the hyphen and equal sign to separate lines as well.
Although the principle is not fixed in stone, you might want to follow the wizard's generated comment style described in table 9.1.
Table 9.1 The Wizard's Commenting Style for Line Separators
A Line of These | Separates This... |
Asterisks | A section with information comments about the program such as the program name and programmer |
Equal signs | A class description |
Hyphens | A class procedure definition |
Scatter comments throughout a program to describe, in human terms, what the program is doing. For example, the following line is cryptic:
for (i=1; i<totNum; i++)
If, however, you preceded the line with the following comment, you'll know right away what the line is supposed to do the next time you need to analyze the program and make changes to the program.
// Step through all the client records
These next two lines in the Simple program appear in almost every Visual J++-based Java program you'll write:
import java.applet.*; // Required support files
import java.awt.*;
The import command inserts classes from other class packages into your program. Remember that a class is a collection of data and routines that you use or write. A package is a collection of classes that are logically grouped together. For example, Visual J++'s pre-installed threading classes all appear inside a single class package.
Instead of writing your own graphics routines when you want to draw a box, you can take advantage of the graphics routines supplied with Visual J++ in the graphics class.
The import command often follows two formats:
import specificPackage.specificClass;
import specificPackage.*;
When you know the exact name of a class that you want to use, you can specify that name inside the import command. The specificPackage is the name of the class package from which you want to import the class named specificClass.
All this talk about classes might confuse you at this point. After all, the Java program that you write is a class, you use procedures, or methods, from classes within your program, and you import classes from other locations, such as from the Visual J++ internal class library packages as done in the Simple.java applet. The classes contain all code executed in Java. When you write a program, you are, in effect, adding a class to the collection of classes already on your machine. Your program is an addition to the other classes that you and your co-workers might write, as well as to the supplied classes that Visual J++ provides. you can get classes from other sources as well.
As you can see, all work is done from inside classes and classes can share power from other classes. Therefore, when your program, a new class, needs to print something on the screen, you should use one of the routines from an output class supplied by Visual J++. You could write your own output routine from scratch, but the goal of the pre-defined class packages is to make your programming life easier and quicker so you have more room for those exotic Jakarta holidays. (Jakarta is the capital of the country named Java, by the way.)
The second form of import uses a wildcard asterisk to specify that you want to import all classes from a class package. The Simple.java applet uses this import form for its own imported classes. The Java.applet class package is a necessary class for you to use to embed your own Java applet on Web pages. Therefore, you'll always import java.applet and all its classes at the top of every applet that you write (so does the Visual J++ wizard).
The java.awt class package contains lots of graphics routines that let you send output to a Web page applet window. If you're used to programming in text-mode environments, such as MS-DOS, you must re-gear and get used to working in a graphics environment. Instead of printing text on the screen, you often draw text. The Simple.java program contains a reference in the body of the code to drawString() (the parentheses indicate that drawString is a method which is a class procedure) and the instructions for drawString() appear in the java.awt class package.
Table 9.2 contains a description of common class packages.
Table 9.2 Common Class Packages You Can Use in Your Java Programs
Package Name | Description |
java.applet | The parental applet class that contains all the information and methods you need to embed an applet inside a Web page. |
java.awt | Contains graphics-related methods. |
java.io | Contains methods that perform input and output. |
java.lang | Contains system interface information that your applet will need. Java automatically imports this class package for you so you'll never import the class package yourself. |
java.net | Holds networking environment support. |
java.util | Contains several utilities for data structure storage, such as linked lists and data manipulation. |
Locating Classes
After a comment, you'll see the following two lines:
public class Simple extends Applet
{
The opening brace begins a group of statements that make up the body of your program's class named Simple. The class does not terminate until the last line of the program which closes out the braces and the grouped statements between the braces.
Although this public class statement looks fairly complex, the statement is required for your applets. The statement informs Visual J++ that you want to create your own class. To create the class, you subclass another class called the Applet class. Subclassing refers to the practice of taking an existing class and making a copy of it in addition to extending that new class's capabilities. In this example, you are taking the generic class called Applet, that comes pre-built into the java.applet class package, making a new copy of the Applet class, naming the copy Simple, and adding your own functionality to it.
If you were to have to write the Applet class from scratch, your programs would be huge and your Java tutorial would take much more time than necessary. As you've already seen in the second part of this book, of the advantages of Java, and of most OOP languages, is that you can inherit functionality from code that's already written. The Applet class contains all the code needed to write on a Web page. You want your applet to write on a Web page also, so why not borrow the code from the java.applet class package Microsoft gave you with Visual J++?
Therefore, the statement creates a new class using the functionality of the Applet class, and names the new class Simple. The public keyword makes the class available to other classes that might want to inherit from Simple. In the second part of this book, you inherited from several pre-defined classes. The programmers who wrote those classes made the classes public so the classes would be available to you and other who wanted to extend them. Almost all classes that you write will be public and the Visual J++ wizard always generates public classes.
Keep in mind that this statement is not actually an executable statement but a definition statement. No semicolon appears after the class statement because the statement does nothing more than define a new class, your class, and informs Visual J++ where the existing functionality is to come from. Although the class statement seems a little long at first, you don't even have to write it in most instances. When you use the wizard to generate a skeleton application, the wizard will include an appropriate extended applet from Applet.
When you create your own source code file, as you've done in this chapter, you only need to tell the Create New Class dialog box the name of the existing class that you're extending, your new extended class name, and then click Public to set the public modifier. Visual J++ will generate the correct class definition line for you in the Editing window when you click OK.
You'll add new functionality to your new Simple class in the class body. The body is made up of all statements from the class statement's opening brace to the closing brace at the end of the program.
The next four lines in the Simple applet define a new method called init(). In reality, you are redefining a method. When you subclassed the pre-built Applet class, you gained the capabilities of every method within the Applet class. Once of those methods is called init(). The Applet's init(), however, does not do much. You must redefine the method. Therefore, every time you write an applet, and extend the Applet method, you'll also have to supply an init() method of your own.
Almost every init() that you write will call the resize() method just as your applet does as repeated here:
public void init()
{
resize(320, 240); // applet's window size
}
The resize() method simply informs your class of your applet's window size in the target Web page. You can also insert any other code inside init() that you want executed right after the initial loading of your applet. resize() requires two arguments: an x- and a y-coordinate. Enter the x- and y-coordinate values in pixels. As figure 9.3 illustrates, the x-coordinate determines the width, in pixels, of your applet's window and the y-coordinate determines the height of your applet's window.
resize() determines the size of your applet's window.
The paint() method should appear in every applet you create and paint() should follow init(). Your applet executes paint() every time your applet window needs redrawing. In a Windows environment, parts of your screen have to be redrawn quite often. For example, you might hide a window and, when you unhide the window, the hidden portion must reappear. Perhaps your end-user minimizes the Web page down to a taskbar icon and then maximizes the window, or resizes the window. As long as you've supplied a paint() method, and you must, you can be assured that your applet window will reappear properly, with the text, colors, and whatever else that appears there.
Here are the Simple applet's paint () lines:
public void paint(Graphics g)
{
// Change subsequent text color to red
g.setColor(Color.red);
// Write a simple message in the window
g.drawString("Very simple!", 75, 100);
}
Unlike init(), paint() requires a parameter inside its parentheses. The parameter is a value that the paint() method operates on. Although Graphics g is a strange parameter, the parameter represents your applet's Web page graphical window. The Graphics g designation is a Java standard designation for your applet window. Even the Visual J++ wizard generates an identical paint() definition line.
Whatever paint() does to the value named g happens to your applet's window. The g is known as a graphics device context. A Windows application does not actually write to your screen; instead, a Windows application writes to windows. The Graphics g parameter tells your applet where to write, namely, the window inside the applet's enclosing Web page.
The next line, shown next, makes a lot of sense despite its wordiness:
g.setColor(Color.red);
Remember that the g represents your Web page applet's window. If you discern that this statement sets your applet window to red you are almost correct. Actually, the statement sets all subsequent output to red. The window remains gray. setColor() will not change an applet's existing colors so you are able to send different colors to the same window by executing multiple setColor() methods between each line of output.
When you see a period following an object (the object, g, represents your applet window), the value to the right of the period will always be a method or a value. Can you tell what setColor() is? setColor() is a method and you know that because of the parentheses that follow its name. The setColor() method is an internal java.awt class method that sets all subsequent output to a specific color. The color must appear inside the parentheses. The color, inside the parentheses, is the setColor() parameter.
Windows is capable of displaying several million colors, although not all graphics cards can display that many colors. As with the Windows API, there exist several ways to represent all the shades of colors that can appear on your screen. Generally, you'll supply an RGB numeric value. RGB stands for Red/Green/Blue. By supplying a number that represents a combination of red, green, and blue color shades, you can specify an exact color value.
Visual J++ makes it easy, however, to specify some standard colors. Therefore, if you don't want to get too picky with finding just that right shade of monkey blue you've always loved on your bedroom ceiling, you can specify one of the colors from Table 9.3 for the argument inside setColor(). Notice that you must precede the color name with the Color object. As mentioned just a couple of paragraphs ago, a period always indicates that a method or a value follows. The Color object is a symbolic object, defined inside the java.awt class package, that represents coloring and you can specify a specific named value by following the Color and period with one of the named color values in table 9.3.
Although the syntax is a little tricky, you can see that the setColor() method is not necessarily hard to understand. For example, you could later print some green text on your applet's window by placing this statement before you print the text:
g.setColor(Color.green);
Table 9.3 Color Values That Represent Specific Colors
black |
blue |
cyan |
darkGray |
gray |
green |
lightGray |
magenta |
orange |
pink |
red |
white |
yellow |
OOP-Based Code
Once the Simple applet sets the color red, the applet sends two words to the applet window with this line:
g.drawString("Very simple!", 75, 100);
drawString() is a commonly-used method that sends strings to the applet's window. drawString() respects the color set by setColor() so the text, Very simple!, will appear in red. Notice the g before the method name. You could, in theory, send different strings to different windows if you knew the multiple window context names by replacing g, your applet's window's context value, with the other windows' context value names.
The second and third parameters of drawString() represent the starting x- and y-coordinates of where you want the text to appear. In other words, init() created an applet window that runs 320 pixels across by 240 pixels down. drawString() starts drawing its text, Very Simple!, exactly 75 pixels down and 100 pixels across the applet window.
You now know all you need to know about the Simple applet. You should be proud of yourself! As you can see, Java programming is not difficult to understand, but some of the statements can get tricky. Fortunately, the wizard generates the critical code for you when you use the Visual J++ wizard to generate the program's skeleton. Also, much of the language will become second nature to you once you've written a couple of applets.
The goal of this chapter was to show you a simple but complete Java program and to walk you through the explanation of every line in the program. You now better understand the "big picture." You know that your applet is actually a subclass, or an inherited version, of an internal applet named Applet that comes with Visual J++. Whereas the Applet is not usable, you can subclass Applet and add your own functionality to make your inherited applet do something unique.
At this point, you have a better understanding of object-oriented programming and of the requirements needed to write a working Java applet. The best thing you can do now, before turning the page to the next chapter, is to change this chapter's Simple applet and make Simple do something else. Start easy; change the applet's output message to your name. Place your name in a different location on the applet window. Change the color. If you really want to make things interesting, print each letter of your name in a different color! (Here's a hint: You'll have to execute the setColor() method once for each letter in your name.)
If you make mistakes, try to fix them. One of the most common mistakes you might make is not getting the case correct on the setColor() and drawString() methods. Be sure that you type these method names exactly as you see them here or Visual J++ will not recognize them and will issue errors. (The error messages are not the most obvious either! It would be nice if Visual J++ would give an error message like, "You misspelled drawString()," but Visual J++ offers a more technical explanation when you misspell a method, such as Cannot find method drawstring.
In the next chapter, you will begin to learn the deep details of the Java language. It's time to get down to the nitty-gritty details of data types and programming control statements and chapter 10 takes you there in a hurry.
Here are the points this chapter covered:
| Previous Chapter | Next Chapter |
| Table of Contents | Book Home Page |
| Que Home Page | Digital Bookshelf | Disclaimer |
To order books from QUE, call us at 800-716-0044 or 317-361-5400.
For comments or technical support for our books and software, select Talk to Us.
© 1996, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.