Chapter 5 -- Writing a Java Applet: The Order
Entry System
Chapter 5
Writing a Java Applet: The Order
Entry System
CONTENTS
In the preceding four chapters, you have had an introduction to
Java as an object-oriented language. You will see, as the book
continues, that this is what makes Java so powerful and easy to
use. In Chapter 3, "An Introduction
to Java Classes," you were given an introduction to the java.applet
and java.awt classes. You
extend your knowledge of those classes over the next six chapters
as we build the Order Entry System applet. This construction of
the Order Entry System and the concepts behind it will span almost
all of Part II. Finishing up Part II of this book, Chapter 11,
"Reading and Writing with Java," covers reading and
writing with Java.
In this chapter, the Order Entry System is described. It is constructed
over the next seven chapters as you explore the implementation
and dynamics of the Java language and class libraries. You explore
the basic concepts behind Java applets and the Abstract Windowing
Toolkit (AWT), which allows you to construct a useful applet for
entering and submitting orders. By the end of Chapter 10,
"The Order Entry System: Exception Handling and Browser Interaction,"
you will have a fully functioning system, along with the knowledge
necessary to customize and maintain it.
The World Wide Web (WWW) is evolving from being a means to communicate
static scientific documents in its early days to becoming an interactive
and alive medium. Currently, both individuals and businesses use
it as a medium for their messages to reach a worldwide audience.
Java is changing the Web from being a static means of communicating.
The future of the WWW, as many people predict, is to be a unique
medium involving active interaction, motion, and multimedia expression.
The Order Entry System functions in this interactive capacity.
It includes graphical user interface (GUI) components such as
buttons, scrolling lists, and text entry fields for use by someone
viewing your Web site. This chapter covers the techniques of password
entry and validation in Java Applets in order to limit access
to your applet. It also checks the data to make sure that the
data is appropriate for entry.
The Order Entry System functions as a stand-alone window, complete
with a menu bar, and has all of the functions of a working window
common to operating systems, such as Windows 95, X Window, and
others. This functionality is accomplished through the use of
Java frames and the layout managers provided in Java; the functionality
is covered in Chapter 8, "The Order
Entry System: Managing the Applet Layout." The layout of
the GUI components is managed using the GridBagLayout Managers
to ensure a clean interface. You will be aiming to produce a professional-looking
and clean-running applet in both appearance and function. In keeping
with this goal, you will also add graphics-based text and figures,
and a logo to the applet. Figure 5.1 shows the Order Entry System
GUI.
Figure 5.1 : The Order Entry System CUI.
The Order Entry System takes user input from the keyboard and
mouse. This is handled using code based on the concept of events,
which are happenings that require some kind of reaction from a
Java program using the AWT. For example, one such event requires
the browser to command the Web browser to change its current focus
to another html document. The concept of events in Java will be
covered in the upcoming chapters. This enables the user to view,
in the case of the Order Entry System, different Web documents
containing descriptions of the different products available. Finally,
this chapter covers the means to get the order back to you, either
through e-mail or through use of CGI scripting.
You will build the Order Entry System block by block, adding more
function and capability as you progress through Java concepts
and their implementations. Each chapter covers an additional group
of Java's capabilities and applies those to the System. But first,
I need to cover some necessary concepts.
Essential to Java is platform independence. As even those with
just a little experience in programming know, porting programs
between platforms is often a daunting task. Take, for instance,
the question of how many bytes are required to store an integer
type. Many systems, such as UNIX-based machines, use four bytes
to store an integer. Intel machines use two. This inconsistency
in changing platforms suggest what kinds of problems are posed
to developers wishing to create machine-independent code. The
designers of Java have attempted to circumvent these problems
through careful planning.
The Java Abstract Windowing Toolkit (AWT) is the means by which
GUIs are implemented in the Java language. It provides the programmer
with the means to create windows utilizing buttons, text entry
fields, and all of the typical elements you expect in windows
systems. It allows the Java programmer to design windowing programs
that can be used on any machine in which a Java bytecode interpreter
and an AWT have been implemented. Above all, the AWT is important
because it allows you to easily produce high-quality interactive
and efficient Java applications and applets.
Note: |
Applets, as you have seen in Chapter 3, are a special type of Java program designed to be incorporated into html documents. Applications are stand-alone Java programs. Their differences are covered more in depth later on in this
chapter.
|
An important characteristic of the Java AWT is that it has been
designed to be event-driven. By this, I mean that actions are
delivered to your program based on the AWT, and your program handles
them from there. The AWT has standardized those actions to make
handling them very easy.
Also important to the portability of the AWT across different
platforms and operating systems is how it handles the layout of
different components. In many window systems, such as Microsoft
Windows, the programmer must specify exact coordinates to specify
the position of each different component of the window. This is,
obviously, a problem when you are trying to design with platform-independence
as a goal. What happens when you design an applet for a screen
size of 1024¥768 and someone tries
to view it on a screen of much lower resolution? An applet that
once filled the entire screen cleanly is now a mess. The AWT is
designed to circumvent this problem by not specifying exact layouts
for a window; instead, it uses various different lay out managers
in the class library, managers that function based on general
rules to lay out the components in a window. This is covered in
depth in Chapter 8.
Note: |
The AWT is designed to produce windows to appear exactly like the native windows in any system. This way, your programs are not distinctively Java when run on different platforms. They blend cleanly into the local windowing system with little or no
discontinuity.
|
The Java AWT is designed based on the concepts of components and
containers. Components are the building blocks of AWT-based applets
and applications. A diagram of the inheritance hierarchy of some
of the AWT is shown in Figure 5.2.
Figure 5.2: The partial inheritance hierarchy of the AWT.
You should notice that the vast majority of the other classes
of the AWT are subclasses of the class Component.
One subclass of the component class is containers. Containers
are AWT components that function to contain other components.
Containers allow you, the programmer, to break down your GUI into
smaller and smaller sections until each is laid out exactly the
way you want it. This is accomplished easily because containers
themselves are derived from components. Because each container
can apply a specific layout to the components that it is housing,
the programmer has much more control.
The type Component can be
conceptually divided into three major categories: containers,
user interface components, and windowing components.
Containers
Containers hold other components, including containers themselves.
The container type you see most often is the Panel
class. Panels are the general container class that function just
to hold other components. They don't do much else, but they are
indispensable in the overall design goals for the AWT.
User Interface Components
User interface components are the buttons, scrolling lists, and
text entry fields that you should be familiar with in dealing
with any windows-based interface. Here is a list of the major
interface components provided by the AWT:
Labels
Buttons
Radio buttons
Checkboxes
Lists
Choices
Text fields
Text areas
Scrollbars
Menus
Canvases
Note: |
Canvases are special components that are, as their name implies, drawing surfaces. You are not limited to drawing just on canvases. You can also draw on panels, but as you see in later chapters, drawing on panels can lead to complications in layout and
portability.
|
These different types of interface components, their form and
their functions, are detailed in depth in the chapters to come
as you build the Order Entry System.
Windowing Components
Windowing components are the components that function to produce
stand-alone windows and menus in your Java applets and applications.
Although these are technically a type of container, they are more
easily understood if they are placed in a separate grouping aside
from general containers. The major types of windowing components
are frames and dialogs. Frames are the means by which you can
create stand-alone windows outside of your browser; you also use
frames when creating your own windowed application. Frames can
include menu bars. Dialogs are limited windows. The most common
type of dialog is the "OK" window, which presents a
message to a user and then gets an OK to continue. Chapter 8
explores two types of dialogs: modal and non-modal. The difference
between the two types is that modal dialogs allow input from the
user only to its window, and no others, while it is active.
The Order Entry System contains almost all of the different components
available. The System GUI is shown in Figure 5.3.
Figure 5.3: The components in the Order Entry System interface.
This simple applet isn't going to do much except incorporate a
button and a comment field into an applet. This example is useful
for you to get a feel for the basic Java applet constructors before
you move on to more complex examples. In any case, here it is:
1. import java.awt.*;
2.
3. public class supersimple extends java.applet.Applet
4. {
5. public void init()
6. {
7. add(new Button("Order"));
8. TextArea CommentArea =
new TextArea(5,25);
9.
CommentArea.insertText("Hal Bialeck",0);
10. add(CommentArea);
11. }
12.}
Note: |
All applets in this book are included on the book's companion CD-ROM.
|
Caution: |
Java requires that your applets are saved in the same file name as the class name. For example, if your class is named dinky, it must be saved in a file called dinky.java. You will otherwise receive an error when you try to compile it.
|
Line 1 imports all of the classes in the Java.awt package. Earlier
chapters covered the process of importing other classes into your
classes. If you are not familiar with this process, go back and
review that section. You can view applets simply as classes you
write to extend and modify the framework of the java.applet.Applet
class. This process is specified in the class declaration in line
3.
As for the rest of the code, here is an explanation in brief (don't
worry much about understanding it all now). Line 5 declares the
new function init(), which
overrides the method imported in the Java.applet.Applet
class. Line 7 creates and inserts a button with the text Order
on it. Lines 9 and 10 create a text area and insert the text Hal
Bialeck in the beginning of the area. Finally, line
11 inserts the text area.
This example gives you a feel for the flow of Java applets.
Figure 5.4 shows this applet when displayed in the AppletViewer
utility from the JDK.
Figure 5.4 : The supersimple AWT example applet.
Note: |
As you found out in previous chapters, applets must be imbedded in an html document before they can be viewed by a Java-enhanced browser or the AppletViewer utility. How to place applets in your Web pages is covered later in this chapter. You learn how to
design the html document to display this example.
|
This chapter has covered what makes up the framework of classes
to produce Java-based GUIs. Next is the concept of applets,
which are Java programs specially designed to be downloaded across
the Internet and included in an html document displayed by a Java
enhanced browser.
Applets are designed to bring the Web alive. They function to
add animation, sound, and eventually complete multimedia into
html documents. Java is also part of the future of interfacing
with virtual-reality environments implemented via VRML. At present,
Java is limited only by the capabilities of the Internet itself.
For more information on VRML, the Virtual Reality Markup Language
for the Web, visit VRML's home at http://www.vrml.org.
http://www.vrml.org
The most important feature of applets on the Web, however, is
the fact that applets change the Web from being a static medium
to one based on interactivity with users. At present, Java is
limited only by the capabilities of the Internet itself. As the
Internet grows in data transmission, Java is ready to expand with
it.
Applets are capable of commanding and interacting with the Web
browser executing them.
Tip: |
Remember that not everyone can view applets that you might put on your Web pages. At the time of this writing, only HotJava, Microsoft Internet Explorer, Netscape Navigator 2.0 (and above) and a number of others are Java-capable. Also, Navigator 2.0 for
Microsoft Windows 3.1 does not support Java, though the current release of Navigator 3.0 for 3.1 does support it. You should, therefore, use applets merely to enhance a Web page or site, not to be the centerpiece. This limitation will change in the future
as Java-capable browsers become the standard, just as browsers capable of displaying images have become the standard today. (Of course, someone will always insist on using Lynx, a text-only browser; you can't do much about these folks.)
|
Technically, applets are subclasses of the panel container of
the AWT. They derive much of their function and form from panels.
But just as the process of imbedding container upon container
makes panels so powerful, the same is true about the versatility
of applets. The diagram of the inheritance path of the class implementing
applets, java.applet.Applet,
is shown in Figure 5.5.
Figure 5.5 : The inheritance path of applets.
Java programs are divided into two types: applets and applications.
As I have discussed previously, applets are Java programs that
are specialized for use over the Web. Applications are stand-alone
Java programs that can be run via a Java interpreter, and when
run in that manner they appear just as any compiled C++ or Basic
program would. Since this book focuses on Java programming for
the WWW, I will concentrate on applets when examining the Java
language.
As you will find out in Chapter 12, "Network
Programming with Java," networking with Java is powerful
and easy. As Java was designed to be a networking language, many
of the problems with network programming in other languages have
been removed. Both Java applications and applets have access to
these networking capabilities, but applets are limited in scope
to where they can connect and to where they can perform input/output
tasks.
As of the 1.0.2 release of Java from June of 1996, applets are
limited in order to ensure the security of the user. When you
are designing applets, you should be aware of limitations in the
areas of read/write access, connectivity, and native language
library access.
Applets cannot read or write to the local file system. If applets
were able to access the local file system, there would be little
to stop an evil applet from searching the local files for valuable
information and then sending that information back to its originating
server. Nothing would stop a programmer from writing an applet
to reformat a hard drive or spread a virus. Obviously, allowing
Java applets to have read/write privileges on local machines would
be disastrous.
Applets cannot make connections and transfer data except from
the machine from which they were downloaded. For example, say
an applet was written to post form data or send e-mail messages.
Although allowing this kind of access would be advantageous, it
is obviously dangerous. Suppose someone wrote an applet that would
send a threatening e-mail message to the President (president@whitehouse.gov)
each time someone viewed a page on the Web. Allowing this kind
of access would be disastrous in that no one browsing the Web
would be able to trust applets they are downloading across the
Internet. By their nature, applets are untrusted by Web browsers.
In fact, if you run the Order Entry System you are constructing
over the next six chapters in Netscape Navigator 2.0, you will
be presented with a large label informing you that you are viewing
an "Untrusted Applet Window." This is to keep an unscrupulous
programmer from writing an applet that would disguise itself as
a trusted application and prompt the user for a password that
it would return to its server. This distrust of Java applets is
becoming less common as more people and developers accept Java.
Java has the capability to access native libraries from other
languages such as C++. Applets are restricted from this feature.
If this was allowed, there would be nothing to keep applets from
calling native language methods that would perform some evil action.
By limiting the applet's library access, the ability for a programmer
to write some evil methods in another language and circumvent
Java's security measures by using them in an applet is removed.
Java applets are also restricted from executing any code on a
local machine. This includes forking processes on UNIX systems.
These limitations are entirely necessary. Say, for instance, an
evil applet spawned a process to search (grep'ed
in UNIX) your file system for the word address or password,
and then sent an e-mail message containing the results back its
server. This would be disastrous.
Hopefully, as the Internet and Java develop, the tight leash around
applets will loosen. For the present day, however, you have to
live with these constraints in order to take advantage of the
capabilities of Java.
Note: |
There are also other notable security concerns and solutions to these problems. They are detailed in Chapter 19, "Security Issues," which deals with security issues and Java.
|
Applets follow a set life cycle during their execution. They are
initialized, started, stopped, and destroyed. Initially, the Java
bytecodes are run through a security check by an object running
in the browser. Then, to start execution, the Java runtime calls
the init() method of your
applet.
The init() method is where
your applet does much of its setup, such as defining its layout,
parsing parameters, or setting the background colors. As with
all of these methods, if you do not override the default methods
provided in the java.applet.Applet
class, they are called and do their normal duty. In the case of
the init() method, if it
isn't overridden, nothing goes on. In any case, it is still called.
If you noticed in the supersimple
example discussed earlier, you utilized the init()
method to set the initial layout for the applet. For the other
three methods standard in the life cycle of Java applets, you
simply used the default methods in the Applet class.
The start() method is used
mainly when implementing threads in Java. You will learn more
about threading in Java in Chapter 16,
"Multithreading with Java," which covers threading and
multithreading. If you have no clue as to what threads are, it
might be helpful to glance at the beginning of that chapter.
In Java, threading is most helpful when performing audio playing
or animation. In these cases, or if you want your program to be
able to stop and restart, it is helpful to override the start()
method and implement your own. But if this isn't the case, you
can just utilize the start()
method in the Applet class.
The stop() method is used
to do what its name suggests: stop what is going on. In it, you
usually stop() the threads
that you initiated in the start()
method. As is the case with the start()
method, if you aren't doing anything that is threaded, you do
not have to worry about implementing this method in your applet.
Tip: |
When a viewer leaves a page, by default, the applet continues running. Utilizing the stop() method ensures that whatever you have started in your applet stops to free up system resources.
|
As with the previous three methods, the destroy()
method is as simple as its name. When it is called, the applet
is told to free up system resources. In most general cases, you
probably won't need to override this method, although there are
some very special cases in which you might want more control on
applet shutdowns.
Figure 5.6 is a diagram of the call path of these methods used
to control Java applets.
Figure 5.6 : The life cycle of applets.
It is important to note that applet design should include multiple
calls to start() and stop();
init() and destroy(),
however, are never called more than once.
Note: |
Different browsers act differently when reloading applets. Netscape Navigator 2.0 simply recalls the start() method of an applet when a viewer returns to a page that he or she has already visited. The AppletViewer included in the Java Developer's
Kit instead reloads the entire applet from scratch. (This was a frustrating lesson learned late in one night of programming.) For this reason, you will probably always use the AppletViewer utility when testing your applets. You will need to use trial and
error to figure out how your specific browser functions.
|
Ideally, I would have liked to include an example demonstrating
the life cycle of a Java applet. However, to do so would mean
incorporating threading, and that would complicate things more
than helping. For the present time, keep these applet characteristics
in mind as you develop the Order Entry System in the chapters
to come.
This section covers the html codes specific to Java applets and
how to include them in your Web pages. You should have a small
amount of familiarity with the way html works before going through
this section. If you don't, it would be best if you looked at
one of the many books or Web documents available to teach html.
A good source of information is Laura Lemay's Teach Yourself
html in a Week. Many good Web documents teach html. Many of
them are available on-line.
This section familiarizes you with how two browsers utilize Java:
Netscape Navigator version 2.0 and above, and Sun's HotJava. This
section covers the tags for declaring an applet in a Web page,
parameters, and other features of html code for implementing applets.
You will be, if nothing else, entirely comfortable with the process
of putting not only your own applets into your pages, but also
those written by programmers (those who give you permission, of
course).
Netscape has pushed long and hard to continue developments above
and beyond its competition in the Web browser arena. By releasing
its software for free, Netscape has attracted millions of new
users and continues doing so through technical advances. The 1.0.2
version of Java is included in the JDK on the CD-ROM with this
book. Most surveys report that the Navigator is far and away the
dominant browser on the market today.
Note: |
You can assume that most of the other browsers on the market today will follow the Netscape format of applet inclusion in html documents. This is the same for Microsoft Internet Explorer and IBM's releases of its Web Explorer.
|
|