CIT 212 Object Oriented Programming With Java
CIT 212 Object Oriented Programming With Java
CHAPTER ONE............................................................................................................2
The Basic Java Application........................................................................................2
Compiling the program, and running the compiled program.....................................3
Key Features of Java Technology..............................................................................6
Functions Of Java Virtual machine(JVM).................................................................8
Execution environment..........................................................................................9
Bytecode verifier....................................................................................................9
Bytecodes...............................................................................................................9
Garbage Collection...................................................................................................12
Why garbage collection........................................................................................12
CHAPTER TWO..........................................................................................................13
Variables...................................................................................................................13
Primitive Types........................................................................................................14
CHAPTER THREE......................................................................................................17
Objects and Classes..................................................................................................17
Inner Classes............................................................................................................21
Static Inner Classes..............................................................................................21
Non-Static Inner Classes......................................................................................22
Inheritance and Polymorphism................................................................................22
Derivation and Inheritance...................................................................................23
CHAPTER FOUR........................................................................................................29
Subroutines...............................................................................................................29
Black Boxes.............................................................................................................29
Static Subroutines and Static Variables....................................................................30
Parameters................................................................................................................39
Return Values...........................................................................................................46
Toolboxes, API's, and Packages...............................................................................52
More on Program Design.........................................................................................56
Preconditions and Postconditions........................................................................56
A Design Example................................................................................................57
The Truth about Declarations...................................................................................63
CHAPTER FIVE..........................................................................................................72
CONTROLS.............................................................................................................72
Blocks, Loops, and Branches...................................................................................72
Algorithm Development...........................................................................................77
Coding, Testing, Debugging.................................................................................83
The while and do..while Statements........................................................................84
The while Statement..........................................................................................84
The do..while Statement................................................................................87
The break and continue Statements.............................................................89
The for Statement.....................................................................................................90
Nested Loops........................................................................................................96
The if Statement.......................................................................................................99
............................................................................................................................106
The switch Statement.............................................................................................106
The Empty Statement.........................................................................................108
A List of Java Statement Types..........................................................................109
Introduction to Applets and Graphics.....................................................................110
CHAPTER SIX..........................................................................................................118
Arrays.....................................................................................................................118
Creating and Using Arrays.................................................................................118
Programming with Arrays......................................................................................123
Dynamic Arrays, ArrayLists, and Vectors..............................................................131
Partially Full Arrays...........................................................................................131
Dynamic Arrays.................................................................................................134
ArrrayLists.........................................................................................................137
Vectors................................................................................................................141
Searching and Sorting............................................................................................141
Searching............................................................................................................142
Association Lists................................................................................................144
Insertion Sort......................................................................................................145
Selection Sort.....................................................................................................147
Unsorting............................................................................................................149
Multi-Dimensional Arrays.....................................................................................149
CHAPTER SEVEN....................................................................................................161
Applets, HTML, and GUI's....................................................................................161
JApplets and Swing................................................................................................164
HTML Basics.........................................................................................................167
Graphics and Painting............................................................................................173
Mouse Events.........................................................................................................183
Keyboard Events....................................................................................................195
Introduction to Layouts and Components..............................................................202
CHAPTER EIGHT.....................................................................................................211
Advanced GUI Programming.................................................................................211
More About Graphics.............................................................................................211
More about Layouts and Components...................................................................220
Basic Components and Their Events.....................................................................227
Menus and Menu Bars...........................................................................................238
Frames and Dialogs................................................................................................266
CHAPTER ONE
We begin our exploration of Java with the problem that has become traditional for
such beginnings: to write a program that displays the message "Hello World!". This
might seem like a trivial problem, but getting a computer to do this is really a big first
step in learning a new programming language (especially if it's your first
programming language). It means that you understand the basic process of:
getting the program text into the computer,
Compiling the program, and running the compiled program.
The first time through, each of these steps will probably take you a few tries to get
right. I can't tell you the details here of how you do each of these steps; it depends on
the particular computer and Java programming environment that you are using.But in
general, you will type the program using some sort of text editor and save the program
in a file. Then, you will use some command to try to compile the file. You'll either get
a message that the program contains syntax errors, or you'll get a compiled version of
the program. In the case of Java, the program is compiled into Java bytecode, not into
machine language. Finally, you can run the compiled program by giving some
appropriate command. For Java, you will actually use an interpreter to execute the
Java bytecode. Your programming environment might automate some of the steps for
you, but you can be sure that the same three steps are being done in the background.
Here is a Java program to display the message "Hello World!". Don't expect to
understand what's going on here just yet -- some of it you won't really understand
until a few chapters from now:
public class HelloWorld {
optional-variable-declarations-and-subroutines
optional-variable-declarations-and-subroutines
}
The name on the first line is the name of the program, as well as the name of the class.
If the name of the class is HelloWorld, then the class should be saved in a file called
HelloWorld.java. When this file is compiled, another file named HelloWorld.class will
be produced. This class file, HelloWorld.class, contains the Java bytecode that is
executed by a Java interpreter. HelloWorld.java is called the source code for the
program. To execute the program, you only need the compiled class file, not the
source code.
Also note that according to the above syntax specification, a program can contain
other subroutines besides main(), as well as things called "variable declarations."
You'll learn more about these later (starting with variables, in the next section).
By the way, recall that one of the neat features of Java is that it can be used to write
applets that can run on pages in a Web browser. Applets are very different things from
stand-alone programs such as the HelloWorld program, and they are not written in the
same way. For one thing, an applet doesn't have a main() routine. Applets will be
covered in the next chapters. In the meantime, you will see applets in this text that
simulate stand-alone programs. The applets you see are not really the same as the
stand-alone programs that they simulate, since they run right on a Web page, but they
will have the same behavior as the programs I describe. Here, just for fun, is an applet
simulating the HelloWorld program. To run the program, click on the button:
Key Features
Platform Independence
Java Server Pages technology delivers "Write Once, Run Anywhere" capability,
offering unprecedented reuse on any platform, any server. JavaServer Pages provide a
component-based, platform-independent method for building Web-based applications.
Most Web and application servers are currently delivering or are about to deliver
products that support the JavaServer Pages technology. This widespread, multi-
platform support empowers Web developers to write their JavaServer Pages code once
and run it anywhere.
Execution environment
Programs intended to run on a JVM must be compiled into a standardized portable
binary format, which typically comes in the form of .class files. A program may
consist of many classes, in which case, every class will be in a different file. For
easier distribution of large programs, multiple class files may be packaged together in
a .jar file.
This binary is then executed by the JVM runtime which carries out emulation of the
JVM instruction set by interpreting it or by applying a just-in-time compiler (JIT)
such as Sun's HotSpot.
The Java byte code is stack based. Therefore interpreter JVM's usually use a stack
architecture. In contrast, JIT compilers usually compile the byte code into register
based machine code. Each thread has its own stack and program counter.
Bytecode verifier
The JVM verifies all bytecode before it is executed. This means that only a limited
amount of bytecode sequences form valid programs, e.g. a JUMP (branch) instruction
can only target an instruction within the same function. Because of this, the fact that
JVM is a stack architecture does not imply a speed penalty for emulation on register
based architectures when using a JIT compiler: in the face of the code-verified JVM
architecture, it makes no difference to a JIT compiler whether it gets named imaginary
registers or imaginary stack positions that need to be allocated to the target
architectures registers. In fact, code verification makes the JVM different from a
classic stack architecture whose efficient emulation with a JIT compiler is more
complicated and typically carried out by a slower interpreter.
Code verification also ensures that arbitrary bit patterns cannot get used as an address.
Memory protection is achieved without the need for an MMU. Thus, JVM is an
efficient way of getting memory protection on simple silicon that has no MMU.
Bytecodes
The JVM has instructions for the following groups of tasks
Load and store
Arithmetic
Type conversion
Object creation and manipulation
Operand stack management (push / pop)
Control transfer (branching)
Method invocation and return
Throwing exceptions
The aim is binary compatibility. Each particular host operating system needs its own
implementation of the JVM and runtime. These JVMs interpret the byte code
semantically the same way, but the actual implementation may be different. More
complicated than just the emulation of bytecode is compatible and efficient
implementation of the Java core API which has to be mapped to each host operating
system.
Secure execution of remote code
A virtual machine architecture allows very fine-grained control over the actions that
code within the machine is permitted to take. This is designed to allow safe execution
of untrusted code from remote sources, a model used most famously by Java applets.
Applets run within a VM incorporated into a user's browser, executing code
downloaded from a remote HTTP server. The remote code runs in a highly restricted
"sandbox", which is designed to protect the user from misbehaving or malicious code.
Publishers with sufficient financial resources can apply for a certificate with which to
digitally sign applets as "safe", giving them permission to break out of the sandbox
and access the local file system and network, presumably under user control
The Java Virtual Machine
Why, you might wonder, use the intermediate Java bytecode at all? Why not just
distribute the original Java program and let each person compile it into the machine
language of whatever computer they want to run it on? There are many reasons. First
of all, a compiler has to understand Java, a complex high-level language. The
compiler is itself a complex program. A Java bytecode interpreter, on the other hand,
is a fairly small, simple program. This makes it easy to write a bytecode interpreter for
a new type of computer; once that is done, that computer can run any compiled Java
program. It would be much harder to write a Java compiler for the same computer.
Furthermore, many Java programs are meant to be downloaded over a network. This
leads to obvious security concerns: you don't want to download and run a program
that will damage your computer or your files. The bytecode interpreter acts as a buffer
between you and the program you download. You are really running the interpreter,
which runs the downloaded program indirectly. The interpreter can protect you from
potentially dangerous actions on the part of that program.
I should note that there is no necessary connection between Java and Java bytecode. A
program written in Java could certainly be compiled into the machine language of a
real computer. And programs written in other languages could be compiled into Java
bytecode. However, it is the combination of Java and Java bytecode that is platform-
independent, secure, and network-compatible while allowing you to program in a
modern high-level object-oriented language.
Garbage Collection
The name "garbage collection" implies that objects that are no longer needed by the
program are "garbage" and can be thrown away. A more accurate and up-to-date
metaphor might be "memory recycling." When an object is no longer referenced by
the program, the heap space it occupies must be recycled so that the space is available
for subsequent new objects. The garbage collector must somehow determine which
objects are no longer referenced by the program and make available the heap space
occupied by such unreferenced objects. In the process of freeing unreferenced objects,
the garbage collector must run any finalizers of objects being freed.
In addition to freeing unreferenced objects, a garbage collector may also combat heap
fragmentation. Heap fragmentation occurs through the course of normal program
execution. New objects are allocated, and unreferenced objects are freed such that free
blocks of heap memory are left in between blocks occupied by live objects. Requests
to allocate new objects may have to be filled by extending the size of the heap even
though there is enough total unused space in the existing heap. This will happen if
there is not enough contiguous free heap space available into which the new object
will fit. On a virtual memory system, the extra paging required to service an ever
growing heap can degrade the performance of the executing program.
This article does not describe an official Java garbage-collected heap, because none
exists. The JVM specification says only that the heap of the Java virtual machine must
be garbage collected. The specification does not define how the garbage collector
must work. The designer of each JVM must decide how to implement the garbage-
collected heap. This article describes various garbage collection techniques that have
been developed and demonstrates a particular garbage collection technique in an
applet.
Why garbage collection.
Garbage collection relieves programmers from the burden of freeing allocated
memory. Knowing when to explicitly free allocated memory can be very tricky.
Giving this job to the JVM has several advantages. First, it can make programmers
more productive. When programming in non-garbage-collected languages the
programmer can spend many late hours (or days or weeks) chasing down an elusive
memory problem. When programming in Java the programmer can use that time more
advantageously by getting ahead of schedule or simply going home to have a life.
A second advantage of garbage collection is that it helps ensure program integrity.
Garbage collection is an important part of Java's security strategy. Java programmers
are unable to accidentally (or purposely) crash the JVM by incorrectly freeing
memory.
A potential disadvantage of a garbage-collected heap is that it adds an overhead that
can affect program performance. The JVM has to keep track of which objects are
being referenced by the executing program, and finalize and free unreferenced objects
on the fly. This activity will likely require more CPU time than would have been
required if the program explicitly freed unnecessary memory. In addition,
programmers in a garbage-collected environment have less control over the
scheduling of CPU time devoted to freeing objects that are no longer needed.
Fortunately, very good garbage collection algorithms have been developed, and
adequate performance can be achieved for all but the most demanding of applications.
Because Java's garbage collector runs in its own thread, it will, in most cases, run
transparently alongside the execution of the program. Plus, if a programmer really
wants to explicitly request a garbage collection at some point, System.gc() or
Runtime.gc() can be invoked, which will fire off a garbage collection at that time.
The Java programmer must keep in mind that it is the garbage collector that runs
finalizers on objects. Because it is not generally possible to predict exactly when
unreferenced objects will be garbage collected, it is not possible to predict when
object finalizers will be run. Java programmers, therefore, should avoid writing code
for which program correctness depends upon the timely finalization of objects. For
example, if a finalizer of an unreferenced object releases a resource that is needed
again later by the program, the resource will not be made available until after the
garbage collector has run the object finalizer. If the program needs the resource before
the garbage collector has gotten around to finalizing the unreferenced object, the
program is out of luck.
CHAPTER TWO
Variables
A variable is a programming language abstraction that represents a storage location.
A Java variable has the following attributes:
name
The name of a variable is the label used to identify a variable in the text of a program.
type
The type of a variable determines the set of values that the variable can have and the
set of operations that can be performed on that variable.
value
The value of a variable is the content of the memory location(s) occupied by that
variable. How the contents of the memory locations are interpreted is determined by
the type of the variable.
lifetime
The lifetime of a variable is the interval of time in the execution of a Java program
during which a variable is said to exist. Local variables exist as long as the method in
which they are declared is active. Non-static fields of a class exist as long as the
object of which they are members exist. Static fields of a class exist as long as the
class in which they are defined remains loaded in the Java virtual machine .
scope
The scope of a variable is the range of statements in the text of a program in which
that variable can be referenced.
Consider the Java variable declaration statement:
int i = 57;
This statement defines a variable and binds various attributes with that variable. The
name of the variable is i, the type of the variable is int, and its initial value is 57.
Some attributes of a variable, such its name and type, are bound at compile time. This
is called static binding. Other attributes of a variable, such as its value, may be bound
at run time. This is called dynamic binding.
There are two kinds of Java variables--local variables and fields. A local variable is
a variable declared inside a method. A field is a variable declared in some class.
(Classes are discussed in Section ). The type of a Java variable is either one of the
primitive types or it is a reference type.
Primitive Types
The Java primitive types are boolean, char, short, int, long, float, and double. The
Java language specification[16] defines the range of values provided by each
primitive type and the set of operations supported by each type.
Every variable of a primitive type is a distinct instance of that type. Thus, an
assignment statement such as
y = x;
takes the value of the variable x and copies that value into the variable y. After the
assignment, x and y remain distinct instances that happen to have equal values.
A comparison of the the form
if (x == y)
{ /* ... */ }
tests whether the values contained in the variables x and y are equal.
References Types
Null References
In Java, it is possible for a reference type variable to refer to nothing at all. A
reference that refers to nothing at all is called a null reference . By default, an
uninitialized reference is null.
We can explicitly assign the null reference to a variable like this:
f = null;
Also, we can test explicitly for the null reference like this
if (f == null)
{ /* ... */ }
Parameter Passing
Parameter passing methods are the ways in which parameters are transfered between
methods when one method calls another. Java provides only one parameter passing
method--pass-by-value .
Passing Primitive Types
Consider the pair of Java methods defined in Program . On line 7, the method one
calls the method two. In general, every method call includes a (possibly empty) list of
arguments. The arguments specified in a method call are called actual parameters . In
this case, there is only one actual parameter--y.
CHAPTER THREE
Objects and Classes
``An object is a class instance or an array'' The class of an object determines what
it is and how it can be manipulated. A class encapsulates methods, data, and
semantics. This encapsulation is like a contract between the implementer of the class
and the user of that class.
The class construct is what makes Java an object-oriented language. A Java class
definition groups a set of values with a set of operations. Classes facilitate modularity
and information hiding. The user of a class manipulates object instances of that class
only through the methods provided by that class.
It is often the case that different classes possess common features. Different classes
may share common values; they may perform the same operations; they may support
common interfaces. In Java such relationships are expressed using derivation and
inheritance.
Constructors
A constructor is a method that has the same name as its class (and which has no
return value). Three constructors are defined in Program . The purpose of a
constructor is to initialize an object. A constructor is invoked whenever a new instance
of a class is created using the new operator.
Consider the following sequence of variable declarations:
Complex c = new Complex (); // calls Complex ()
Complex d = new Complex (2.0); // calls Complex (double)
Complex i = new Complex (0, 1); // calls Complex (double, double)
Consider the constructor that takes two double arguments, x and y (lines 6-10). This
constructor initializes the complex number by assigning x and y to the real and imag
fields, respectively.
Mutators
A mutator is a method that can modify an object. In the simplest case, a mutator just
assigns a new value to one of the fields. In general, a mutator performs some
computation and modifies any number of fields.
The setReal and setImag methods defined in Program are mutators. Program
defines three more mutators for the Complex class, setR, setTheta, and assign. All
three of these assign new values to the real and imag fields, as appropriate.
Program: Complex class mutator methods.
Inner Classes
In Java it is possible to define one class inside another. A class defined inside another
one is called an inner class . Java provides two kinds of inner classes--static and non-
static.
void f () {}
}
}
This fragment defines the class A which contains an static inner class B.
A static inner class behaves like any ``outer'' class. It may contain methods and fields,
and it may be instantiated like this:
A.B object = new A.B ();
This statement creates an new instance of the inner class B. Given such an instance,
we can invoke the f method in the usual way:
object.f();
Note, it is not necessarily the case that an instance of the outer class A exists even
when we have created an instance of the inner class. Similarly, instantiating the outer
class A does not create any instances of the inner class B.
The methods of a static inner class may access all the members (fields or methods) of
the inner class but they can access only static members (fields or methods) of the
outer class. Thus, f can access the field x, but it cannot access the field y.
Non-Static Inner Classes
By default, an inner class is non-static:
public class A
{
int y;
public class B
{
int x;
void f () {}
}
}
This fragment defines the class A which contains a non-static inner class B.
A non-static inner class can be instantiated only inside a non-static method of the
outer class. This is because every instance of a non-static inner class must be
associated with an instance of the outer class. In a sense, every instance of a non-static
inner class exists ``inside'' an instance of the outer class. A single instance of the outer
class may have associated with it more than one instance of the inner class.
Because an instance of a non-static inner class has an associated instance of the outer
class, the methods of the inner class can access directly any of the members (fields or
methods) of the outer class instance. For example, the f method defined above can
access both x and y directly.
The Java keyword this can be used in a non-static method to refer to the current
object instance. Thus in the method f, this refers to an instance of the inner B class.
Every non-static inner class is associated with an instance of the outer class. To access
the outer class instance inside the method f we write A.this
Interfaces
Abstract Methods and Abstract Classes
Method Resolution
Abstract Classes and Concrete Classes
Algorithmic Abstraction
Interfaces
Consider a program for creating simple drawings. Suppose the program provides a set
of primitive graphical objects, such as circles, rectangles, and squares. The user of the
program selects the desired objects, and then invokes commands to draw, to erase, or
to move them about. Ideally, all graphical objects support the same set of operations.
Nevertheless, the way that the operations are implemented varies from one object to
the next.
We implement this as follows: First, we define a Java interface which represents the
common operations provided by all graphical objects. A Java interface declares a set
of methods. An object that supports an interface must provide
Program defines the GraphicsPrimitives interface comprised of three methods,
draw, erase, and moveTo. the methods declared in the interface.
Method Resolution
Consider the following sequence of instructions:
GraphicalObject g1 = new Circle (new Point (0,0), 5);
GraphicalObject g2 = new Square (new Point (0,0), 5);
g1.draw ();
g2.draw ();
The statement g1.draw() calls Circle.draw whereas the statement g2.draw() calls
Rectangle.draw.
It is as if every object of a class ``knows'' the actual method to be invoked when a
method is called on that object. E.g, a Circle ``knows'' to call Circle.draw,
GraphicalObject.erase and GraphicalObject.moveTo, whereas a Square ``knows'' to
call Rectangle.draw, GraphicalObject.erase and GraphicalObject.moveTo.
In this way, Java ensures that the ``correct'' method is actually called, regardless of
how the object is accessed. Consider the following sequence:
Square s = new Square (new Point (0,0), 5);
Rectangle r = s;
GraphicalObject g = r;
Here s, r and g all refer to the same object, even though they are all of different types.
However, because the object is a Square, s.draw(), r.draw() and g.draw() all invoke
Rectangle.draw.
CHAPTER FOUR
Subroutines
Black Boxes
A subroutine is sometimes said to be a "black box" because you can't see what's
"inside" it (or, to be more precise, you usually don't want to see inside it, because then
you would have to deal with all the complexity that the subroutine is meant to hide).
Of course, a black box that has no way of interacting with the rest of the world would
be pretty useless. A black box needs some kind of interface with the rest of the world,
which allows some interaction between what's inside the box and what's outside. A
physical black box might have buttons on the outside that you can push, dials that you
can set, and slots that can be used for passing information back and forth. Since we
are trying to hide complexity, not create it, we have the first rule of black boxes:
Are there any examples of black boxes in the real world? Yes; in fact, you are
surrounded by them. Your television, your car, your VCR, your refrigerator... You can
turn your television on and off, change channels, and set the volume by using
elements of the television's interface -- dials, remote control, don't forget to plug in the
power -- without understanding anything about how the thing actually works. The
same goes for a VCR, although if stories about how hard people find it to set the time
on a VCR are true, maybe the VCR violates the simple interface rule.
Now, a black box does have an inside -- the code in a subroutine that actually
performs the task, all the electronics inside your television set. The inside of a black
box is called its implementation. The second rule of black boxes is that
To use a black box, you shouldn't need to know anything about its
implementation; all you need to know is its interface.
Of course, to have a black box, someone must have designed and built the
implementation in the first place. The black box idea works to the advantage of the
implementor as well as of the user of the black box. After all, the black box might be
used in an unlimited number of different situations. The implementor of the black box
doesn't need to know about any of that. The implementor just needs to make sure that
the box performs its assigned task and interfaces correctly with the rest of the world.
This is the third rule of black boxes:
The implementor of a black box should not need to know anything about the
larger systems in which the box will be used.
In a way, a black box divides the world into two parts: the inside (implementation)
and the outside. The interface is at the boundary, connecting those two parts.
By the way, you should not think of an interface as just the physical connection
between the box and the rest of the world. The interface also includes a specification
of what the box does and how it can be controlled by using the elements of the
physical interface. It's not enough to say that a TV set has a power switch; you need to
specify that the power switch is used to turn the TV on and off!
To put this in computer science terms, the interface of a subroutine has a semantic as
well as a syntactic component. The syntactic part of the interface tells you just what
you have to type in order to call the subroutine. The semantic component specifies
exactly what task the subroutine will accomplish. To write a legal program, you need
to know the syntactic specification of the subroutine. To understand the purpose of the
subroutine and to use it effectively, you need to know the subroutine's semantic
specification. I will refer to both parts of the interface -- syntactic and semantic --
collectively as the contract of the subroutine.
It will take us a while -- most of the chapter -- to get through what all this means in
detail. Of course, you've already seen examples of subroutines in previous chapters,
such as the main() routine of a program and the paint() routine of an applet. So you
are familiar with the general format.
The statements between the braces, { and }, make up the body of the subroutine.
These statements are the inside, or implementation part, of the "black box", as
discussed in the previous section. They are the instructions that the computer executes
when the method is called. Subroutines can contain any of the statements discussed in
Chapter 2 and Chapter 3.
The modifiers that can occur at the beginning of a subroutine definition are words
that set certain characteristics of the method, such as whether it is static or not. The
modifiers that you've seen so far are "static" and "public". There are only about a
half-dozen possible modifiers altogether.
If the subroutine is a function, whose job is to compute some value, then the return-
type is used to specify the type of value that is returned by the function. We'll be
looking at functions and return types in some detail in Section 4. If the subroutine is
not a function, then the return-type is replaced by the special value void, which
indicates that no value is returned. The term "void" is meant to indicate that the return
value is empty or non-existent.
Finally, we come to the parameter-list of the method. Parameters are part of the
interface of a subroutine. They represent information that is passed into the subroutine
from outside, to be used by the subroutine's internal computations. For a concrete
example, imagine a class named Television that includes a method named
changeChannel(). The immediate question is: What channel should it change to? A
parameter can be used to answer this question. Since the channel number is an integer,
the type of the parameter would be int, and the declaration of the changeChannel()
method might look like
The parameter list in a subroutine can be empty, or it can consist of one or more
parameter declarations of the form type parameter-name. If there are several
declarations, they are separated by commas. Note that each declaration can name only
one parameter. For example, if you want two parameters of type double, you have to
say "double x, double y", rather than "double x, y".
Here are a few examples of subroutine definitions, leaving out the statements that
define what the subroutines do:
int getNextN(int N) {
// there are no modifiers; "int" in the return-type
// "getNextN" is the subroutine-name; the parameter-list
// includes one parameter whose name is "N" and whose
// type is "int"
. . . // statements that define what getNextN does go
here
}
static boolean lessThan(double x, double y) {
// "static" is a modifier; "boolean" is the
// return-type; "lessThan" is the subroutine-name; the
// parameter-list includes two parameters whose names are
// "x" and "y", and the type of each of these parameters
// is "double"
. . . // statements that define what lessThan does go
here
}
In the second example given here, getNextN, is a non-static method, since its
definition does not include the modifier "static" -- and so it's not an example that we
should be looking at in this chapter! The other modifier shown in the examples is
"public". This modifier indicates that the method can be called from anywhere in a
program, even from outside the class where the method is defined. There is another
modifier, "private", which indicates that the method can be called only from inside
the same class. The modifiers public and private are called access specifiers. If no
access specifier is given for a method, then by default, that method can be called from
anywhere in the "package" that contains the class, but not from outside that package.
(Packages were mentioned in Section 3.7, and you'll learn more about packages in this
chapter, in Section 5.) There is one other access modifier, protected, which will only
become relevant when we turn to object-oriented programming in Chapter 5.
Note, by the way, that the main() routine of a program follows the usual syntax rules
for a subroutine. In
the modifiers are public and static, the return type is void, the subroutine name is
main, and the parameter list is "String[] args". The only question might be about
"String[]", which has to be a type if it is to match the format of a parameter list. In
fact, String[] represents a so-called "array type", so the syntax is valid. We will
cover arrays in Chapter 8. (The parameter, args, represents information provided to
the program when the main() routine is called by the system. In case you know the
term, the information consists of any "command-line arguments" specified in the
command that the user typed to run the program.)
You've already had some experience with filling in the statements of a subroutine. In
this chapter, you'll learn all about writing your own complete subroutine definitions,
including the interface part.
When you define a subroutine, all you are doing is telling the computer that the
subroutine exists and what it does. The subroutine doesn't actually get executed until
it is called. (This is true even for the main() routine in a class -- even though you
don't call it, it is called by the system when the system runs your program.) For
example, the playGame() method defined above could be called using the following
subroutine call statement:
playGame();
This statement could occur anywhere in the same class that includes the definition of
playGame(), whether in a main() method or in some other subroutine. Since
playGame() is a public method, it can also be called from other classes, but in that
case, you have to tell the computer which class it comes from. Let's say, for example,
that playGame() is defined in a class named Poker. Then to call playGame() from
outside the Poker class, you would have to say
Poker.playGame();
The use of the class name here tells the computer which class to look in to find the
method. It also lets you distinguish between Poker.playGame() and other potential
playGame() methods defined in other classes, such as Roulette.playGame() or
Blackjack.playGame().
subroutine-name(parameters);
class-name.subroutine-name(parameters);
It's time to give an example of what a complete program looks like, when it includes
other subroutines in addition to the main() routine. Let's write a program that plays a
guessing game with the user. The computer will choose a random number between 1
and 100, and the user will try to guess it. The computer tells the user whether the
guess is high or low or correct. If the user gets the number after six guesses or fewer,
the user wins the game. After each game, the user has the option of continuing with
another game.
Since playing one game can be thought of as a single, coherent task, it makes sense to
write a subroutine that will play one guessing game with the user. The main() routine
will use a loop to call the playGame() subroutine over and over, as many times as the
user wants to play. We approach the problem of designing the playGame() subroutine
the same way we write a main() routine: Start with an outline of the algorithm and
apply stepwise refinement. Here is a short pseudocode algorithm for a guessing game
program:
With variable declarations added and translated into Java, this becomes the definition
of the playGame() routine. A random integer between 1 and 100 can be computed as
(int)(100 * Math.random()) + 1. I've cleaned up the interaction with the user to
make it flow better.
Now, where exactly should you put this? It should be part of the same class as the
main() routine, but not inside the main routine. It is not legal to have one subroutine
physically nested inside another. The main() routine will call playGame(), but not
contain it physically. You can put the definition of playGame() either before or after
the main() routine. Java is not very picky about having the members of a class in any
particular order.
It's pretty easy to write the main routine. You've done things like this before. Here's
what the complete program looks like (except that a serious program needs more
comments than I've included here).
Take some time to read the program carefully and figure out how it works. And try to
convince yourself that even in this relatively simple case, breaking up the program
into two methods makes the program easier to understand and probably made it easier
to write each piece.
A class can include other things besides subroutines. In particular, it can also include
variable declarations. Of course, you can have variable declarations inside
subroutines. Those are called local variables. However, you can also have variables
that are not part of any subroutine. To distinguish such variables from local variables,
we call them member variables, since they are members of a class.
Just as with subroutines, member variables can be either static or non-static. In this
chapter, we'll stick to static variables. A static member variable belongs to the class
itself, and it exists as long as the class exists. Memory is allocated for the variable
when the class is first loaded by the Java interpreter. Any assignment statement that
assigns a value to the variable changes the content of that memory, no matter where
that assignment statement is located in the program. Any time the variable is used in
an expression, the value is fetched from that same memory, no matter where the
expression is located in the program. This means that the value of a static member
variable can be set in one subroutine and used in another subroutine. Static member
variables are "shared" by all the static subroutines in the class. A local variable in a
subroutine, on the other hand, exists only while that subroutine is being executed, and
is completely inaccessible from outside that one subroutine.
The declaration of a member variable looks just like the declaration of a local variable
except for two things: The member variable is declared outside any subroutine
(although it still has to be inside a class), and the declaration can be marked with
modifiers such as static, public, and private. Since we are only working with
static member variables for now, every declaration of a member variable in this
chapter will include the modifier static. For example:
A static member variable that is not declared to be private can be accessed from
outside the class where it is defined, as well as inside. When it is used in some other
class, it must be referred to with a compound identifier of the form class-
name.variable-name. For example, the System class contains the public static
member variable named out, and you use this variable in your own classes by
referring to System.out. If numberOfPlayers is a public static member variable in a
class named Poker, subroutines in the Poker class would refer to it simply as
numberOfPlayers. Subroutines in another class would refer to it as
Poker.numberOfPlayers.
As an example, let's add a static member variable to the GuessingGame class that we
wrote earlier in this section. This variable will be used to keep track of how many
games the user wins. We'll call the variable gamesWon and declare it with the
statement "static int gamesWon;" In the playGame() routine, we add 1 to
gamesWon if the user wins the game. At the end of the main() routine, we print out the
value of gamesWon. It would be impossible to do the same thing with a local variable,
since we need access to the same variable from both subroutines.
When you declare a local variable in a subroutine, you have to assign a value to that
variable before you can do anything with it. Member variables, on the other hand are
automatically initialized with a default value. For numeric variables, the default value
is zero. For boolean variables, the default is false. And for char variables, it's the
unprintable character that has Unicode code number zero. (For objects, such as
Strings, the default initial value is a special value called null, which we won't
encounter officially until later.)
Since it is of type int, the static member variable gamesWon automatically gets
assigned an initial value of zero. This happens to be the correct initial value for a
variable that is being used as a counter. You can, of course, assign a different value to
the variable at the beginning of the main() routine if you are not satisfied with the
default initial value.
Parameters
As an example, let's go back to the "3N+1" problem that was discussed in Section 3.2.
(Recall that a 3N+1 sequence is computed according to the rule, "if N is odd, multiply
by 3 and add 1; if N is even, divide by 2; continue until N is equal to 1." For example,
starting from N=3 we get the sequence: 3, 10, 5, 16, 8, 4, 2, 1.) Suppose that we want
to write a subroutine to print out such sequences. The subroutine will always perform
the same task: Print out a 3N+1 sequence. But the exact sequence it prints out depends
on the starting value of N. So, the starting value of N would be a parameter to the
subroutine. The subroutine could be written like this:
while (N > 1) {
if (N % 2 == 1) // is N odd?
N = 3 * N + 1;
else
N = N / 2;
count++; // count this term
TextIO.putln(N); // print this term
}
TextIO.putln();
TextIO.putln("There were " + count + " terms in the
sequence.");
} // end of Print3NSequence()
The parameter list of this subroutine, "(int startingValue)", specifies that the
subroutine has one parameter, of type int. When the subroutine is called, a value
must be provided for this parameter. This value is assigned to the parameter,
startingValue, before the body of the subroutine is executed. For example, the
subroutine could be called using the subroutine call statement
"Print3NSequence(17);". When the computer executes this statement, the computer
assigns the value 17 to startingValue and then executes the statements in the
subroutine. This prints the 3N+1 sequence starting from 17. If K is a variable of type
int, then when the computer executes the subroutine call statement
"Print3NSequence(K);", it will take the value of the variable K, assign that value to
startingValue, and execute the body of the subroutine.
The class that contains Print3NSequence can contain a main() routine (or other
subroutines) that call Print3NSequence. For example, here is a main() program that
prints out 3N+1 sequences for various starting values specified by the user:
Note that the term "parameter" is used to refer to two different, but related, concepts.
There are parameters that are used in the definitions of subroutines, such as
startingValue in the above example. And there are parameters that are used in
subroutine call statements, such as the K in the statement "Print3NSequence(K);".
Parameters in a subroutine definition are called formal parameters or dummy
parameters. The parameters that are passed to a subroutine when it is called are called
actual parameters. When a subroutine is called, the actual parameters in the subroutine
call statement are evaluated and the values are assigned to the formal parameters in
the subroutine's definition. Then the body of the subroutine is executed.
A formal parameter must be an identifier, that is, a name. A formal parameter is very
much like a variable, and -- like a variable -- it has a specified type such as int,
boolean, or String. An actual parameter is a value, and so it can be specified by any
expression, provided that the expression computes a value of the correct type. The
type of the actual parameter must be one that could legally be assigned to the formal
parameter with an assignment statement. For example, if the formal parameter is of
type double, then it would be legal to pass an int as the actual parameter since ints
can legally be assigned to doubles. When you call a subroutine, you must provide
one actual parameter for each formal parameter in the subroutine's definition.
Consider, for example, a subroutine
When the computer executes this statement, it has essentially the same effect as the
block of statements:
{
int N; // Allocate memory locations for the formal
parameters.
double x;
boolean test;
N = 17; // Assign 17 to the first formal
parameter, N.
x = Math.sqrt(z+1); // Compute Math.sqrt(z+1), and assign it
to
// the second formal parameter, x.
test = (z >= 10); // Evaluate "z >= 10" and assign the
resulting
// true/false value to the third
formal
// parameter, test.
// statements to perform the task go here
}
Java is somewhat unusual in that it allows two different subroutines in the same class
to have the same name, provided that their signatures are different. (The language C+
+ on which Java is based also has this feature.) We say that the name of the subroutine
is overloaded because it has several different meanings. The computer doesn't get the
subroutines mixed up. It can tell which one you want to call by the number and types
of the actual parameters that you provide in the subroutine call statement. You have
already seen overloading used in the TextIO class. This class includes many different
methods named putln, for example. These methods all have different signatures, such
as:
Of course all these different subroutines are semantically related, which is why it is
acceptable programming style to use the same name for them all. But as far as the
computer is concerned, printing out an int is very different from printing out a
String, which is different from printing out a boolean, and so forth -- so that each of
these operations requires a different method.
Note, by the way, that the signature does not include the subroutine's return type. It is
illegal to have two subroutines in the same class that have the same signature but that
have different return types. For example, it would be a syntax error for a class to
contain two methods defined as:
So it should be no surprise that in the TextIO class, the methods for reading different
types are not all named getln(). In a given class, there can only be one routine that
has the name getln and has no parameters. The input routines in TextIO are
distinguished by having different names, such as getlnInt() and getlnDouble().
Writing a subroutine always means filling out this format. The assignment tells us that
there is one parameter, of type int, and it tells us what the statements in the body of
the subroutine should do. Since we are only working with static subroutines for now,
we'll need to use static as a modifier. We could add an access modifier (public or
private), but in the absence of any instructions, I'll leave it out. Since we are not told
to return a value, the return type is void. Since no names are specified, we'll have to
make up names for the formal parameter and for the subroutine itself. I'll use N for the
parameter and printDivisors for the subroutine name. The subroutine will look like
and all we have left to do is to write the statements that make up the body of the
routine. This is not difficult. Just remember that you have to write the body assuming
that N already has a value! The algorithm is: "For each possible divisor D in the range
from 1 to N, if D evenly divides N, then print D." Written in Java, this becomes:
I've added comments indicating the contract of the subroutine -- that is, what it does
and what assumptions it makes. The contract includes the assumption that N is a
positive integer. It is up to the caller of the subroutine to make sure that this
assumption is satisfied.
Here, we are told the name of the subroutine and the names of the two parameters, so
we don't have much choice about the first line of the subroutine definition. The task in
this case is pretty simple, so the body of the subroutine is easy to write. The complete
subroutine is given by
Note that in this case, the contract makes no assumption about N, but it makes it clear
what will happen in all cases, including the unexpected case that N < 0.
Finally, let's do an example that shows how one subroutine can build on another. Let's
write a subroutine that takes a String as a parameter. For each character in the string,
it will print a line of output containing 25 copies of that character. It should use the
printRow() subroutine to produce the output.
Again, we get to choose a name for the subroutine and a name for the parameter. I'll
call the subroutine printRowsFromString and the parameter str. The algorithm is
pretty clear: For each position i in the string str, call
printRow(str.charAt(i),25) to print one line of the output. So, we get:
Local variables have no connection to the outside world; they are purely part of the
internal working of the subroutine. Parameters are used to "drop" values into the
subroutine when it is called, but once the subroutine starts executing, parameters act
much like local variables. Changes made inside a subroutine to a formal parameter
have no effect on the rest of the program (at least if the type of the parameter is one of
the primitive types -- things are more complicated in the case of objects, as we'll see
later).
Things are different when a subroutine uses a variable that is defined outside the
subroutine. That variable exists independently of the subroutine, and it is accessible to
other parts of the program, as well as to the subroutine. Such a variable is said to be
global to the subroutine, as opposed to the "local" variables defined inside the
subroutine. The scope of a global variable includes the entire class in which it is
defined. Changes made to a global variable can have effects that extend outside the
subroutine where the changes are made. You've seen how this works in the last
example in the previous section, where the value of the global variable, gamesWon, is
computed inside a subroutine and is used in the main() routine.
It's not always bad to use global variables in subroutines, but you should realize that
the global variable then has to be considered part of the subroutine's interface. The
subroutine uses the global variable to communicate with the rest of the program. This
is a kind of sneaky, back-door communication that is less visible than communication
done through parameters, and it risks violating the rule that the interface of a black
box should be straightforward and easy to understand. So before you use a global
variable in a subroutine, you should consider whether it's really necessary.
I don't advise you to take an absolute stand against using global variables inside
subroutines. There is at least one good reason to do it: If you think of the class as a
whole as being a kind of black box, it can be very reasonable to let the subroutines
inside that box be a little sneaky about communicating with each other, if that will
make the class as a whole look simpler from the outside.
Return Values
(It is also legal to use a function call as a stand-alone statement, just as if it were a
regular subroutine. In this case, the computer ignores the value computed by the
subroutine. Sometimes this makes sense. For example, the function TextIO.getln(),
with a return type of String, reads and returns a line of input typed in by the user.
Usually, the line that is returned is assigned to a variable to be used later in the
program, as in the statement "name = TextIO.getln();". However, this function is
also useful as a subroutine call statement "TextIO.getln();", which still reads all
input up to and including the next carriage return. Since this input is not assigned to a
variable or used in an expression, it is simply discarded. Sometimes, discarding
unwanted input is exactly what you need to do.)
You've already seen how functions such as Math.sqrt() and TextIO.getInt() can
be used. What you haven't seen is how to write functions of your own. A function
takes the same form as a regular subroutine, except that you have to specify the value
that is to be returned by the subroutine. This is done with a return statement, which
takes the form:
return expression;
Such a return statement can only occur inside the definition of a function, and the
type of the expression must match the return type that was specified for the function.
(More exactly, it must be legal to assign the expression to a variable whose type is
specified by the return type.) When the computer executes this return statement, it
evaluates the expression, terminates execution of the function, and uses the value of
the expression as the returned value of the function.
Inside an ordinary subroutine -- with declared return type "void" -- you can use a
return statement with no expression to immediately terminate execution of the
subroutine and return control back to the point in the program from which the
subroutine was called. This can be convenient if you want to terminate execution
somewhere in the middle of the subroutine, but return statements are optional in
non-function subroutines. In a function, on the other hand, a return statement, with
expression, is always required.
Here is a very simple function that could be used in a program to compute 3N+1
sequences. (The 3N+1 sequence problem is one we've looked at several times
already.) Given one term in a 3N+1 sequence, this function computes the next term of
the sequence:
Exactly one of the two return statements is executed to give the value of the
function. A return statement can occur anywhere in a function. Some people,
however, prefer to use a single return statement at the very end of the function. This
allows the reader to find the return statement easily. You might choose to write
nextN() like this, for example:
Here is a subroutine that uses this nextN function. In this case, the improvement from
the version in Section 3 is not great, but if nextN() were a long function that
performed a complex computation, then it would make a lot of sense to hide that
complexity inside a function:
while (N > 1) {
N = nextN( N ); // Compute next term,
// using the function
nextN.
count++; // Count this term.
TextIO.putln(N); // Print this term.
}
TextIO.putln();
TextIO.putln("There were " + count + " terms in the
sequence.");
} // end of Print3NSequence()
Here are a few more examples of functions. The first one computes a letter grade
corresponding to a given numerical grade, on a typical grading scale:
The type of the return value of letterGrade() is char. Functions can return values
of any type at all. Here's a function whose return value is of type boolean. It
demonstrates some interesting programming points, so you should read the
comments:
if (N <= 1)
return false; // No number <= 1 is a prime.
Finally, here is a function with return type String. This function has a String as
parameter. The returned value is a reversed copy of the parameter. For example, the
reverse of "Hello World" is "dlroW olleH". The algorithm for computing the reverse
of a string, str, is to start with an empty string and then to append each character
from str, starting from the last character of str and working backwards to the first.
A palindrome is a string that reads the same backwards and forwards, such as "radar".
The reverse() function could be used to check whether a string, word, is a
palindrome by testing "if (word.equals(reverse(word)))".
By the way, a typical beginner's error in writing functions is to print out the answer,
instead of returning it. This represents a fundamental misunderstanding. The task of a
function is to compute a value and return it to the point in the program where the
function was called. That's where the value is used. Maybe it will be printed out.
Maybe it will be assigned to a variable. Maybe it will be used in an expression. But
it's not for the function to decide.
I'll finish this section with a complete new version of the 3N+1 program. This will
give me a chance to show the function nextN(), which was defined above, used in a
complete program. I'll also take the opportunity to improve the program by getting it
to print the terms of the sequence in columns, with five terms on each line. This will
make the output more presentable. This idea is this: Keep track of how many terms
have been printed on the current line; when that number gets up to 5, start a new line
of output. To make the terms line up into columns, I will use the version of
TextIO.put() with signature put(int,int). The second int parameter tells how wide
the columns should be.
/*
A program that computes and displays several 3N+1
sequences. Starting values for the sequences are
input by the user. Terms in a sequence are printed
in columns, with five terms on each line of output.
After a sequence has been displayed, the number of
terms in that sequence is reported to the user.
*/
} // end main()
while (N > 1) {
N = nextN(N); // compute next term
count++; // count this term
if (onLine == 5) { // If current output line is full
TextIO.putln(); // ...then output a carriage
return
onLine = 0; // ...and note that there are no
terms
// on the new line.
}
TextIO.put(N, 8); // Print this term in an 8-char
column.
onLine++; // Add 1 to the number of terms on this
line.
}
} // end of Print3NSequence()
You should read this program carefully and try to understand how it works. Here is an
applet version for you to try:
Someone who wants to program for Macintosh computers -- and to produce programs
that look and behave the way users expect them to -- must deal with the Macintosh
Toolbox, a collection of well over a thousand different subroutines. There are routines
for opening and closing windows, for drawing geometric figures and text to windows,
for adding buttons to windows, and for responding to mouse clicks on the window.
There are other routines for creating menus and for reacting to user selections from
menus. Aside from the user interface, there are routines for opening files and reading
data from them, for communicating over a network, for sending output to a printer, for
handling communication between programs, and in general for doing all the standard
things that a computer has to do. Windows 98 and Windows 2000 provide their own
sets of subroutines for programmers to use, and they are quite a bit different from the
subroutines used on the Mac.
The analogy of a "toolbox" is a good one to keep in mind. Every programming project
involves a mixture of innovation and reuse of existing tools. A programmer is given a
set of tools to work with, starting with the set of basic tools that are built into the
language: things like variables, assignment statements, if statements, and loops. To
these, the programmer can add existing toolboxes full of routines that have already
been written for performing certain tasks. These tools, if they are well-designed, can
be used as true black boxes: They can be called to perform their assigned tasks
without worrying about the particular steps they go through to accomplish those tasks.
The innovative part of programming is to take all these tools and apply them to some
particular project or problem (word-processing, keeping track of bank accounts,
processing image data from a space probe, Web browsing, computer games,...). This
is called applications programming.
A software toolbox is a kind of black box, and it presents a certain interface to the
programmer. This interface is a specification of what routines are in the toolbox, what
parameters they use, and what tasks they perform. This information constitutes the
API, or Applications Programming Interface, associated with the toolbox. The
Macintosh API is a specification of all the routines available in the Macintosh
Toolbox. A company that makes some hardware device -- say a card for connecting a
computer to a network -- might publish an API for that device consisting of a list of
routines that programmers can call in order to communicate with and control the
device. Scientists who write a set of routines for doing some kind of complex
computation -- such as solving "differential equations", say -- would provide an API
to allow others to use those routines without understanding the details of the
computations they perform.
Java is platform-independent. That is, the same program can run on platforms as
diverse as Macintosh, Windows, UNIX, and others. The same Java API must work on
all these platforms. But notice that it is the interface that is platform-independent; the
implementation varies from one platform to another. A Java system on a particular
computer includes implementations of all the standard API routines. A Java program
includes only calls to those routines. When the Java interpreter executes a program
and encounters a call to one of the standard routines, it will pull up and execute the
implementation of that routine which is appropriate for the particular platform on
which it is running. This is a very powerful idea. It means that you only need to learn
one API to program for a wide variety of platforms.
Like all subroutines in Java, the routines in the standard API are grouped into classes.
To provide larger-scale organization, classes in Java can be grouped into packages.
You can have even higher levels of grouping, since packages can also contain other
packages. In fact, the entire standard Java API is implemented in several packages.
One of these, which is named "java", contains the non-GUI packages as well as the
original AWT graphics user interface classes. Another package, "javax", was added in
Java version 1.2 and contains the classes used by the Swing graphical user interface.
A package can contain both classes and other packages. A package that is contained in
another package is sometimes called a "sub-package." Both the java package and the
javax package contain sub-packages. One of the sub-packages of java, for example,
is called "awt". Since awt is contained within java, its full name is actually
java.awt. This is the package that contains classes related to the AWT graphical user
interface, such as a Button class which represents push-buttons on the screen and the
Graphics class which provides routines for drawing on the screen. Since these classes
are contained in the package java.awt, their full names are actually
java.awt.Button and java.awt.Graphics. (I hope that by now you've gotten the
hang of how this naming thing works in Java.) Similarly, javax contains a sub-
package named javax.swing, which includes such classes as
javax.swing.JButton and javax.swing.JApplet.
The java package includes several other sub-packages, such as java.io, which
provides facilities for input/output, java.net, which deals with network
communication, and java.applet, which implements the basic functionality of
applets. The most basic package is called java.lang. This package contains
fundamental classes such as String and Math.
java.awt.Color rectColor;
import java.awt.Color;
at the beginning of a Java source code file, then, in the rest of the file, you can
abbreviate the full name java.awt.Color to just the name of the class, Color. This
would allow you to say just
Color rectColor;
to declare the variable rectColor. (The only effect of the import statement is to
allow you to use simple class names instead of full "package.class" names; you aren't
really importing anything substantial. If you leave out the import statement, you can
still access the class -- you just have to use its full name.) There is a shortcut for
importing all the classes from a given package. You can import all the classes from
java.awt by saying
import java.awt.*;
and you can import all the classes from javax.swing with the line
import javax.swing.*;
In fact, any Java program that uses a graphical user interface is likely to begin with
one or both of these lines. A program might also include lines such as "import
java.net.*;" or "import java.io.*;" to get easy access to networking and
input/output classes. (When you start importing lots of packages in this way, you have
to be careful about one thing: It's possible for two classes that are in different
packages to have the same name. For example, both the java.awt package and the
java.util package contain classes named List. If you import both java.awt.* and
java.util.*, the simple name List will be ambiguous. If you try to declare a
variable of type List, you will get a compiler error message about an ambiguous
class name. The solution is simple: use the full name of the class, either
java.awt.List or java.util.List. Another solution is to use import to import the
individual classes you need, instead of importing entire packages.)
Because the package java.lang is so fundamental, all the classes in java.lang are
automatically imported into every program. It's as if every program began with the
statement "import java.lang.*;". This is why we have been able to use the class
name String instead of java.lang.String, and Math.sqrt() instead of
java.lang.Math.sqrt(). It would still, however, be perfectly legal to use the longer
forms of the names.
Programmers can create new packages. Suppose that you want some classes that you
are writing to be in a package named utilities. Then the source code file that
defines those classes must begin with the line "package utilities;". Any program
that uses the classes should include the directive "import utilities.*;" to obtain
access to all the classes in the utilities package. Unfortunately, things are a little
more complicated than this. Remember that if a program uses a class, then the class
must be "available" when the program is compiled and when it is executed. Exactly
what this means depends on which Java environment you are using. Most commonly,
classes in a package named utilities should be in a directory with the name
utilities, and that directory should be located in the same place as the program that
uses the classes.
In projects that define large numbers of classes, it makes sense to organize those
classes into one or more packages. It also makes sense for programmers to create new
packages as toolboxes that provide functionality and API's for dealing with areas not
covered in the standard Java API. (And in fact such "toolmaking" programmers often
have more prestige than the applications programmers who use their tools.)
However, I will not be creating any packages in this textbook. You need to know
about packages mainly so that you will be able to import the standard packages. These
packages are always available to the programs that you write. You might wonder
where the standard classes are actually located. Again, that depends to some extent on
the version of Java that you are using. But they are likely to be collected together into
a large file named rt.jar or classes.zip, which is located in some place where the
Java compiler and the Java interpreter will know to look for it.
The precondition of a subroutine is something that must be true when the subroutine
is called, if the subroutine is to work correctly. For example, for the built-in function
Math.sqrt(x), a precondition is that the parameter, x, is greater than or equal to zero,
since it is not possible to take the square root of a negative number. In terms of a
contract, a precondition represents an obligation of the caller of the subroutine. If you
call a subroutine without meeting its precondition, then there is no reason to expect it
to work properly. The program might crash or give incorrect results, but you can only
blame yourself, not the subroutine.
Let's work through an example of program design using subroutines. In this example,
we will both use prewritten subroutines as building blocks and design new
subroutines that we need to complete the project.
Suppose that I have found an already-written class called Mosaic. This class allows a
program to work with a window that displays little colored rectangles arranged in
rows and columns. The window can be opened, closed, and otherwise manipulated
with static member subroutines defined in the Mosaic class. Here are some of the
available routines:
boolean Mosaic.isOpen();
Precondition: None.
Postcondition: The return value is true if the mosaic window
is open on the screen, and is false
otherwise.
Note: The window will be closed if the user clicks its
close box. It can also be closed programmatically by
calling the subroutine Mosaic.close().
My idea is to use the Mosaic class as the basis for a neat animation. I want to fill the
window with randomly colored squares, and then randomly change the colors in a
loop that continues as long as the window is open. "Randomly change the colors"
could mean a lot of different things, but after thinking for a while, I decide it would be
interesting to have a "disturbance" that wanders randomly around the window,
changing the color of each square that it encounters. Here's an applet that shows what
the program will do:
With basic routines for manipulating the window as a foundation, I can turn to the
specific problem at hand. A basic outline for my program is
Filling the window with random colors seems like a nice coherent task that I can work
on separately, so let's decide to write a separate subroutine to do it. The third step can
be expanded a bit more, into the steps: Start in the middle of the window, then keep
moving to a new square and changing the color of that square. This should continue as
long as the mosaic window is still open. Thus we can refine the algorithm to:
I need to represent the current position in some way. That can be done with two int
variables named currentRow and currentColumn. I'll use 10 rows and 20 columns of
squares in my mosaic, so setting the current position to be in the center means setting
currentRow to 5 and currentColumn to 10. I already have a subroutine,
Mosaic.open(), to open the window, and I have a function, Mosaic.isOpen(), to
test whether the window is open. To keep the main routine simple, I decide that I will
write two more subroutines of my own to carry out the two tasks in the while loop.
The algorithm can then be written in Java as:
Mosaic.open(10,20,10,10)
fillWithRandomColors();
currentRow = 5; // Middle row, halfway down the window.
currentColumn = 10; // Middle column.
while ( Mosaic.isOpen() ) {
changeToRandomColor(currentRow, currentColumn);
randomMove();
}
With the proper wrapper, this is essentially the main() routine of my program. It turns
out I have to make one small modification: To prevent the animation from running too
fast, the line "Mosaic.delay(20);" is added to the while loop.
The main() routine is taken care of, but to complete the program, I still have to write
the subroutines fillWithRandomColors(), changeToRandomColor(int,int), and
randomMove(). Writing each of these subroutines is a separate, small task. The
fillWithRandomColors() routine is defined by the postcondition that "each of the
rectangles in the mosaic has been changed to a random color." Pseudocode for an
algorithm to accomplish this task can be given as:
"For each row" and "for each column" can be implemented as for loops. We've
already planned to write a subroutine changeToRandomColor that can be used to set
the color. (The possibility of reusing subroutines in several places is one of the big
payoffs of using them!) So, fillWithRandomColors() can be written in proper Java
as:
int directionNum;
directoinNum = (int)(4*Math.random());
switch (directionNum) {
case 0: // move up
currentRow--;
if (currentRow < 0) // CurrentRow is outside the
mosaic;
currentRow = 9; // move it to the opposite
edge.
break;
case 1: // move right
currentColumn++;
if (currentColumn >= 20)
currentColumn = 0;
break;
case 2: // move down
currentRow++;
if (currentRow >= 10)
currentRow = 0;
break;
case 3: // move left
currentColumn--;
if (currentColumn < 0)
currentColumn = 19;
break;
}
Putting this all together, we get the following complete program. The variables
currentRow and currentColumn are defined as static members of the class, rather
than local variables, because each of them is used in several different subroutines.
This program actually depends on two other classes, Mosaic and another class called
MosaicCanvas that is used by Mosaic. If you want to compile and run this program,
both of these classes must be available to the program.
/*
This program shows a window full of randomly colored
squares. A "disturbance" moves randomly around
in the window, randomly changing the color of
each square that it visits. The program runs
until the user closes the window.
*/
When a variable declaration is executed, memory is allocated for the variable. This
memory must be initialized to contain some definite value before the variable can be
used in an expression. In the case of a local variable, the declaration is often followed
closely by an assignment statement that does the initialization. For example,
However, the truth about declaration statements is that it is legal to include the
initialization of the variable in the declaration statement. The two statements above
can therefore be abbreviated as
The computer still executes this statement in two steps: Declare the variable count,
then assign the value 0 to the newly created variable. The initial value does not have
to be a constant. It can be any expression. It is legal to initialize several variables in
one declaration statement. For example,
This feature is especially common in for loops, since it makes it possible to declare a
loop control variable at the same point in the loop where it is initialized. Since the
loop control variable generally has nothing to do with the rest of the program outside
the loop, it's reasonable to have its declaration in the part of the program where it's
actually used. For example:
{
int i;
for ( i = 0; i < 10; i++ ) {
System.out.println(i);
}
}
A member variable can also be initialized at the point where it is declared. For
example:
A static member variable is created as soon as the class is loaded by the Java
interpreter, and the initialization is also done at that time. In the case of member
variables, this is not simply an abbreviation for a declaration followed by an
assignment statement. Declaration statements are the only type of statement that can
occur outside of a subroutine. Assignment statements cannot, so the following is
illegal:
Sometimes, the value of a variable is not supposed to change after it is initialized. For
example, in the above example where interestRate is initialized to the value 0.05,
it's quite possible that that is meant to be the value throughout the entire program. In
this case, the programmer is probably defining the variable, interestRate, to give a
meaningful name to the otherwise meaningless number, 0.05. It's easier to understand
what's going on when a program says "principal += principal*interestRate;"
rather than "principal += principal*0.05;".
In Java, the modifier "final" can be applied to a variable declaration to ensure that
the value of the variable cannot be changed after the variable has been initialized. For
example, if the member variable interestRate is declared with
then it would be impossible for the value of interestRate to change anywhere else in
the program. Any assignment statement that tries to assign a value to interestRate
will be rejected by the computer as a syntax error when the program is compiled.
It is legal to apply the final modifier to local variables and even to formal
parameters, but it is most useful for member variables. I will often refer to a static
member variable that is declared to be final as a named constant, since its value
remains constant for the whole time that the program is running. The readability of a
program can be greatly enhanced by using named constants to give meaningful names
to important quantities in the program. A recommended style rule for named constants
is to give them names that consist entirely of upper case letters, with underscore
characters to separate words if necessary. For example, the preferred style for the
interest rate constant would be
This is the style that is generally used in Java's standard classes, which define many
named constants. For example, the Math class defines a named constant PI to
represent the mathematical constant of that name. Since it is a member of the Math
class, you would have to refer to it as Math.PI in your own programs. Many constants
are provided to give meaningful names to be used as parameters in subroutine calls.
For example, a standard class named Font contains named constants Font.PLAIN,
Font.BOLD, and Font.ITALIC. These constants are used for specifying different
styles of text when calling various subroutines in the Font class.
Curiously enough, one of the major reasons to use named constants is that it's easy to
change the value of a named constant. Of course, the value can't change while the
program is running. But between runs of the program, it's easy to change the value in
the source code and recompile the program. Consider the interest rate example. It's
quite possible that the value of the interest rate is used many times throughout the
program. Suppose that the bank changes the interest rate and the program has to be
modified. If the literal number 0.05 were used throughout the program, the
programmer would have to track down each place where the interest rate is used in
the program and change the rate to the new value. (This is made even harder by the
fact that the number 0.05 might occur in the program with other meanings besides the
interest rate, as well as by the fact that someone might have used 0.025 to represent
half the interest rate.) On the other hand, if the named constant INTEREST_RATE is
declared and used consistently throughout the program, then only the single line
where the constant is initialized needs to be changed.
The rest of the program is carefully modified to use the named constants. For
example, in the new version of the program, the Mosaic window is opened with the
statement
Sometimes, it's not easy to find all the places where a named constants needs to be
used. It's always a good idea to run a program using several different values for any
named constants, to test that it works properly in all cases.
Here is the complete new program, RandomMosaicWalk2, with all modifications from
the previous version shown in red.
/*
This program shows a window full of randomly colored
squares. A "disturbance" moves randomly around
in the window, randomly changing the color of
each square that it visits. The program runs
until the user closes the window.
*/
Java 1.5 Note: Constants are often used to represent a small set of related
values. For example, you might declare int constants named RECT, OVAL, and
ROUNDRECT to represent shapes. Note that the values of these constants are not
really important; they exist only to name the different types of shapes. Java
1.5 introduces enumerated types to represent such sets of constants.
Enumerated types have long been available in other programming languages.
In Java 1.5, an enumerated type for representing shapes could be defined as
"enum ShapeName { RECT, OVAL, ROUNDRECT }" (or more likely "public
static enum ShapeName { RECT, OVAL, ROUNDRECT }"). This defines a
type named ShapeName that can be used to define variables and parameters in
that same way as any other type. The values of this type are denoted
ShapeName.RECT, ShapeName.OVAL, and ShapeName.ROUNDRECT. In
fact, ShapeName is really a class (except that it must be defined inside another
class). An enum is preferable to a bunch of int-valued constants because the
enum is "type-safe": A variable of type ShapeName can only have one of the
three specified values of type ShapeName. There is no way to guarantee that a
variable of type int has one of the three values that represent shapes.
When a variable declaration is executed, memory is allocated for that variable. The
variable name can be used in at least some part of the program source code to refer to
that memory or to the data that is stored in the memory. The portion of the program
source code where the variable name is valid is called the scope of the variable.
Similarly, we can refer to the scope of subroutine names and formal parameter names.
For a variable that is declared as a static member variable in a class, the situation is
similar, but with one complication. It is legal to have a local variable or a formal
parameter that has the same name as a member variable. In that case, within the scope
of the local variable or parameter, the member variable is hidden. Consider, for
example, a class named Game that has the form:
.
. // More variables and subroutines.
.
} // end Game
In the statements that make up the body of the playGame() subroutine, the name
"count" refers to the local variable. In the rest of the Game class, "count" refers to the
member variable, unless hidden by other local variables or parameters named count.
However, there is one further complication. The member variable named count can
also be referred to by the full name Game.count. Usually, the full name is only used
outside the class where count is defined. However, there is no rule against using it
inside the class. The full name, Game.count, can be used inside the playGame()
subroutine to refer to the member variable. So, the full scope rule for static member
variables is that the scope of a member variable includes the entire class in which it is
defined, but where the simple name of the member variable is hidden by a local
variable or formal parameter name, the member variable must be referred to by its full
name of the form className.variableName. (Scope rules for non-static members are
similar to those for static members, except that, as we shall see, non-static members
cannot be used in static subroutines.)
The scope of a formal parameter of a subroutine is the block that makes up the body
of the subroutine. The scope of a local variable extends from the declaration statement
that defines the variable to the end of the block in which the declaration occurs. As
noted above, it is possible to declare a loop control variable of a for loop in the for
statement, as in "for (int i=0; i < 10; i++)". The scope of such a declaration is
considered as a special case: It is valid only within the for statement and does not
extend to the remainder of the block that contains the for statement.
It is not legal to redefine the name of a formal parameter or local variable within its
scope, even in a nested block. For example, this is not allowed:
void badSub(int y) {
int x;
while (y > 0) {
int x; // ERROR: x is already defined.
.
.
.
}
}
In many languages, this would be legal. The declaration of x in the while loop would
hide the original declaration. It is not legal in Java. However, once the block in which
a variable is declared ends, its name does become available for reuse in Java. For
example:
void goodSub(int y) {
while (y > 10) {
int x;
.
.
.
// The scope of x ends here.
}
while (y > 0) {
int x; // OK: Previous declaration of x has
expired.
.
.
.
}
}
You might wonder whether local variable names can hide subroutine names. This
can't happen, for a reason that might be surprising. There is no rule that variables and
subroutines have to have different names. The computer can always tell whether a
name refers to a variable or to a subroutine, because a subroutine name is always
followed by a left parenthesis. It's perfectly legal to have a variable called count and a
subroutine called count in the same class. (This is one reason why I often write
subroutine names with parentheses, as when I talk about the main() routine. It's a
good idea to think of the parentheses as part of the name.) Even more is true: It's legal
to reuse class names to name variables and subroutines. The syntax rules of Java
guarantee that the computer can always tell when a name is being used as a class
name. A class name is a type, and so it can be used to declare variables and to specify
the return type of a function. This means that you could legally have a class called
Insanity in which you declare a function
The first Insanity is the return type of the function. The second is the function name,
the third is the type of the formal parameter, and the fourth is a formal parameter
name. However, please remember that not everything that is possible is a good idea!
CHAPTER FIVE
CONTROLS
The block is the simplest type of structured statement. Its purpose is simply to group a
sequence of statements into a single statement. The format of a block is:
{
statements
}
That is, it consists of a sequence of statements enclosed between a pair of braces, "{"
and "}". (In fact, it is possible for a block to contain no statements at all; such a block
is called an empty block, and can actually be useful at times. An empty block consists
of nothing but an empty pair of braces.) Block statements usually occur inside other
statements, where their purpose is to group together several statements into a unit.
However, a block can be legally used wherever a statement can occur. There is one
place where a block is required: As you might have already noticed in the case of the
main subroutine of a program, the definition of a subroutine is a block, since it is a
sequence of statements enclosed inside a pair of braces.
I should probably note at this point that Java is what is called a free-format language.
There are no syntax rules about how the language has to be arranged on a page. So,
for example, you could write an entire block on one line if you want. But as a matter
of good programming style, you should lay out your program on the page in a way
that will make its structure as clear as possible. In general, this means putting one
statement per line and using indentation to indicate statements that are contained
inside control structures. This is the format that I will generally use in my examples.
{
System.out.print("The answer is ");
System.out.println(ans);
}
In the second example, a variable, temp, is declared inside the block. This is perfectly
legal, and it is good style to declare a variable inside a block if that variable is used
nowhere else but inside the block. A variable declared inside a block is completely
inaccessible and invisible from outside that block. When the computer executes the
variable declaration statement, it allocates memory to hold the value of the variable.
When the block ends, that memory is discarded (that is, made available for reuse).
The variable is said to be local to the block. There is a general concept called the
"scope" of an identifier. The scope of an identifier is the part of the program in which
that identifier is valid. The scope of a variable defined inside a block is limited to that
block, and more specifically to the part of the block that comes after the declaration of
the variable.
The block statement by itself really doesn't affect the flow of control in a program.
The five remaining control structures do. They can be divided into two classes: loop
statements and branching statements. You really just need one control structure from
each category in order to have a completely general-purpose programming language.
More than that is just convenience. In this section, I'll introduce the while loop and
the if statement. I'll give the full details of these statements and of the other three
control structures in later sections.
A while loop is used to repeat a given statement over and over. Of course, its not
likely that you would want to keep repeating it forever. That would be an infinite
loop, which is generally a bad thing. (There is an old story about computer pioneer
Grace Murray Hopper, who read instructions on a bottle of shampoo telling her to
"lather, rinse, repeat." As the story goes, she claims that she tried to follow the
directions, but she ran out of shampoo. (In case you don't get it, this is a joke about
the way that computers mindlessly follow instructions.))
To be more specific, a while loop will repeat a statement over and over, but only so
long as a specified condition remains true. A while loop has the form:
while (boolean-expression)
statement
Since the statement can be, and usually is, a block, many while loops have the form:
while (boolean-expression) {
statements
}
The semantics of this statement go like this: When the computer comes to a while
statement, it evaluates the boolean-expression, which yields either true or false as
the value. If the value is false, the computer skips over the rest of the while loop
and proceeds to the next command in the program. If the value of the expression is
true, the computer executes the statement or block of statements inside the loop.
Then it returns to the beginning of the while loop and repeats the process. That is, it
re-evaluates the boolean-expression, ends the loop if the value is false, and
continues it if the value is true. This will continue over and over until the value of the
expression is false; if that never happens, then there will be an infinite loop.
Here is an example of a while loop that simply prints out the numbers 1, 2, 3, 4, 5:
The variable number is initialized with the value 1. So the first time through the while
loop, when the computer evaluates the expression "number < 6", it is asking whether
1 is less than 6, which is true. The computer therefor proceeds to execute the two
statements inside the loop. The first statement prints out "1". The second statement
adds 1 to number and stores the result back into the variable number; the value of
number has been changed to 2. The computer has reached the end of the loop, so it
returns to the beginning and asks again whether number is less than 6. Once again this
is true, so the computer executes the loop again, this time printing out 2 as the value
of number and then changing the value of number to 3. It continues in this way until
eventually number becomes equal to 6. At that point, the expression "number < 6"
evaluates to false. So, the computer jumps past the end of the loop to the next
statement and prints out the message "Done!". Note that when the loop ends, the value
of number is 6, but the last value that was printed was 5.
By the way, you should remember that you'll never see a while loop standing by itself
in a real program. It will always be inside a subroutine which is itself defined inside
some class. As an example of a while loop used inside a complete program, here is a
little program that computes the interest on an investment over several years. This is
an improvement over examples from the previous chapter that just reported the results
for one year:
/*
This class implements a simple program that
will compute the amount of interest that is
earned on an investment over a period of
5 years. The initial amount of the investment
and the interest rate are input by the user.
The value of the investment at the end of each
year is output.
*/
} // end of main()
You should study this program, and make sure that you understand what the computer
does step-by-step as it executes the while loop.
An if statement tells the computer to take one of two alternative courses of action,
depending on whether the value of a given boolean-valued expression is true or false.
It is an example of a "branching" or "decision" statement. An if statement has the
form:
if ( boolean-expression )
statement
else
statement
In many cases, you want the computer to choose between doing something and not
doing it. You can do this with an if statement that omits the else part:
if ( boolean-expression )
statement
To execute this statement, the computer evaluates the expression. If the value is true,
the computer executes the statement that is contained inside the if statement; if the
value is false, the computer skips that statement.
Of course, either or both of the statement's in an if statement can be a block, so that
an if statement often looks like:
if ( boolean-expression ) {
statements
}
else {
statements
}
or:
if ( boolean-expression ) {
statements
}
if ( x > y ) {
int temp; // A temporary variable for use in this
block.
temp = x; // Save a copy of the value of x in temp.
x = y; // Copy the value of y into x.
y = temp; // Copy the value of temp into y.
}
Finally, here is an example of an if statement that includes an else part. See if you
can figure out what it does, and why it would be used:
I'll have more to say about control structures later in this chapter. But you already
know the essentials. If you never learned anything more about control structures, you
would already know enough to perform any possible computing task. Simple looping
and branching are all you really need!
Algorithm Development
When programming in the small, you have a few basics to work with: variables,
assignment statements, and input-output routines. You might also have some
subroutines, objects, or other building blocks that have already been written by you or
someone else. (Input/output routines fall into this class.) You can build sequences of
these basic instructions, and you can also combine them into more complex control
structures such as while loops and if statements.
Suppose you have a task in mind that you want the computer to perform. One way to
proceed is to write a description of the task, and take that description as an outline of
the algorithm you want to develop. Then you can refine and elaborate that description,
gradually adding steps and detail, until you have a complete algorithm that can be
translated directly into programming language. This method is called stepwise
refinement, and it is a type of top-down design. As you proceed through the stages of
stepwise refinement, you can write out descriptions of your algorithm in pseudocode
-- informal instructions that imitate the structure of programming languages without
the complete detail and perfect syntax of actual program code.
As an example, let's see how one might develop the program from the previous
section, which computes the value of an investment over five years. The task that you
want the program to perform is: "Compute and display the value of an investment for
each of the next five years, where the initial investment and interest rate are to be
specified by the user." You might then write -- or at least think -- that this can be
expanded as:
This is correct, but rather repetitive. And seeing that repetition, you might notice an
opportunity to use a loop. A loop would take less typing. More important, it would be
more general: Essentially the same loop will work no matter how many years you
want to process. So, you might rewrite the above sequence of steps as:
Now, for a computer, we'll have to be more explicit about how to "Get the user's
input," how to "Compute the value after the next year," and what it means to say
"there are more years to process." We can expand the step, "Get the user's input" into
As for testing whether there are more years to process, the only way that we can do
that is by counting the years ourselves. This displays a very common pattern, and you
should expect to use something similar in a lot of programs: We have to start with
zero years, add one each time we process a year, and stop when we reach the desired
number of years. So the while loop becomes:
years = 0
while years < 5:
years = years + 1
Compute the interest
Add the interest to the value
Display the value
We still have to know how to compute the interest. Let's say that the interest is to be
computed by multiplying the interest rate by the current value of the investment.
Putting this together with the part of the algorithm that gets the user's inputs, we have
the complete algorithm:
Finally, we are at the point where we can translate pretty directly into proper
programming-language syntax. We still have to choose names for the variables,
decide exactly what we want to say to the user, and so forth. Having done this, we
could express our algorithm in Java as:
One thing you should have noticed here is that my original specification of the
problem -- "Compute and display the value of an investment for each of the next five
years" -- was far from being complete. Before you start writing a program, you should
make sure you have a complete specification of exactly what the program is supposed
to do. In particular, you need to know what information the program is going to input
and output and what computation it is going to perform. Here is what a reasonably
complete specification of the problem might look like in this example:
"Write a program that will compute and display the value of an investment for each of
the next five years. Each year, interest is added to the value. The interest is computed
by multiplying the current value by a fixed interest rate. Assume that the initial value
and the rate of interest are to be input by the user when the program is run."
Let's do another example, working this time with a program that you haven't already
seen. The assignment here is an abstract mathematical problem that is one of my
favorite programming exercises. This time, we'll start with a more complete
specification of the task to be performed:
"Given a positive integer, N, define the '3N+1' sequence starting from N as follows: If
N is an even number, then divide N by two; but if N is odd, then multiply N by 3 and
add 1. Continue to generate numbers in this way until N becomes equal to 1. For
example, starting from N = 3, which is odd, we multiply by 3 and add 1, giving N =
3*3+1 = 10. Then, since N is even, we divide by 2, giving N = 10/2 = 5. We continue
in this way, stopping when we reach 1, giving the complete sequence: 3, 10, 5, 16, 8,
4, 2, 1.
"Write a program that will read a positive integer from the user and will print out the
3N+1 sequence starting from that integer. The program should also count and print
out the number of terms in the sequence."
The bulk of the program is in the second step. We'll need a loop, since we want to
keep computing numbers until we get 1. To put this in terms appropriate for a while
loop, we want to continue as long as the number is not 1. So, we can expand our
pseudocode algorithm to:
In order to compute the next term, the computer must take different actions depending
on whether N is even or odd. We need an if statement to decide between the two
cases:
We are almost there. The one problem that remains is counting. Counting means that
you start with zero, and every time you have something to count, you add one. We
need a variable to do the counting. (Again, this is a common pattern that you should
expect to see over and over.) With the counter added, we get:
We still have to worry about the very first step. How can we get a positive integer
from the user? If we just read in a number, it's possible that the user might type in a
negative number or zero. If you follow what happens when the value of N is negative
or zero, you'll see that the program will go on forever, since the value of N will never
become equal to 1. This is bad. In this case, the problem is probably no big deal, but
in general you should try to write programs that are foolproof. One way to fix this is
to keep reading in numbers until the user types in a positive number:
Ask user to input a positive number;
Let N be the user's response;
while N is not positive:
Print an error message;
Read another value for N;
Let counter = 0;
while N is not 1:
if N is even:
Compute N = N/2;
else
Compute N = 3 * N + 1;
Output N;
Add 1 to counter;
Output the counter;
The first while loop will end only when N is a positive number, as required. (A
common beginning programmer's error is to use an if statement instead of a while
statement here: "If N is not positive, ask the user to input another value." The problem
arises if the second number input by the user is also non-positive. The if statement is
only executed once, so the second input number is never tested. With the while loop,
after the second number is input, the computer jumps back to the beginning of the
loop and tests whether the second number is positive. If not, it asks the user for a third
number, and it will continue asking for numbers until the user enters an acceptable
input.)
Here is a Java program implementing this algorithm. It uses the operators <= to mean
"is less than or equal to" and != to mean "is not equal to." To test whether N is even, it
uses "N % 2 == 0". All the operators used here were discussed in Section 2.5.
counter = 0;
while (N != 1) {
if (N % 2 == 0)
N = N / 2;
else
N = 3 * N + 1;
TextIO.putln(N);
counter = counter + 1;
}
TextIO.putln();
TextIO.put("There were ");
TextIO.put(counter);
TextIO.putln(" terms in the sequence.");
} // end of main()
As usual, you can try this out in an applet that simulates the program. Try different
starting values for N, including some negative values:
Two final notes on this program: First, you might have noticed that the first term of
the sequence -- the value of N input by the user -- is not printed or counted by this
program. Is this an error? It's hard to say. Was the specification of the program careful
enough to decide? This is the type of thing that might send you back to the
boss/professor for clarification. The problem (if it is one!) can be fixed easily enough.
Just replace the line "counter = 0" before the while loop with the two lines:
Second, there is the question of why this problem is at all interesting. Well, it's
interesting to mathematicians and computer scientists because of a simple question
about the problem that they haven't been able to answer: Will the process of
computing the 3N+1 sequence finish after a finite number of steps for all possible
starting values of N? Although individual sequences are easy to compute, no one has
been able to answer the general question. (To put this another way, no one knows
whether the process of computing 3N+1 sequences can properly be called an
algorithm, since an algorithm is required to terminate after a finite number of steps!)
It would be nice if, having developed an algorithm for your program, you could relax,
press a button, and get a perfectly working program. Unfortunately, the process of
turning an algorithm into Java source code doesn't always go smoothly. And when you
do get to the stage of a working program, it's often only working in the sense that it
does something. Unfortunately not what you want it to do.
After program design comes coding: translating the design into a program written in
Java or some other language. Usually, no matter how careful you are, a few syntax
errors will creep in from somewhere, and the Java compiler will reject your program
with some kind of error message. Unfortunately, while a compiler will always detect
syntax errors, it's not very good about telling you exactly what's wrong. Sometimes,
it's not even good about telling you where the real error is. A spelling error or missing
"{" on line 45 might cause the compiler to choke on line 105. You can avoid lots of
errors by making sure that you really understand the syntax rules of the language and
by following some basic programming guidelines. For example, I never type a "{"
without typing the matching "}". Then I go back and fill in the statements between the
braces. A missing or extra brace can be one of the hardest errors to find in a large
program. Always, always indent your program nicely. If you change the program,
change the indentation to match. It's worth the trouble. Use a consistent naming
scheme, so you don't have to struggle to remember whether you called that variable
interestrate or interestRate. In general, when the compiler gives multiple error
messages, don't try to fix the second error message from the compiler until you've
fixed the first one. Once the compiler hits an error in your program, it can get
confused, and the rest of the error messages might just be guesses. Maybe the best
advice is: Take the time to understand the error before you try to fix it. Programming
is not an experimental science.
When your program compiles without error, you are still not done. You have to test
the program to make sure it works correctly. Remember that the goal is not to get the
right output for the two sample inputs that the professor gave in class. The goal is a
program that will work correctly for all reasonable inputs. Ideally, when faced with an
unreasonable input, it will respond by gently chiding the user rather than by crashing.
Test your program on a wide variety of inputs. Try to find a set of inputs that will test
the full range of functionality that you've coded into your program. As you begin
writing larger programs, write them in stages and test each stage along the way. You
might even have to write some extra code to do the testing -- for example to call a
subroutine that you've just written. You don't want to be faced, if you can avoid it,
with 500 newly written lines of code that have an error in there somewhere.
The point of testing is to find bugs -- semantic errors that show up as incorrect
behavior rather than as compilation errors. And the sad fact is that you will probably
find them. Again, you can minimize bugs by careful design and careful coding, but no
one has found a way to avoid them altogether. Once you've detected a bug, it's time
for debugging. You have to track down the cause of the bug in the program's source
code and eliminate it. Debugging is a skill that, like other aspects of programming,
requires practice to master. So don't be afraid of bugs. Learn from them. One essential
debugging skill is the ability to read source code -- the ability to put aside
preconceptions about what you think it does and to follow it the way the computer
does -- mechanically, step-by-step -- to see what it really does. This is hard. I can still
remember the time I spent hours looking for a bug only to find that a line of code that
I had looked at ten times had a "1" where it should have had an "i", or the time when I
wrote a subroutine named WindowClosing which would have done exactly what I
wanted except that the computer was looking for windowClosing (with a lower case
"w"). Sometimes it can help to have someone who doesn't share your preconceptions
look at your code.
Often, it's a problem just to find the part of the program that contains the error. Most
programming environments come with a debugger, which is a program that can help
you find bugs. Typically, your program can be run under the control of the debugger.
The debugger allows you to set "breakpoints" in your program. A breakpoint is a point
in the program where the debugger will pause the program so you can look at the
values of the program's variables. The idea is to track down exactly when things start
to go wrong during the program's execution. The debugger will also let you execute
your program one line at a time, so that you can watch what happens in detail once
you know the general area in the program where the bug is lurking.
I will confess that I only rarely use debuggers myself. A more traditional approach to
debugging is to insert debugging statements into your program. These are output
statements that print out information about the state of the program. Typically, a
debugging statement would say something like System.out.println("At start of
while loop, N = " + N). You need to be able to tell where in your program the
output is coming from, and you want to know the value of important variables.
Sometimes, you will find that the computer isn't even getting to a part of the program
that you think it should be executing. Remember that the goal is to find the first point
in the program where the state is not what you expect it to be. That's where the bug is.
The while statement was already introduced in Section 1. A while loop has the form
while ( boolean-expression )
statement
Let's look at a typical problem that can be solved using a while loop: finding the
average of a set of positive integers entered by the user. The average is the sum of the
integers, divided by the number of integers. The program will ask the user to enter
one integer at a time. It will keep count of the number of integers entered, and it will
keep a running total of all the numbers it has read so far. Here is a pseudocode
algorithm for the program:
Let sum = 0
Let count = 0
while there are more integers to process:
Read an integer
Add it to the sum
Count it
Divide sum by count to get the average
Print out the average
But how can we test whether there are more integers to process? A typical solution is
to tell the user to type in zero after all the data have been entered. This will work
because we are assuming that all the data are positive numbers, so zero is not a legal
data value. The zero is not itself part of the data to be averaged. It's just there to mark
the end of the real data. A data value used in this way is sometimes called a sentinel
value. So now the test in the while loop becomes "while the input integer is not zero".
But there is another problem! The first time the test is evaluated, before the body of
the loop has ever been executed, no integer has yet been read. There is no "input
integer" yet, so testing whether the input integer is zero doesn't make sense. So, we
have to do something before the while loop to make sure that the test makes sense.
Setting things up so that the test in a while loop makes sense the first time it is
executed is called priming the loop. In this case, we can simply read the first integer
before the beginning of the loop. Here is a revised algorithm:
Let sum = 0
Let count = 0
Read an integer
while the integer is not zero:
Add the integer to the sum
Count it
Read an integer
Divide sum by count to get the average
Print out the average
Notice that I've rearranged the body of the loop. Since an integer is read before the
loop, the loop has to begin by processing that integer. At the end of the loop, the
computer reads a new integer. The computer then jumps back to the beginning of the
loop and tests the integer that it has just read. Note that when the computer finally
reads the sentinel value, the loop ends before the sentinel value is processed. It is not
added to the sum, and it is not counted. This is the way it's supposed to work. The
sentinel is not part of the data. The original algorithm, even if it could have been made
to work without priming, was incorrect since it would have summed and counted all
the integers, including the sentinel. (Since the sentinel is zero, the sum would still be
correct, but the count would be off by one. Such so-called off-by-one errors are very
common. Counting turns out to be harder than it looks!)
We can easily turn the algorithm into a complete program. Note that the program
cannot use the statement "average = sum/count;" to compute the average. Since
sum and count are both variables of type int, the value of sum/count is an integer.
The average should be a real number. We've seen this problem before: we have to
convert one of the int values to a double to force the computer to compute the
quotient as a real number. This can be done by type-casting one of the variables to
type double. The type cast "(double)sum" converts the value of sum to a real number,
so in the program the average is computed as "average = ((double)sum) /
count;". Another solution in this case would have been to declare sum to be a variable
of type double in the first place.
One other issue is addressed by the program: If the user enters zero as the first input
value, there are no data to process. We can test for this case by checking whether
count is still equal to zero after the while loop. This might seem like a minor point,
but a careful programmer should cover all the bases.
sum = 0;
count = 0;
while (inputNumber != 0) {
sum += inputNumber; // Add inputNumber to running
sum.
count++; // Count the input by adding 1 to
count.
TextIO.put("Enter your next positive integer, or 0 to
end: ");
inputNumber = TextIO.getlnInt();
}
if (count == 0) {
TextIO.putln("You didn't enter any data!");
}
else {
average = ((double)sum) / count;
TextIO.putln();
TextIO.putln("You entered " + count + " positive
integers.");
TextIO.putln("Their average is " + average + ".");
}
} // end main()
do
statement
while ( boolean-expression );
do {
statements
} while ( boolean-expression );
Note the semicolon, ';', at the end. This semicolon is part of the statement, just as the
semicolon at the end of an assignment statement or declaration is part of the
statement. Omitting it is a syntax error. (More generally, every statement in Java ends
either with a semicolon or a right brace, '}'.)
To execute a do loop, the computer first executes the body of the loop -- that is, the
statement or statements inside the loop -- and then it evaluates the boolean expression.
If the value of the expression is true, the computer returns to the beginning of the do
loop and repeats the process; if the value is false, it ends the loop and continues with
the next part of the program. Since the condition is not tested until the end of the loop,
the body of a do loop is executed at least once.
For example, consider the following pseudocode for a game-playing program. The do
loop makes sense here instead of a while loop because with the do loop, you know
there will be at least one game. Also, the test that is used at the end of the loop
wouldn't even make sense at the beginning:
do {
Play a Game
Ask user if he wants to play another game
Read the user's response
} while ( the user's response is yes );
Let's convert this into proper Java code. Since I don't want to talk about game playing
at the moment, let's say that we have a class named Checkers, and that the Checkers
class contains a static member subroutine named playGame() that plays one game of
checkers against the user. Then, the pseudocode "Play a game" can be expressed as
the subroutine call statement "Checkers.playGame();". We need a variable to store
the user's response. The TextIO class makes it convenient to use a boolean variable
to store the answer to a yes/no question. The input function TextIO.getlnBoolean()
allows the user to enter the value as "yes" or "no". "Yes" is considered to be true, and
"no" is considered to be false. So, the algorithm can be coded as
When the value of the boolean variable is set to false, it is a signal that the loop
should end. When a boolean variable is used in this way -- as a signal that is set in
one part of the program and tested in another part -- it is sometimes called a flag or
flag variable (in the sense of a signal flag).
do {
doSomething
} while ( boolean-expression );
doSomething
while ( boolean-expression ) {
doSomething
}
Similarly,
while ( boolean-expression ) {
doSomething
}
can be replaced by
if ( boolean-expression ) {
do {
doSomething
} while ( boolean-expression );
}
The syntax of the while and do..while loops allows you to test the continuation
condition at either the beginning of a loop or at the end. Sometimes, it is more natural
to have the test in the middle of the loop, or to have several tests at different places in
the same loop. Java provides a general method for breaking out of the middle of any
loop. It's called the break statement, which takes the form
break;
When the computer executes a break statement in a loop, it will immediately jump
out of the loop. It then continues on to whatever follows the loop in the program.
Consider for example:
If the number entered by the user is greater than zero, the break statement will be
executed and the computer will jump out of the loop. Otherwise, the computer will
print out "Your answer must be > 0." and will jump back to the start of the loop to
read another input value.
(The first line of the loop, "while (true)" might look a bit strange, but it's perfectly
legitimate. The condition in a while loop can be any boolean-valued expression. The
computer evaluates this expression and checks whether the value is true or false.
The boolean literal "true" is just a boolean expression that always evaluates to true.
So "while (true)" can be used to write an infinite loop, or one that can be
terminated only by a break statement.)
A break statement terminates the loop that immediately encloses the break statement.
It is possible to have nested loops, where one loop statement is contained inside
another. If you use a break statement inside a nested loop, it will only break out of
that loop, not out of the loop that contains the nested loop. There is something called a
"labeled break" statement that allows you to specify which loop you want to break. I
won't give the details here; you can look them up if you ever need them.
The continue statement is related to break, but less commonly used. A continue
statement tells the computer to skip the rest of the current iteration of the loop.
However, instead of jumping out of the loop altogether, it jumps back to the beginning
of the loop and continues with the next iteration (after evaluating the loop's
continuation condition to see whether any further iterations are required).
WE TURN IN THIS SECTION to another type of loop, the for statement. Any for
loop is equivalent to some while loop, so the language doesn't get any additional
power by having for statements. But for a certain type of problem, a for loop can be
easier to construct and easier to read than the corresponding while loop. It's quite
possible that in real programs, for loops actually outnumber while loops.
The for statement makes a common type of while loop easier to write. Many while
loops have the general form:
initialization
while ( continuation-condition ) {
statements
update
}
The initialization, continuation condition, and updating have all been combined in the
first line of the for loop. This keeps everything involved in the "control" of the loop
in one place, which helps makes the loop easier to read and understand. The for loop
is executed in exactly the same way as the original code: The initialization part is
executed once, before the loop begins. The continuation condition is executed before
each execution of the loop, and the loop ends when this condition is false. The
update part is executed at the end of each execution of the loop, just before jumping
back to check the condition.
Usually, the initialization part of a for statement assigns a value to some variable, and
the update changes the value of that variable with an assignment statement or with an
increment or decrement operation. The value of the variable is tested in the
continuation condition, and the loop ends when this condition evaluates to false. A
variable used in this way is called a loop control variable. In the for statement given
above, the loop control variable is years.
Certainly, the most common type of for loop is the counting loop, where a loop
control variable takes on all integer values between some minimum and some
maximum value. A counting loop has the form
where min and max are integer-valued expressions (usually constants). The variable
takes on the values min, min+1, min+2, ...,max. The value of the loop control
variable is often used in the body of the loop. The for loop at the beginning of this
section is a counting loop in which the loop control variable, years, takes on the
values 1, 2, 3, 4, 5. Here is an even simpler example, in which the numbers 1, 2, ..., 10
are displayed on standard output:
Using < instead of <= in the test, or vice versa, is a common source of off-by-one
errors in programs. You should always stop and think, do I want the final value to be
processed or not?
It's easy to count down from 10 to 1 instead of counting up. Just start with 10,
decrement the loop control variable instead of incrementing it, and continue as long as
the variable is greater than or equal to one.
Now, in fact, the official syntax of a for statemenent actually allows both the
initialization part and the update part to consist of several expressions, separated by
commas. So we can even count up from 1 to 10 and count down from 10 to 1 at the
same time!
As a final example, let's say that we want to use a for loop that prints out just the
even numbers between 2 and 20, that is: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20. There are
several ways to do this. Just to show how even a very simple problem can be solved in
many ways, here are four different solutions (three of which would get full credit):
Perhaps it is worth stressing one more time that a for statement, like any statement,
never occurs on its own in a real program. A statement must be inside the main
routine of a program or inside some other subroutine. And that subroutine must be
defined inside a class. I should also remind you that every variable must be declared
before it can be used, and that includes the loop control variable in a for statement. In
all the examples that you have seen so far in this section, the loop control variables
should be declared to be of type int. It is not required that a loop control variable be
an integer. Here, for example, is a for loop in which the variable, ch, is of type char:
Let's look at a less trivial problem that can be solved with a for loop. If N and D are
positive integers, we say that D is a divisor of N if the remainder when D is divided into
N is zero. (Equivalently, we could say that N is an even multiple of D.) In terms of Java
programming, D is a divisor of N if N % D is zero.
Let's write a program that inputs a positive integer, N, from the user and computes
how many different divisors N has. The numbers that could possibly be divisors of N
are 1, 2, ...,N. To compute the number of divisors of N, we can just test each possible
divisor of N and count the ones that actually do divide N evenly. In pseudocode, the
algorithm takes the form
This algorithm displays a common programming pattern that is used when some, but
not all, of a sequence of items are to be processed. The general pattern is
The for loop in our divisor-counting algorithm can be translated into Java code as
On a modern computer, this loop can be executed very quickly. It is not impossible to
run it even for the largest legal int value, 2147483647. (If you wanted to run it for
even larger values, you could use variables of type long rather than int.) However, it
does take a noticeable amount of time for very large numbers. So when I implemented
this algorithm, I decided to output a period every time the computer has tested one
million possible divisors. In the improved version of the program, there are two types
of counting going on. We have to count the number of divisors and we also have to
count the number of possible divisors that have been tested. So the program needs two
counters. When the second counter reaches 1000000, we output a '.' and reset the
counter to zero so that we can start counting the next group of one million. Reverting
to pseudocode, the algorithm now looks like
Finally, we can translate the algorithm into a complete Java program. Here it is,
followed by an applet that simulates it:
while (true) {
TextIO.put("Enter a positive integer: ");
N = TextIO.getlnInt();
if (N > 0)
break;
TextIO.putln("That number is not positive. Please try
again.");
}
divisorCount = 0;
numberTested = 0;
TextIO.putln();
TextIO.putln("The number of divisors of " + N
+ " is " + divisorCount);
} // end main()
Control structures in Java are statements that contain statements. In particular, control
structures can contain control structures. You've already seen several examples of if
statements inside loops, but any combination of one control structure inside another is
possible. We say that one structure is nested inside another. You can even have
multiple levels of nesting, such as a while loop inside an if statement inside another
while loop. The syntax of Java does not set a limit on the number of levels of nesting.
As a practical matter, though, it's difficult to understand a program that has more than
a few levels of nesting.
Nested for loops arise naturally in many algorithms, and it is important to understand
how they work. Let's look at a couple of examples. First, consider the problem of
printing out a multiplication table like this one:
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144
The data in the table are arranged into 12 rows and 12 columns. The process of
printing them out can be expressed in a pseudocode algorithm as
The first step in the for loop can itself be expressed as a for loop:
so a refined algorithm for printing the table has one for loop nested inside another:
Assuming that rowNumber and N have been declared to be variables of type int, this
can be expressed in Java as
This section has been weighed down with lots of examples of numerical processing.
For our final example, let's do some text processing. Consider the problem of finding
which of the 26 letters of the alphabet occur in a given string. For example, the letters
that occur in "Hello World" are D, E, H, L, O, R, and W. More specifically, we will
write a program that will list all the letters contained in a string and will also count the
number of different letters. The string will be input by the user. Let's start with a
pseudocode algorithm for the program.
Since we want to process the entire line of text that is entered by the user, we'll use
TextIO.getln() to read it. The line of the algorithm that reads "for each letter of the
alphabet" can be expressed as "for (letter='A'; letter<='Z'; letter++)". But
the body of this for loop needs more thought. How do we check whether the given
letter, letter, occurs in str? One idea is to look at each letter in the string in turn,
and check whether that letter is equal to letter. We can get the i-th character of str
with the function call str.charAt(i), where i ranges from 0 to str.length() - 1.
One more difficulty: A letter such as 'A' can occur in str in either upper or lower
case, 'A' or 'a'. We have to check for both of these. But we can avoid this difficulty by
converting str to upper case before processing it. Then, we only have to check for the
upper case letter. We can now flesh out the algorithm fully. Note the use of break in
the nested for loop. It is required to avoid printing or counting a given letter more
than once. The break statement breaks out of the inner for loop, but not the outer for
loop. Upon executing the break, the computer continues the outer loop with the next
value of letter.
str = str.toUpperCase();
count = 0;
TextIO.putln("Your input contains the following
letters:");
TextIO.putln();
TextIO.put(" ");
for ( letter = 'A'; letter <= 'Z'; letter++ ) {
int i; // Position of a character in str.
for ( i = 0; i < str.length(); i++ ) {
if ( letter == str.charAt(i) ) {
TextIO.put(letter);
TextIO.put(' ');
count++;
break;
}
}
}
TextIO.putln();
TextIO.putln();
TextIO.putln("There were " + count + " different
letters.");
} // end main()
In fact, there is an easier way to determine whether a given letter occurs in a string,
str. The built-in function str.indexOf(letter) will return -1 if letter does not
occur in the string. It returns a number greater than or equal to zero if it does occur.
So, we could check whether letter occurs in str simply by checking "if
(str.indexOf(letter) >= 0)". If we used this technique in the above program, we
wouldn't need a nested for loop. This gives you preview of how subroutines can be
used to deal with complexity.
The if Statement
if (boolean-expression)
statement-1
else
statement-2
Now, an if statement is, in particular, a statement. This means that either statement-1
or statement-2 in the above if statement can itself be an if statement. A problem
arises, however, if statement-1 is an if statement that has no else part. This special
case is effectively forbidden by the syntax of Java. Suppose, for example, that you
type
if ( x > 0 )
if (y > 0)
System.out.println("First case");
else
System.out.println("Second case");
Now, remember that the way you've indented this doesn't mean anything at all to the
computer. You might think that the else part is the second half of your "if (x > 0)"
statement, but the rule that the computer follows attaches the else to "if (y > 0)",
which is closer. That is, the computer reads your statement as if it were formatted:
if ( x > 0 )
if (y > 0)
System.out.println("First case");
else
System.out.println("Second case");
You can force the computer to use the other interpretation by enclosing the nested if
in a block:
if ( x > 0 ) {
if (y > 0)
System.out.println("First case");
}
else
System.out.println("Second case");
These two statements have different meanings: If x <= 0, the first statement doesn't
print anything, but the second statement prints "Second case.".
Much more interesting than this technicality is the case where statement-2, the else
part of the if statement, is itself an if statement. The statement would look like this
(perhaps without the final else part):
if (boolean-expression-1)
statement-1
else
if (boolean-expression-2)
statement-2
else
statement-3
However, since the computer doesn't care how a program is laid out on the page, this
is almost always written in the format:
if (boolean-expression-1)
statement-1
else if (boolean-expression-2)
statement-2
else
statement-3
You should think of this as a single statement representing a three-way branch. When
the computer executes this, one and only one of the three statements -- statement-1,
statement-2, or statement-3 -- will be executed. The computer starts by evaluating
boolean-expression-1. If it is true, the computer executes statement-1 and then
jumps all the way to the end of the outer if statement, skipping the other two
statements. If boolean-expression-1 is false, the computer skips statement-1 and
executes the second, nested if statement. To do this, it tests the value of boolean-
expression-2 and uses it to decide between statement-2 and statement-3.
Here is an example that will print out one of three different messages, depending on
the value of a variable named temperature:
If temperature is, say, 42, the first test is true. The computer prints out the message
"It's cold", and skips the rest -- without even evaluating the second condition. For a
temperature of 75, the first test is false, so the computer goes on to the second test.
This test is true, so the computer prints "It's nice" and skips the rest. If the
temperature is 173, both of the tests evaluate to false, so the computer says "It's hot"
(unless its circuits have been fried by the heat, that is).
You can go on stringing together "else-if's" to make multi-way branches with any
number of cases:
if (boolean-expression-1)
statement-1
else if (boolean-expression-2)
statement-2
else if (boolean-expression-3)
statement-3
.
. // (more cases)
.
else if (boolean-expression-N)
statement-N
else
statement-(N+1)
The computer evaluates boolean expressions one after the other until it comes to one
that is true. It executes the associated statement and skips the rest. If none of the
boolean expressions evaluate to true, then the statement in the else part is executed.
This statement is called a multi-way branch because only one of the statements will be
executed. The final else part can be omitted. In that case, if all the boolean
expressions are false, none of the statements is executed. Of course, each of the
statements can be a block, consisting of a number of statements enclosed between
{ and }. (Admittedly, there is lot of syntax here; as you study and practice, you'll
become comfortable with it.)
One way to approach this is to ask, where does x belong in the list? It comes first if
it's less than both y and z. It comes last if it's greater than both y and z. Otherwise, it
comes in the middle. We can express this with a 3-way if statement, but we still have
to worry about the order in which y and z should be printed. In pseudocode,
You might check that this code will work correctly even if some of the values are the
same. If the values of two variables are the same, it doesn't matter which order you
print them in.
Note, by the way, that even though you can say in English "if x is less than y and z,",
you can't say in Java "if (x < y && z)". The && operator can only be used between
boolean values, so you have to make separate tests, x<y and x<z, and then combine
the two tests with &&.
There is an alternative approach to this problem that begins by asking, "which order
should x and y be printed in?" Once that's known, you only have to decide where to
stick in z. This line of thought leads to different Java code:
Once again, we see how the same problem can be solved in many different ways. The
two approaches to this problem have not exhausted all the possibilities. For example,
you might start by testing whether x is greater than y. If so, you could swap their
values. Once you've done that, you know that x should be printed before y.
Finally, let's write a complete program that uses an if statement in an interesting way.
I want a program that will convert measurements of length from one unit of
measurement to another, such as miles to yards or inches to feet. So far, the problem is
extremely under-specified. Let's say that the program will only deal with
measurements in inches, feet, yards, and miles. It would be easy to extend it later to
deal with other units. The user will type in a measurement in one of these units, such
as "17 feet" or "2.73 miles". The output will show the length in terms of each of the
four units of measure. (This is easier than asking the user which units to use in the
output.) An outline of the process is
The program can read both parts of the user's input from the same line by using
TextIO.getDouble() to read the numerical measurement and TextIO.getlnWord()
to read the units of measure. The conversion into different units of measure can be
simplified by first converting the user's input into inches. From there, it can be
converted into feet, yards, and miles. We still have to test the input to determine
which unit of measure the user has specified:
In my final program, I decided to make things more interesting by allowing the user to
enter a whole sequence of measurements. The program will end only when the user
inputs 0. To do this, I just have to wrap the above algorithm inside a while loop, and
make sure that the loop ends when the user inputs a 0. Here's the complete program,
followed by an applet that simulates it.
while (true) {
if (units.equals("inch") || units.equals("inches")
|| units.equals("in")) {
inches = measurement;
}
else if (units.equals("foot") || units.equals("feet")
|| units.equals("ft")) {
inches = measurement * 12;
}
else if (units.equals("yard") || units.equals("yards")
|| units.equals("yd")) {
inches = measurement * 36;
}
else if (units.equals("mile") || units.equals("miles")
|| units.equals("mi"))
{
inches = measurement * 12 * 5280;
}
else {
TextIO.putln("Sorry, but I don't understand \""
+ units +
"\".");
continue; // back to start of while loop
}
TextIO.putln();
TextIO.putln("That's equivalent to:");
TextIO.put(inches, 15);
TextIO.putln(" inches");
TextIO.put(feet, 15);
TextIO.putln(" feet");
TextIO.put(yards, 15);
TextIO.putln(" yards");
TextIO.put(miles, 15);
TextIO.putln(" miles");
TextIO.putln();
} // end while
TextIO.putln();
TextIO.putln("OK! Bye for now.");
} // end main()
A switch statement allows you to test the value of an expression and, depending on
that value, to jump to some location within the switch statement. The expression must
be either integer-valued or character-valued. It cannot be a String or a real number.
The positions that you can jump to are marked with "case labels" that take the form:
"case constant:". This marks the position the computer jumps to when the expression
evaluates to the given constant. As the final case in a switch statement you can,
optionally, use the label "default:", which provides a default jump point that is used
when the value of the expression is not listed in any case label.
switch (expression) {
case constant-1:
statements-1
break;
case constant-2:
statements-2
break;
.
. // (more cases)
.
case constant-N:
statements-N
break;
default: // optional default case
statements-(N+1)
} // end of switch statement
The break statements are technically optional. The effect of a break is to make the
computer jump to the end of the switch statement. If you leave out the break
statement, the computer will just forge ahead after completing one case and will
execute the statements associated with the next case label. This is rarely what you
want, but it is legal. (I will note here -- although you won't understand it until you get
to the next chapter -- that inside a subroutine, the break statement is sometimes
replaced by a return statement.)
Note that you can leave out one of the groups of statements entirely (including the
break). You then have two case labels in a row, containing two different constants.
This just means that the computer will jump to the same place and perform the same
action for each of the two constants.
Here is an example of a switch statement. This is not a useful example, but it should
be easy for you to follow. Note, by the way, that the constants in the case labels don't
have to be in any particular order, as long as they are all different:
The switch statement is pretty primitive as control structures go, and it's easy to make
mistakes when you use it. Java takes all its control structures directly from the older
programming languages C and C++. The switch statement is certainly one place
where the designers of Java should have introduced some improvements.
switch ( optionNumber ) {
case 1:
TextIO.putln("Enter the number of inches: );
measurement = TextIO.getlnDouble();
inches = measurement;
break;
case 2:
TextIO.putln("Enter the number of feet: );
measurement = TextIO.getlnDouble();
inches = measurement * 12;
break;
case 3:
TextIO.putln("Enter the number of yards: );
measurement = TextIO.getlnDouble();
inches = measurement * 36;
break;
case 4:
TextIO.putln("Enter the number of miles: );
measurement = TextIO.getlnDouble();
inches = measurement * 12 * 5280;
break;
default:
TextIO.putln("Error! Illegal option number! I
quit!");
System.exit(1);
} // end switch
As a final note in this section, I will mention one more type of statement in Java: the
empty statement. This is a statement that consists simply of a semicolon. The
existence of the empty statement makes the following legal, even though you would
not ordinarily see a semicolon after a }.
if (x < 0) {
x = -x;
};
The semicolon is legal after the }, but the computer considers it to be an empty
statement, not part of the if statement. Occasionally, you might find yourself using
the empty statement when what you mean is, in fact, "do nothing". I prefer, though, to
use an empty block, consisting of { and } with nothing between, for such cases.
Why? Because the ";" at the end of the first line is a statement, and it is this statement
that is executed ten times. The System.out.println statement is not really inside the
for statement at all, so it is executed just once, after the for loop has completed.
A List of Java Statement Types
I mention the empty statement here mainly for completeness. You've now seen just
about every type of Java statement. A complete list is given below for reference. The
only new items in the list are the try..catch, throw, and synchronized statements,
which are related to advanced aspects of Java known as exception-handling and multi-
threading, and the return statement, which is used in subroutines. These will be
covered in later sections.
Another possible surprise is what I've listed as "other expression statement," which
reflects the fact that any expression followed by a semicolon can be used as a
statement. To execute such a statement, the computer simply evaluates the expression,
and then ignores the value. Of course, this only makes sense when the evaluation has
a side effect that makes some change in the state of the computer. An example of this
is the expression statement "x++;", which has the side effect of adding 1 to the value
of x. Similarly, the function call "TextIO.getln()", which reads a line of input, can
be used as a stand-alone statement if you want to read a line of input and discard it.
Note that, technically, assignment statements and subroutine call statements are also
considered to be expression statements.
An applet is a Java program that runs on a Web page. An applet is not a stand-alone
application, and it does not have a main() routine. In fact, an applet is an object
rather than a class. When an applet is placed on a Web page, it is assigned a
rectangular area on the page. It is the job of the applet to draw the contents of that
rectangle. When the region needs to be drawn, the Web page calls a subroutine in the
applet to do so. This is not so different from what happens with stand-alone programs.
When a program needs to be run, the system calls the main() routine of the program.
Similarly, when an applet needs to be drawn, the Web page calls the paint() routine
of the applet. The programmer specifies what happens when these routines are called
by filling in the bodies of the routines. Programming in the small! Applets can do
other things besides draw themselves, such as responding when the user clicks the
mouse on the applet. Each of the applet's behaviors is defined by a subroutine in the
applet object. The programmer specifies how the applet behaves by filling in the
bodies of the appropriate subroutines.
A very simple applet, which does nothing but draw itself, can be defined by a class
that contains nothing but a paint() routine. The source code for the class would have
the form:
import java.awt.*;
import java.applet.*;
where name-of-applet is an identifier that names the class, and the statements are the
code that actually draws the applet. This looks similar to the definition of a stand-
alone program, but there are a few things here that need to be explained, starting with
the first two lines.
When you write a program, there are certain built-in classes that are available for you
to use. These built-in classes include System and Math. If you want to use one of
these classes, you don't have to do anything special. You just go ahead and use it. But
Java also has a large number of standard classes that are there if you want them but
that are not automatically available to your program. (There are just too many of
them.) If you want to use these classes in your program, you have to ask for them
first. The standard classes are grouped into so-called "packages." Two of these
packages are called "java.awt" and "java.applet". The directive "import java.awt.*;"
makes all the classes from the package java.awt available for use in your program.
The java.awt package contains classes related to graphical user interface
programming, including a class called Graphics. The Graphics class is referred to in
the paint() routine above. The java.applet package contains classes specifically
related to applets, including the class named Applet.
The first line of the class definition above says that the class "extends Applet."
Applet is a standard class that is defined in the java.applet package. It defines all the
basic properties and behaviors of applet objects. By extending the Applet class, the
new class we are defining inherits all those properties and behaviors. We only have to
define the ways in which our class differs from the basic Applet class. In our case,
the only difference is that our applet will draw itself differently, so we only have to
define the paint() routine. This is one of the main advantages of object-oriented
programming.
(Actually, most of our applets will be defined to extend JApplet rather than Applet.
The JApplet class is itself an extension of Applet. The Applet class has existed
since the original version of Java, while JApplet is part of the newer "Swing" set of
graphical user interface components. For the moment, the distinction is not
important.)
One more thing needs to be mentioned -- and this is a point where Java's syntax gets
unfortunately confusing. Applets are objects, not classes. Instead of being static
members of a class, the subroutines that define the applet's behavior are part of the
applet object. We say that they are "non-static" subroutines. Of course, objects are
related to classes because every object is described by a class. Now here is the part
that can get confusing: Even though a non-static subroutine is not actually part of a
class (in the sense of being part of the behavior of the class), it is nevertheless defined
in a class (in the sense that the Java code that defines the subroutine is part of the Java
code that defines the class). Many objects can be described by the same class. Each
object has its own non-static subroutine. But the common definition of those
subroutines -- the actual Java source code -- is physically part of the class that
describes all the objects. To put it briefly: static subroutines in a class definition say
what the class does; non-static subroutines say what all the objects described by the
class do. An applet's paint() routine is an example of a non-static subroutine. A
stand-alone program's main() routine is an example of a static subroutine. The
distinction doesn't really matter too much at this point: When working with stand-
alone programs, mark everything with the reserved word, "static"; leave it out when
working with applets. However, the distinction between static and non-static will
become more important later in the course.
Let's write an applet that draws something. In order to write an applet that draws
something, you need to know what subroutines are available for drawing, just as in
writing text-oriented programs you need to know what subroutines are available for
reading and writing text. In Java, the built-in drawing subroutines are found in objects
of the class Graphics, one of the classes in the java.awt package. In an applet's
paint() routine, you can use the Graphics object g for drawing. (This object is
provided as a parameter to the paint() routine when that routine is called.) Graphics
objects contain many subroutines. I'll mention just three of them here. You'll find
more listed in Section 6.3.
g.setColor(c), is called to set the color that is used for drawing. The parameter, c is
an object belonging to a class named Color, another one of the classes in the java.awt
package. About a dozen standard colors are available as static member variables in the
Color class. These standard colors include Color.black, Color.white, Color.red,
Color.green, and Color.blue. For example, if you want to draw in red, you would
say "g.setColor(Color.red);". The specified color is used for all drawing
operations up until the next time setColor is called.
This applet first fills its entire rectangular area with red. Then it changes the drawing
color to black and draws a sequence of rectangles, where each rectangle is nested
inside the previous one. The rectangles can be drawn with a while loop. Each time
through the loop, the rectangle gets smaller and it moves down and over a bit. We'll
need variables to hold the width and height of the rectangle and a variable to record
how far the top-left corner of the rectangle is inset from the edges of the applet. The
while loop ends when the rectangle shrinks to nothing. In general outline, the
algorithm for drawing the applet is
In my applet, each rectangle is 15 pixels away from the rectangle that surrounds it, so
the inset is increased by 15 each time through the while loop. The rectangle shrinks
by 15 pixels on the left and by 15 pixels on the right, so the width of the rectangle
shrinks by 30 each time through the loop. The height also shrinks by 30 pixels each
time through the loop.
It is not hard to code this algorithm into Java and use it to define the paint() method
of an applet. I've assumed that the applet has a height of 160 pixels and a width of 300
pixels. The size is actually set in the source code of the Web page where the applet
appears. In order for an applet to appear on a page, the source code for the page must
include a command that specifies which applet to run and how big it should be. (The
commands that can be used on a Web page are discussed in Section 6.2.) It's not a
great idea to assume that we know how big the applet is going to be. On the other
hand, it's also not a great idea to write an applet that does nothing but draw a static
picture. I'll address both these issues before the end of this section. But for now, here
is the source code for the applet:
import java.awt.*;
import java.applet.Applet;
g.setColor(Color.red);
g.fillRect(0,0,300,160); // Fill the entire applet with
red.
inset = 0;
} // end paint()
(You might wonder why the initial rectWidth is set to 299, instead of to 300, since
the width of the applet is 300 pixels. It's because rectangles are drawn as if with a pen
whose nib hangs below and to the right of the point where the pen is placed. If you
run the pen exactly along the right edge of the applet, the line it draws is actually
outside the applet and therefore is not seen. So instead, we run the pen along a line
one pixel to the left of the edge of the applet. The same reasoning applies to
rectHeight. Careful graphics programming demands attention to details like these.)
When you write an applet, you get to build on the work of the people who wrote the
Applet class. The Applet class provides a framework on which you can hang your
own work. Any programmer can create additional frameworks that can be used by
other programmers as a basis for writing specific types of applets or stand-alone
programs. One example is the applets in previous sections that simulate text-based
programs. All these applets are based on a class called ConsoleApplet, which itself is
based on the standard Applet class. You can write your own console applet by filling
in this simple framework (which leaves out just a couple of bells and whistles):
public class name-of-applet extends ConsoleApplet {
The statements in the program() subroutine are executed when the user of the applet
clicks the applet's "Run Program" button. This "program" can't use TextIO or
System.out to do input and output. However, the ConsoleApplet framework
provides an object named console for doing text input/output. This object contains
exactly the same set of subroutines as the TextIO class. For example, where you
would say TextIO.putln("Hello World") in a stand-alone program, you could say
console.putln("Hello World") in a console applet. The console object just
displays the output on the applet instead of on standard output. Similarly, you can
substitute x = console.getInt() for x = TextIO.getInt(), and so on. As a simple
example, here's a console applet that gets two numbers from the user and prints their
product:
prod = x * y;
console.putln();
console.put("The product is ");
console.putln(prod);
} // end program()
Now, any console-style applet that you write depends on the ConsoleApplet class,
which is not a standard part of Java. This means that the compiled class file,
ConsoleApplet.class must be available to your applet when it is run. As a matter of
fact, ConsoleApplet uses two other non-standard classes, ConsolePanel and
ConsoleCanvas, so the compiled class files ConsolePanel.class and
ConsoleCanvas.class must also be available to your applet. This just means that all
four class files -- your own class and the three classes it depends on -- must be in the
same directory with the source code for the Web page on which your applet appears.
I've written another framework that makes it possible to write applets that display
simple animations. An example is given by the applet at the bottom of this page,
which is an animated version of the nested squares applet from earlier in this section.
A computer animation is really just a sequence of still images. The computer displays
the images one after the other. Each image differs a bit from the preceding image in
the sequence. If the differences are not too big and if the sequence is displayed
quickly enough, the eye is tricked into perceiving continuous motion.
In the example, rectangles shrink continually towards the center of the applet, while
new rectangles appear at the edge. The perpetual motion is, of course, an illusion. If
you think about it, you'll see that the applet loops through the same set of images over
and over. In each image, there is a gap between the borders of the applet and the
outermost rectangle. This gap gets wider and wider until a new rectangle appears at
the border. Only it's not a new rectangle. What has really happened is that the applet
has started over again with the first image in the sequence.
The problem of creating an animation is really just the problem of drawing each of the
still images that make up the animation. Each still image is called a frame. In my
framework for animation, which is based on a non-standard class called
SimpleAnimationApplet2, all you have to do is fill in the code that says how to draw
one frame. The basic format is as follows:
import java.awt.*;
In the sample applet, the thing that differs from one frame to another is the distance
between the edges of the applet and the outermost rectangle. Since the rectangles are
15 pixels apart, this distance increases from 0 to 14 and then jumps back to 0 when a
"new" rectangle appears. The appropriate value can be computed very simply from
the frame number, with the statement "inset = getFrameNumber() % 15;". The
value of the expression getFrameNumber() % 15 is between 0 and 14. When the
frame number reaches 15, the value of getFrameNumber() % 15 jumps back to 0.
Drawing one frame in the sample animated applet is very similar to drawing the single
image of the StaticRects applet, as given above. The paint() method in the
StaticRects applet becomes, with only minor modification, the drawFrame()
method of my MovingRects animation applet. I've chosen to make one improvement:
The StaticRects applet assumes that the applet is 300 by 160 pixels. The
MovingRects applet will work for any applet size. To implement this, the
drawFrame() routine has to know how big the applet is. There are two functions that
can be called to get this information. The function getWidth() returns an integer
value representing the width of the applet, and the function getHeight() returns the
height. The width and height, together with the frame number, are used to compute
the size of the first rectangle that is drawn. Here is the complete source code:
import java.awt.*;
} // end drawFrame()
(The SimpleAnimationApplet2 class uses Swing and requires Java version 1.3 or
better. There is an older version named SimpleAnimationApplet that provides the
same functionality but works with any version of Java. You could use
SimpleAnimationApplet to write animations that will work on older Web browsers.)
The main point here is that by building on an existing framework, you can do
interesting things using the type of local, inside-a-subroutine programming that was
covered in Chapters 2 and 3. As you learn more about programming and more about
Java, you'll be able to do more on your own -- but no matter how much you learn,
you'll always be dependent on other people's work to some extent.
CHAPTER SIX
Arrays
Creating and Using Arrays
WHEN A NUMBER OF DATA ITEMS are chunked together into a unit, the result is
a data structure. Data structures can have very complex structure, but in many
applications, the appropriate data structure consists simply of a sequence of data
items. Data structures of this simple variety can be either arrays or records.
The term "record" is not used in Java. A record is essentially the same as a Java object
that has instance variables only, but no instance methods. Some other languages,
which do not support objects in general, nevertheless do support records. The C
programming language, for example, is not object-oriented, but it has records, which
in C go by the name "struct." The data items in a record -- in Java, an object's instance
variables -- are called the fields of the record. Each item is referred to using a field
name. In Java, field names are just the names of the instance variables. The
distinguishing characteristics of a record are that the data items in the record are
referred to by name and that different fields in a record are allowed to be of different
types. For example, if the class Person is defined as:
class Person {
String name;
int id_number;
Date birthday;
int age;
}
then an object of class Person could be considered to be a record with four fields. The
field names are name, id_number, birthday, and age. Note that the fields are of various
types: String, int, and Date.
Because records are just a special type of object, I will not discuss them further.
Like a record, an array is a sequence of items. However, where items in a record are
referred to by name, the items in an array are numbered, and individual items are
referred to by their position number. Furthermore, all the items in an array must be
of the same type. The definition of an array is: a numbered sequence of items, which
are all of the same type. The number of items in an array is called the length of the
array. The position number of an item in an array is called the index of that item. The
type of the individual items in an array is called the base type of the array.
The base type of an array can be any Java type, that is, one of the primitive types, or a
class name, or an interface name. If the base type of an array is int, it is referred to as
an "array of ints." An array with base type String is referred to as an "array of Strings."
However, an array is not, properly speaking, a list of integers or strings or other
values. It is better thought of as a list of variables of type int, or of type String, or of
some other type. As always, there is some potential for confusion between the two
uses of a variable: as a name for a memory location and as a name for the value stored
in that memory location. Each position in an array acts as a variable. Each position
can hold a value of a specified type (the base type of the array). The value can be
changed at any time. Values are stored in an array. The array is the container, not the
values.
The items in an array -- really, the individual variables that make up the array -- are
more often referred to as the elements of the array. In Java, the elements in an array
are always numbered starting from zero. That is, the index of the first element in the
array is zero. If the length of the array is N, then the index of the last element in the
array is N-1. Once an array has been created, its length cannot be changed.
Java arrays are objects. This has several consequences. Arrays are created using a
form of the new operator. No variable can ever hold an array; a variable can only refer
to an array. Any variable that can refer to an array can also hold the value null,
meaning that it doesn't at the moment refer to anything. Like any object, an array
belongs to a class, which like all classes is a subclass of the class Object. The elements
of the array are, essentially, instance variables in the array object, except that they are
referred to by number rather than by name.
Nevertheless, even though arrays are objects, there are differences between arrays and
other kinds of objects, and there are a number of special language features in Java for
creating and using arrays.
Suppose that A is a variable that refers to an array. Then the item at index k in A is
referred to as A[k]. The first item is A[0], the second is A[1], and so forth. "A[k]" is
really a variable, and it can be used just like any other variable. You can assign values
to it, you can use it in expressions, and you can pass it as a parameter to subroutines.
All of this will be discussed in more detail below. For now, just keep in mind the
syntax
array-variable [ integer-expression ]
Although every array, as an object, is a member of some class, array classes never
have to be defined. Once a type exists, the corresponding array class exists
automatically. If the name of the type is BaseType, then the name of the associated
array class is BaseType[]. That is to say, an object belonging to the class BaseType[] is an
array of items, where each item is a variable of type BaseType. The brackets, "[]", are
meant to recall the syntax for referring to the individual items in the array. "BaseType[]"
is read as "array of BaseType" or "BaseType array." It might be worth mentioning
here that if ClassA is a subclass of ClassB, then ClassA[] is automatically a subclass of
ClassB[].
The base type of an array can be any legal Java type. From the primitive type int, the
array type int[] is derived. Each element in an array of type int[] is a variable of type int,
which holds a value of type int. From a class named Shape, the array type Shape[] is
derived. Each item in an array of type Shape[] is a variable of type Shape, which holds a
value of type Shape. This value can be either null or a reference to an object belonging
to the class Shape. (This includes objects belonging to subclasses of Shape.)
Let's try to get a little more concrete about all this, using arrays of integers as our first
example. Since int[] is a class, it can be used to declare variables. For example,
int[] list;
creates a variable named list of type int[]. This variable is capable of referring to an
array of ints, but initially its value is null (if it is a member variable in a class) or
undefined (if it is a local variable in a method). The new operator is used to create a
new array object, which can then be assigned to list. The syntax for using new with
arrays is different from the syntax you learned previously. As an example,
creates an array of five integers. More generally, the constructor "new BaseType[N]" is
used to create an array belonging to the class BaseType[]. The value N in brackets
specifies the length of the array, that is, the number of elements that it contains. Note
that the array "knows" how long it is. The length of the array is an instance variable in
the array object. In fact, the length of an array, list, can be referred to as list.length.
(However, you are not allowed to change the value of list.length, so it's really a "final"
instance variable, that is, one whose value cannot be changed after it has been
initialized.)
The situation produced by the statement "list = new int[5];" can be pictured like this:
Note that the newly created array of integers is automatically filled with zeros. In
Java, a newly created array is always filled with a known, default value: zero for
numbers, false for boolean, the character with Unicode number zero for char, and null for
objects.
The elements in the array, list, are referred to as list[0], list[1], list[2], list[3], and list[4].
(Note again that the index for the last item is one less than list.length.) However, array
references can be much more general than this. The brackets in an array reference can
contain any expression whose value is an integer. For example if indx is a variable of
type int, then list[indx] and list[2*indx+7] are syntactically correct references to elements
of the array list. Thus, the following loop would print all the integers in the array, list,
to standard output:
The first time through the loop, i is 0, and list[i] refers to list[0]. So, it is the value
stored in the variable list[0] that is printed. The second time through the loop, i is 1,
and the value stored in list[1] is printed. The loop ends after printing the value of list[4],
when i becomes equal to 5 and the continuation condition "i<list.length" is no longer
true. This is a typical example of using a loop to process an array. I'll discuss more
examples of array processing throughout this chapter.
Every use of a variable in a program specifies a memory location. Think for a moment
about what the computer does when it encounters a reference to an array element,
list[k], while it is executing a program. The computer must determine which memory
location is being referred to. To the computer, list[k] means something like this: "Get
the pointer that is stored in the variable, list. Follow this pointer to find an array object.
Get the value of k. Go to the k-th position in the array, and that's the memory location
you want." There are two things that can go wrong here. Suppose that the value of list
is null. If that is the case, then list doesn't even refer to an array. The attempt to refer to
an element of an array that doesn't exist is an error. This is an example of a "null
pointer" error. The second possible error occurs if list does refer to an array, but the
value of k is outside the legal range of indices for that array. This will happen if k < 0
or if k >= list.length. This is called an "array index out of bounds" error. When you use
arrays in a program, you should be mindful that both types of errors are possible.
However, array index out of bounds errors are by far the most common error when
working with arrays.
For an array variable, just as for any variable, you can declare the variable and
initialize it in a single step. For example,
If list is a local variable in a subroutine, then this is exactly equivalent to the two
statements:
int[] list;
list = new int[5];
(If list is an instance variable, then of course you can't simply replace "int[] list = new
int[5];" with "int[] list; list = new int[5];" since the assignment statement "list = new int[5];" is
only legal inside a subroutine.)
The new array is filled with the default value appropriate for the base type of the array
-- zero for int and null for class types, for example. However, Java also provides a way
to initialize an array variable with a new array filled with a specified list of values. In
a declaration statement that creates a new array, this is done with an array initializer.
For example,
creates a new array containing the seven values 1, 4, 9, 16, 25, 36, and 49, and sets list
to refer to that new array. The value of list[0] will be 1, the value of list[1] will be 4, and
so forth. The length of list is seven, since seven values are provided in the initializer.
An array initializer takes the form of a list of values, separated by commas and
enclosed between braces. The length of the array does not have to be specified,
because it is implicit in the list of values. The items in an array initializer don't have to
be constants. They can be variables or arbitrary expressions, provided that their values
are of the appropriate type. For example, the following declaration creates an array of
eight Colors. Some of the colors are given by expressions of the form "new Color(r,g,b)":
Color[] palette =
{
Color.black,
Color.red,
Color.pink,
new Color(0,180,0), // dark green
Color.green,
Color.blue,
new Color(180,180,255), // light blue
Color.white
};
A list initializer of this form can be used only in a declaration statement, to give an
initial value to a newly declared array variable. It cannot be used in an assignment
statement to assign a value to a variable that has been previously declared. However,
there is another, similar notation for creating a new array that can be used in an
assignment statement or passed as a parameter to a subroutine. The notation uses
another form of the new operator to create and initialize a new array object For
example to assign a new value to an array variable, list, that was declared previously,
you could use:
This is an expression whose value is an array object. It can be used in any context
where an object of type base-type[] is expected. For example, if makeButtons is a
method that takes an array of Strings as a parameter, you could say:
int[] list;
int list[];
which is a syntax used in the languages C and C++. However, this alternative syntax
does not really make much sense in the context of Java, and it is probably best
avoided. After all, the intent is to declare a variable of a certain type, and the name of
that type is "int[]". It makes sense to follow the "type-name variable-name;" syntax
for such declarations.
In many cases, processing an array means applying the same operation to each item in
the array. This is commonly done with a for loop. A loop for processing all the items in
an array A has the form:
Suppose, for example, that A is an array of type double[]. Suppose that the goal is to
add up all the numbers in the array. An informal algorithm for doing this would be:
Start with 0;
Add A[0]; (process the first item in A)
Add A[1]; (process the second item in A)
.
.
.
Add A[ A.length - 1 ]; (process the last item in A)
Putting the obvious repetition into a loop and giving a name to the sum, this becomes:
Note that the continuation condition, "i < A.length", implies that the last value of i that
is actually processed is A.length-1, which is the index of the final item in the array. It's
important to use "<" here, not "<=", since "<=" would give an array index out of
bounds error.
Eventually, you should just about be able to write loops similar to this one in your
sleep. I will give a few more simple examples. Here is a loop that will count the
number of items in the array A which are less than zero:
int count = 0;
for (int i = 0; i < A.length - 1; i++) {
if (A[i] == A[i+1])
count++;
}
(There is one subtle problem here. It's possible in Java for an array to have length
zero. In that case, A[0] doesn't exist, and the reference to A[0] in the first line gives an
array index out of bounds error. However, zero-length arrays are normally something
that you want to avoid in real problems. Anyway, what would it mean to ask for the
largest item in an array that contains no items at all?)
double[] B = A;
since this does not create a new array object. All it does is declare a new array
variable and make it refer to the same object to which A refers. (So that, for example,
a change to A[i] will automatically change B[i] as well.) To make a new array that is a
copy of A, it is necessary to make a new array object and to copy each of the
individual items from A into the new array:
where sourceArray and destArray can be arrays with any base type. Values are copied
from sourceArray to destArray. The count tells how many elements to copy. Values are
taken from sourceArray starting at position sourceStartIndex and are stored in destArray
starting at position destStartIndex. For example, to make a copy of the array, A, using
this subroutine, you would say:
An array type, such as double[], is a full-fledged Java type, so it can be used in all the
ways that any other Java type can be used. In particular, it can be used as the type of a
formal parameter in a subroutine. It can even be the return type of a function. For
example, it might be useful to have a function that makes a copy of an array of doubles:
The main() routine of a program has a parameter of type String[]. You've seen this used
since all the way back in Chapter 2, but I haven't really been able to explain it until
now. The parameter to the main() routine is an array of Strings. When the system calls
the main() routine, the strings in this array are the command-line parameters. When
using a command-line interface, the user types a command to tell the system to
execute a program. The user can include extra input in this command, beyond the
name of the program. This extra input becomes the command-line parameters. For
example, if the name of the class that contains the main() routine is myProg, then the
user can type "java myProg" to execute the program. In this case, there are no
command-line parameters. But if the user types the command "java myProg one two
three", then the command-line parameters are the strings "one", "two", and "three".
The system puts these strings into an array of Strings and passes that array as a
parameter to the main() routine. Here, for example, is a short program that simply
prints out any command line parameters entered by the user:
Note that the parameter, args, is never null when main() is called by the system, but it
might be an array of length zero.
So far, all my examples of array processing have used sequential access. That is, the
elements of the array were processed one after the other in the sequence in which they
occur in the array. But one of the big advantages of arrays is that they allow random
access. That is, every element of the array is equally accessible at any given time.
To simulate the experiment, we need to keep track of each birthday that we find.
There are 365 different possible birthdays. (We'll ignore leap years.) For each possible
birthday, we need to know, has this birthday already been used? The answer is a
boolean value, true or false. To hold this data, we can use an array of 365 boolean
values:
boolean[] used;
used = new boolean[365];
The days of the year are numbered from 0 to 364. The value of used[i] is true if
someone has been selected whose birthday is day number i. Initially, all the values in
the array, used, are false. When we select someone whose birthday is day number i, we
first check whether used[i] is true. If so, then this is the second person with that
birthday. We are done. If used[i] is false, we set used[i] to be true to record the fact that
we've encountered someone with that birthday, and we go on to the next person. Here
is a subroutine that carries out the simulated experiment (Of course, in the subroutine,
there are no simulated people, only simulated birthdays):
count = 0;
while (true) {
// Select a birthday at random, from 0 to 364.
// If the birthday has already been used, quit.
// Otherwise, record the birthday as used.
int birthday; // The selected birthday.
birthday = (int)(Math.random()*365);
count++;
if ( used[birthday] )
break;
used[birthday] = true;
}
} // end birthdayProblem()
This subroutine makes essential use of the fact that every element in a newly created
array of booleans is set to be false. If we wanted to reuse the same array in a second
simulation, we would have to reset all the elements in it to be false with a for loop
Here is an applet that will run the simulation as many times as you like. Are you
surprised at how few people have to be chosen, in general?
One of the examples in Section 6.4 was an applet that shows multiple copies of a
message in random positions, colors, and fonts. When the user clicks on the applet,
the positions, colors, and fonts are changed to new random values. Like several other
examples from that chapter, the applet had a flaw: It didn't have any way of storing
the data that would be necessary to redraw itself. Chapter 7 introduced off-screen
canvases as a solution to this problem, but off-screen canvases are not a good solution
in every case. Arrays provide us with an alternative solution. Here's a new version of
the applet. This version uses an array to store the position, font, and color of each
string. When the applet is painted, this information is used to draw the strings, so it
will redraw itself correctly when it is covered and then uncovered. When you click on
the applet, the array is filled with new random values and the applet is repainted.
In this applet, the number of copies of the message is given by a named constant,
MESSAGE_COUNT. One way to store the position, color, and font of MESSAGE_COUNT
strings would be to use four arrays:
These arrays would be filled with random values. In the paintComponent() method, the i-
th copy of the string would be drawn at the point (x[i],y[i]). Its color would be given by
color[i]. And it would be drawn in the font font[i]. This would be accomplished by the
paintComponent() method
This approach is said to use parallel arrays. The data for a given copy of the message
is spread out across several arrays. If you think of the arrays as laid out in parallel
columns -- array x in the first column, array y in the second, array color in the third,
and array font in the fourth -- then the data for the i-th string can be found along the
the i-th row. There is nothing wrong with using parallel arrays in this simple example,
but it does go against the object-oriented philosophy of keeping related data in one
object. If we follow this rule, then we don't have to imagine the relationship among
the data because all the data for one copy of the message is physically in one place.
So, when I wrote the applet, I made a simple class to represent all the data that is
needed for one copy of message:
class StringData {
// Data for one copy of the message.
int x,y; // Position of the message.
Color color; // Color of the message.
Font font; // Font used for the message.
}
(This class is actually defined as a static nested class in the main applet class.) To
store the data for multiple copies of the message, I use an array of type StringData[].
The array is declared as an instance variable, with the name data:
StringData[] data;
Of course, the value of data is null until an actual array is created and assigned to it.
This is done in the init() method of the applet with the statement
Just after this array is created, the value of each element in the array is null. We want
to store data in objects of type StringData, but no such objects exist yet. All we have is
an array of variables that are capable of referring to such objects. I decided to create
the objects in the applet's init method. (It could be done in other places -- just so long
as we avoid trying to use to an object that doesn't exist. This is important: Remember
that a newly created array whose base type is an object type is always filled with null
elements. There are no objects in the array until you put them there.) The objects are
created with the for loop
Now, the idea is to store data for the i-th copy of the message in the variables data[i].x,
data[i].y, data[i].color, and data[i].font. (Make sure that you understand the notation here:
data[i] refers to an object. That object contains instance variables. The notation data[i].x
tells the computer: "Find your way to the object that is referred to by data[i]. Then go
to the instance variable named x in that object." Variable names can get even more
complicated than this.) Using the array, data, the paintComponent() method for the applet
becomes
There is still the matter of filling the array, data, with random values. If you are
interested, you can look at the source code for the applet,
RandomStringsWithArray.java.
The applet actually uses one other array. The font for a given copy of the message is
chosen at random from a set of five possible fonts. In the original version of the
applet, there were five variables of type Font to represent the fonts. The variables were
named font1, font2, font3, font4, and font5. To select one of these fonts at random, a switch
statement could be used:
In the new version of the applet, the five fonts are stored in an array, which is named
fonts. This array is declared as an instance variable
Font[] fonts;
The array is created and filled with fonts in the init() method:
This makes it much easier to select one of the fonts at random. It can be done with the
statements
The switch statement has been replaced by a single line of code. This is a very typical
application of arrays. Here is another example of the same sort of thing. Months are
often stored as numbers 1, 2, 3, ..., 12. Sometimes, however, these numbers have to be
translated into the names January, February, ..., December. The translation can be
done with an array. The array could be declared and initialized as
If mth is a variable that holds one of the integers 1 through 12, then monthName[mth-1] is
the name of the corresponding month. We need the "-1" because months are numbered
starting from 1, while array elements are numbered starting from 0. Simple array
indexing does the translation for us!
Dynamic Arrays, ArrayLists, and Vectors
THE SIZE OF AN ARRAY is fixed when it is created. In many cases, however, the
number of data items that are actually stored in the array varies with time. Consider
the following examples: An array that stores the lines of text in a word-processing
program. An array that holds the list of computers that are currently downloading a
page from a Web site. An array that contains the shapes that have been added to the
screen by the user of a drawing program. Clearly, we need some way to deal with
cases where the number of data items in an array is not fixed.
Consider an application where the number of items that we want to store in an array
changes as the program runs. Since the size of the array can't actually be changed, a
separate counter variable must be used to keep track of how many spaces in the array
are in use. (Of course, every space in the array has to contain something; the question
is, how many spaces contain useful or valid items?)
Consider, for example, a program that reads positive integers entered by the user and
stores them for later processing. The program stops reading when the user inputs a
number that is less than or equal to zero. The input numbers can be kept in an array,
numbers, of type int[]. Let's say that no more than 100 numbers will be input. Then the
size of the array can be fixed at 100. But the program must keep track of how many
numbers have actually been read and stored in the array. For this, it can use an integer
variable, numCt. Each time a number is stored in the array, numCt must be incremented
by one. As a rather silly example, let's write a program that will read the numbers
input by the user and then print them in reverse order. (This is, at least, a processing
task that requires that the numbers be saved in an array. Remember that many types of
processing, such as finding the sum or average or maximum of the numbers, can be
done without saving the individual numbers.)
while (true) { // Get the numbers and put them in the array.
TextIO.put("? ");
num = TextIO.getlnInt();
if (num <= 0)
break;
numbers[numCt] = num;
numCt++;
}
} // end main();
It is especially important to note that the variable numCt plays a dual role. It is the
number of numbers that have been entered into the array. But it is also the index of the
next available spot in the array. For example, if 4 numbers have been stored in the
array, they occupy locations number 0, 1, 2, and 3. The next available spot is location
4. When the time comes to print out the numbers in the array, the last occupied spot in
the array is location numCt - 1, so the for loop prints out values starting from location
numCt - 1 and going down to 0.
Let's look at another, more realistic example. Suppose that you write a game program,
and that players can join the game and leave the game as it progresses. As a good
object-oriented programmer, you probably have a class named Player to represent the
individual players in the game. A list of all players who are currently in the game
could be stored in an array, playerList, of type Player[]. Since the number of players can
change, you will also need a variable, playerCt, to record the number of players
currently in the game. Assuming that there will never be more than 10 players in the
game, you could declare the variables as:
After some players have joined the game, playerCt will be greater than 0, and the
player objects representing the players will be stored in the array elements playerList[0],
playerList[1], ..., playerList[playerCt-1]. Note that the array element playerList[playerCt] is not
in use. The procedure for adding a new player, newPlayer, to the game is simple:
Deleting a player from the game is a little harder, since you don't want to leave a
"hole" in the array. Suppose you want to delete the player at index k in playerList. If
you are not worried about keeping the players in any particular order, then one way to
do this is to move the player from the last occupied position in the array into position
k and then to decrement the value of playerCt:
The player previously in position k is no longer in the array. The player previously in
position playerCt - 1 is now in the array twice. But it's only in the occupied or valid part
of the array once, since playerCt has decreased by one. Remember that every element
of the array has to hold some value, but only the values in positions 0 through playerCt
- 1 will be looked at or processed in any way.
Suppose that when deleting the player in position k, you'd like to keep the remaining
players in the same order. (Maybe because they take turns in the order in which they
are stored in the array.) To do this, all the players in positions k+1 and above must
move down one position in the array. Player k+1 replaces player k, who is out of the
game. Player k+2 fills the spot left open when player k+1 moved. And so on. The code
for this is
It's worth emphasizing that the Player example deals with an array whose base type is a
class. An item in the array is either null or is a reference to an object belonging to the
class, Player. The Player objects themselves are not really stored in the array, only
references to them. Note that because of the rules for assignment in Java, the objects
can actually belong to subclasses of Player. Thus there could be different classes of
Players such as computer players, regular human players, players who are wizards, ...,
all represented by different subclasses of Player.
As another example, suppose that a class Shape represents the general idea of a shape
drawn on a screen, and that it has subclasses to represent specific types of shapes such
as lines, rectangles, rounded rectangles, ovals, filled-in ovals, and so forth. (Shape
itself would be an abstract class, as discussed in Section 5.4.) Then an array of type
Shape[] can hold references to objects belonging to the subclasses of Shape. For
example, the situation created by the statements
The statement "shapes[i].redraw(g);" calls the redraw() method belonging to the particular
shape at index i in the array. Each object knows how to redraw itself, so that repeated
executions of the statement can produce a variety of different shapes on the screen.
This is nice example both of polymorphism and of array processing.
Dynamic Arrays
In each of the above examples, an arbitrary limit was set on the number of items --
100 ints, 10 Players, 100 Shapes. Since the size of an array is fixed, a given array can
only hold a certain maximum number of items. In many cases, such an arbitrary limit
is undesirable. Why should a program work for 100 data values, but not for 101? The
obvious alternative of making an array that's so big that it will work in any practical
case is not usually a good solution to the problem. It means that in most cases, a lot of
computer memory will be wasted on unused space in the array. That memory might be
better used for something else. And what if someone is using a computer that could
handle as many data values as the user actually wants to process, but doesn't have
enough memory to accommodate all the extra space that you've allocated?
Clearly, it would be nice if we could increase the size of an array at will. This is not
possible, but what is possible is just as good. Remember that an array variable does
not actually hold an array. It just holds a reference to an array object. We can't make
the array bigger, but we can make a new, bigger array object and change the value of
the array variable so that it refers to the bigger array. Of course, we also have to copy
the contents of the old array into the new array. The array variable then refers to an
array object that contains all the data of the old array, with room for additional data.
The old array will be garbage collected, since it is no longer in use.
Let's look back at the game example, in which playerList is an array of type Player[] and
playerCt is the number of spaces that have been used in the array. Suppose that we
don't want to put a pre-set limit on the number of players. If a new player joins the
game and the current array is full, we just make a new, bigger one. The same variable,
playerList, will refer to the new array. Note that after this is done, playerList[0] will refer
to a different memory location, but the value stored in playerList[0] will still be the
same as it was before. Here is some code that will do this:
if (playerCt == playerList.length) {
// Array is full. Make a new, bigger array,
// copy the contents of the old array into it,
// and set playerList to refer to the new array.
int newSize = 2 * playerList.length; // Size of new array.
Player[] temp = new Player[newSize]; // The new array.
System.arraycopy(playerList, 0, temp, 0, playerList.length);
playerList = temp; // Set playerList to refer to new array.
}
If we are going to be doing things like this regularly, it would be nice to define a
reusable class to handle the details. An array-like object that changes size to
accommodate the amount of data that it actually contains is called a dynamic array. A
dynamic array supports the same operations as an array: putting a value at a given
position and getting the value that is stored at a given position. But there is no upper
limit on the positions that can be used (except those imposed by the size of the
computer's memory). In a dynamic array class, the put and get operations must be
implemented as instance methods. Here, for example, is a class that implements a
dynamic array of ints:
public DynamicArrayOfInt() {
// Constructor.
data = new int[1]; // Array will grow as necessary.
}
The data in a DynamicArrayOfInt object is actually stored in a regular array, but that
array is discarded and replaced by a bigger array whenever necessary. If numbers is a
variable of type DynamicArrayOfInt, then the command numbers.put(pos,val) stores the
value val at position number pos in the dynamic array. The function numbers.get(pos)
returns the value stored at position number pos.
The first example in this section used an array to store positive integers input by the
user. We can rewrite that example to use a DynamicArrayOfInt. A reference to numbers[i]
is replaced by numbers.get(i). The statement "numbers[numCt] = num;" is replaced by
"numbers.put(numCt,num);". Here's the program:
} // end main();
The following applet simulates this program. I've included an output statement in the
DynamicArrayOfInt class. This statement will inform you each time the data array
increases in size. (Of course, the output statement doesn't really belong in the class.
It's included here for demonstration purposes.)
ArrrayLists
The DynamicArrayOfInt class could be used in any situation where an array of int with
no preset limit on the size is needed. However, if we want to store Shapes instead of
ints, we would have to define a new class to do it. That class, probably named
"DynamicArrayOfShape", would look exactly the same as the DynamicArrayOfInt class
except that everywhere the type "int" appears, it would be replaced by the type
"Shape". Similarly, we could define a DynamicArrayOfDouble class, a DynamicArrayOfPlayer
class, and so on. But there is something a little silly about this, since all these classes
are close to being identical. It would be nice to be able to write some kind of source
code, once and for all, that could be used to generate any of these classes on demand,
given the type of value that we want to store. This would be an example of generic
programming. Some programming languages, such as C++, have support for generic
programming. Java does not, at least not quite. We can come close to generic
programming in Java by working with data structures that contain elements of type
Object.
In Java, every class is a subclass of the class named Object. This means that every
object can be assigned to a variable of type Object. Any object can be put into an array
of type Object[]. If a subroutine has a formal parameter of type Object, than any object
can be passed to the subroutine as an actual parameter. If we defined a
DynamicArrayOfObject class, then we could store objects of any type. This is not true
generic programming, and it doesn't apply to the primitive types such as int and double.
But it does come close. In fact, there is no need for us to define a DynamicArrayOfObject
class. Java already has a standard class named ArrayList that serves much the same
purpose. The ArrayList class is in the package java.util, so if you want to use the ArrayList
class in a program, you should put the directive "import java.util.ArrayList;" or "import
java.util.*;" at the beginning of your source code file.
The ArrayList class differs from my DynamicArrayOfInt class in that an ArrayList object
always has a definite size, and it is illegal to refer to a position in the ArrayList that lies
outside its size. In this, an ArrayList is more like a regular array. However, the size of
an ArrayList can be increased at will. The ArrayList class defines many instance
methods. I'll describe some of the most useful. Suppose that list is a variable of type
ArrayList.
-- This function returns the current size of the ArrayList. The only valid
list.size()
positions in the list are numbers in the range 0 to list.size()-1. Note that the size can be
zero. A call to the default constructor new ArrayList() creates an ArrayList of size zero.
-- Adds an object onto the end of the ArrayList, increasing the size by 1. The
list.add(obj)
parameter, obj, can refer to an object of any type, or it can be null.
-- This function returns the value stored at position N in the ArrayList. N must
list.get(N)
be an integer in the range 0 to list.size()-1. If N is outside this range, an error occurs.
Calling this function is similar to referring to A[N] for an array, A, except that you
can't use list.get(N) on the left side of an assignment statement.
-- Assigns the object, obj, to position N in the ArrayList, replacing the item
list.set(N, obj)
previously stored at position N. The integer N must be in the range from 0 to list.size()-
1. A call to this function is equivalent to the command A[N] = obj for an array A.
-- For an integer, N, this removes the N-th item in the ArrayList. N must be
list.remove(N)
in the range 0 to list.size()-1. Any items in the list that come after the removed item are
moved down one position. The size of the ArrayList decreases by 1.
-- A function that searches for the object, obj, in the ArrayList If the
list.indexOf(obj)
object is found in the list, then the position number where it is found is returned. If the
object is not found, then -1 is returned.
For example, suppose again that players in a game are represented by objects of type
Player. The players currently in the game could be stored in an ArrayList named players.
This variable would be declared as
ArrayList players;
If newPlayer is a variable that refers to a Player object, the new player would be added to
the ArrayList and to the game by saying
players.add(newPlayer);
players.remove(i);
Or, if player is a variable that refers to the Player that is to be removed, you could say
players.remove(player);
All this works very nicely. The only slight difficulty arises when you use the function
players.get(i) to get the value stored at position i in the ArrayList. The return type of this
function is Object. In this case the object that is returned by the function is actually of
type Player. In order to do anything useful with the returned value, it's usually
necessary to type-cast it to type Player:
The two lines inside the for loop can be combined to a single line:
((Player)players.get(i)).makeMove();
This gets an item from the list, type-casts it, and then calls the makeMove() method on
the resulting Player. The parentheses around "(Player)players.get(i)" are required because
of Java's precedence rules. The parentheses force the type-cast to be performed before
the makeMove() method is called.
In Section 5.4, I displayed an applet, ShapeDraw, that uses ArrayLists. Here is another
version of the same idea, simplified to make it easier to see how ArrayLists are being
used. Right-click the large white drawing area to add a colored rectangle. (On a
Macintosh, Command-click the drawing area.) The color of the rectangle is given by
the "rainbow palette" along the bottom of the applet. Click the palette to select a new
color. Click and drag rectangles with the left mouse button. Hold down the Alt or
Option key and click on a rectangle to delete it. Shift-click a rectangle to move it out
in front of all the other rectangles.
The source code for this applet is in the file SimpleDrawRects.java. You should be
able to follow it in its entirety. (If you've read Chapter 7, you can also take a look at
the file RainbowPalette.java, which defines a custom component that is used for the
colored palette in this applet.) Here, I just want to look at the parts of the program that
use an ArrayList.
The applet uses a variable named rects, of type ArrayList, to hold information about the
rectangles that have been added to the drawing area. The objects that are stored in the
list belong to a class, ColoredRect, that is defined as
class ColoredRect {
// Holds data for one colored rectangle.
int x,y; // Upper left corner of the rectangle.
int width,height; // size of the rectangle.
Color color; // Color of the rectangle.
}
If g is a variable of type Graphics, then the following code draws all the rectangles that
are stored in the list rects (with a black outline around each rectangle, as shown in the
applet):
To implement all the mouse operations in the applet, it must be possible to find the
rectangle, if any, that contains the point where the user clicked the mouse. To do this,
I wrote the function
The code for removing a ColoredRect, rect, from the drawing area is simply
rects.remove(rect) (followed by a repaint()). Bringing a given rectangle out in front of all
the other rectangles is just a little harder. Since the rectangles are drawn in the order in
which they occur in the ArrayList, the rectangle that is in the last position in the list is
in front of all the other rectangles on the screen. So we need to move the rectangle to
the last position in the list. This is done by removing the rectangle from its current
position in the list and then adding it back at the end:
This should be enough to give you the basic idea. You can look in the source code for
more details.
Vectors
The ArrayList class was introduced in Java version 1.2, as one of a group of classes
designed for working with collections of objects. We'll look at these "collection
classes" in Chapter 12. Earlier versions of Java did not include ArrayList, but they did
have a very similar class named java.util.Vector. You can still see Vectors used in older
code and in many of Java's standard classes, so it's worth knowing about them. Using
a Vector is similar to using an ArrayList, except that different names are used for some
commonly used instance methods, and some instance methods in one class don't
correspond to any instance method in the other class.
Like an ArrayList, a Vector is similar to an array of Objects that can grow to be as large as
necessary. The default constructor, new Vector(), creates a vector with no elements.
The Vector class includes many more methods, but these are probably the most
commonly used.
Sorting and searching are often discussed, in a theoretical sort of way, using an array
of numbers as an example. In practical situations, though, more interesting types of
data are usually involved. For example, the array might be a mailing list, and each
element of the array might be an object containing a name and address. Given the
name of a person, you might want to look up that person's address. This is an example
of searching, since you want to find the object in the array that contains the given
name. It would also be useful to be able to sort the array according to various criteria.
One example of sorting would be ordering the elements of the array so that the names
are in alphabetical order. Another example would be to order the elements of the array
according to zip code before printing a set of mailing labels. (This kind of sorting can
get you a cheaper postage rate on a large mailing.)
This example can be generalized to a more abstract situation in which we have an
array that contains objects, and we want to search or sort the array based on the value
of one of the instance variables in that array. We can use some terminology here that
originated in work with "databases," which are just large, organized collections of
data. We refer to each of the objects in the array as a record. The instance variables in
an object are then called fields of the record. In the mailing list example, each record
would contain a name and address. The fields of the record might be the first name,
last name, street address, state, city and zip code. For the purpose of searching or
sorting, one of the fields is designated to be the key field. Searching then means
finding a record in the array that has a specified value in its key field. Sorting means
moving the records around in the array so that the key fields of the record are in
increasing (or decreasing) order.
In this section, most of my examples follow the tradition of using arrays of numbers.
But I'll also give a few examples using records and keys, to remind you of the more
practical applications.
Searching
There is an obvious algorithm for searching for a particular item in an array: Look at
each item in the array in turn, and check whether that item is the one you are looking
for. If so, the search is finished. If you look at every item without finding the one you
want, then you can be sure that the item is not in the array. It's easy to write a
subroutine to implement this algorithm. Let's say the array that you want to search is
an array of ints. Here is a method that will search the array for a specified integer. If
the integer is found, the method returns the index of the location in the array where it
is found. If the integer is not in the array, the method returns the value -1 as a signal
that the integer could not be found:
return -1;
This method of searching an array by looking at each item in turn is called linear
search. If nothing is known about the order of the items in the array, then there is
really no better alternative algorithm. But if the elements in the array are known to be
in increasing or decreasing order, then a much faster search algorithm can be used. An
array in which the elements are in order is said to be sorted. Of course, it takes some
work to sort an array, but if the array is to be searched many times, then the work
done in sorting it can really pay off.
Binary search is a method for searching for a given item in a sorted array. Although
the implementation is not trivial, the basic idea is simple: If you are searching for an
item in a sorted list, then it is possible to eliminate half of the items in the list by
inspecting a single item. For example, suppose that you are looking for the number 42
in a sorted array of 1000 integers. Let's assume that the array is sorted into increasing
order. Suppose you check item number 500 in the array, and find that the item is 93.
Since 42 is less than 93, and since the elements in the array are in increasing order, we
can conclude that if 42 occurs in the array at all, then it must occur somewhere before
location 500. All the locations numbered 500 or above contain values that are greater
than or equal to 93. These locations can be eliminated as possible locations of the
number 42.
The next obvious step is to check location 250. If the number at that location is, say,
21, then you can eliminate locations before 250 and limit further search to locations
between 251 and 499. The next test will limit the search to about 125 locations, and
the one after that to about 62. After just 10 steps, there is only one location left. This
is a whole lot better than looking through every element in the array. If there were a
million items, it would still take only 20 steps for this method to search the array!
(Mathematically, the number of steps is the logarithm, in the base 2, of the number of
items in the array.)
In order to make binary search into a Java subroutine that searches an array A for an
item N, we just have to keep track of the range of locations that could possibly contain
N. At each step, as we eliminate possibilities, we reduce the size of this range. The
basic operation is to look at the item in the middle of the range. If this item is greater
than N, then the second half of the range can be eliminated. If it is less than N, then the
first half of the range can be eliminated. If the number in the middle just happens to
be N exactly, then the search is finished. If the size of the range decreases to zero, then
the number N does not occur in the array. Here is a subroutine that returns the location
of N in a sorted array A. If N cannot be found in the array, then a value of -1 is
returned instead:
int lowestPossibleLoc = 0;
int highestPossibleLoc = A.length - 1;
return -1;
Association Lists
Association lists are very widely used in computer science. For example, a compiler
has to keep track of the location in memory associated with each variable. It can do
this with an association list in which each key is a variable name and the associated
value is the address of that variable in memory. Another example would be a mailing
list, if we think of it as associating an address to each name on the list. As a related
example, consider a phone directory that associates a phone number to each name.
The items in the list could be objects belonging to the class:
class PhoneEntry {
String name;
String phoneNum;
}
The data for a phone directory consists of an array of type PhoneEntry[] and an integer
variable to keep track of how many entries are actually stored in the directory. (This is
an example of a "partially full array" as discussed in the previous section. It might be
better to use a dynamic array or an ArrayList to hold the phone entries.) A phone
directory could be an object belonging to the class:
class PhoneDirectory {
Note that the search method, getNumber, only looks through the locations in the array
that have actually been filled with PhoneEntries. Also note that unlike the search
routines given earlier, this routine does not return the location of the item in the array.
Instead, it returns the value that it finds associated with the key, name. This is often
done with association lists.
This class could use a lot of improvement. For one thing, it would be nice to use
binary search instead of simple linear search in the getNumber method. However, we
could only do that if the list of PhoneEntries were sorted into alphabetical order
according to name. In fact, it's really not all that hard to keep the list of entries in
sorted order, as you'll see in just a second.
Insertion Sort
We've seen that there are good reasons for sorting arrays. There are many algorithms
available for doing so. One of the easiest to understand is the insertion sort algorithm.
This method is also applicable to the problem of keeping a list in sorted order as you
add new items to the list. Let's consider that case first:
Suppose you have a sorted list and you want to add an item to that list. If you want to
make sure that the modified list is still sorted, then the item must be inserted into the
right location, with all the smaller items coming before it and all the bigger items after
it. This will mean moving each of the bigger items up one space to make room for the
new item.
Conceptually, this could be extended to a sorting method if we were to take all the
items out of an unsorted array, and then insert them back into the array one-by-one,
keeping the list in sorted order as we do so. Each insertion can be done using the insert
routine given above. In the actual algorithm, we don't really take all the items from
the array; we just remember what part of the array has been sorted:
The following is an illustration of one stage in insertion sort. It shows what happens
during one execution of the for loop in the above method, when itemsSorted is 5.
Selection Sort
Another typical sorting method uses the idea of finding the biggest item in the list and
moving it to the end -- which is where it belongs if the list is to be in increasing order.
Once the biggest item is in its correct location, you can then apply the same idea to
the remaining items. That is, find the next-biggest item, and move it into the next-to-
last space, and so forth. This algorithm is called selection sort. It's easy to write:
Insertion sort and selection sort are suitable for sorting fairly small arrays (up to a few
hundred elements, say). There are more complicated sorting algorithms that are much
faster than insertion sort and selection sort for large arrays. I'll discuss one such
algorithm in Section 11.1.
A variation of selection sort is used in the Hand class that was introduced in Section
5.3. (By the way, you are finally in a position to fully understand the source code for
both the Hand class and the Deck class from that section. See the source files Deck.java
and Hand.java.)
In the Hand class, a hand of playing cards is represented by a Vector. This is older code,
which used Vector instead of ArrayList, and I have chosen not to modify it so that you
would see at least one example of using Vectors. See the previous section for a
discussion of ArrayLists and Vectors.
The objects stored in the Vector are of type Card. A Card object contains instance
methods getSuit() and getValue() that can be used to determine the suit and value of the
card. In my sorting method, I actually create a new vector and move the cards one-by-
one from the old vector to the new vector. The cards are selected from the old vector
in increasing order. In the end, the new vector becomes the hand and the old vector is
discarded. This is certainly not an efficient procedure! But hands of cards are so small
that the inefficiency is negligible. Here is the code:
I can't resist ending this section on sorting with a related problem that is much less
common, but is a bit more fun. That is the problem of putting the elements of an array
into a random order. The typical case of this problem is shuffling a deck of cards. A
good algorithm for shuffling is similar to selection sort, except that instead of moving
the biggest item to the end of the list, an item is selected at random and moved to the
end of the list. Here is a subroutine to shuffle an array of ints:
Multi-Dimensional Arrays
ANY TYPE CAN BE USED AS THE BASE TYPE FOR AN ARRAY. You can have
an array of ints, an array of Strings, an array of Objects, and so on. In particular, since an
array type is a first-class Java type, you can have an array of arrays. For example, an
array of ints has type int[]. This means that there is automatically another type, int[][],
which represents an "array of arrays of ints". Such an array is said to be a two-
dimensional array. Of course once you have the type int[][], there is nothing to stop
you from forming the type int[][][], which represents a three-dimensional array -- and
so on. There is no limit on the number of dimensions that an array type can have.
However, arrays of dimension three or higher are fairly uncommon, and I concentrate
here mainly on two-dimensional arrays. The type BaseType[][] is usually read "two-
dimensional array of BaseType" or "BaseType array array".
The declaration statement "int[][] A;" declares a variable named A of type int[][]. This
variable can hold a reference to an object of type int[][]. The assignment statement "A =
new int[3][4];" creates a new two-dimensional array object and sets A to point to the
newly created object. As usual, the declaration and assignment could be combined in
a single declaration statement "int[][] A = new int[3][4];". The newly created object is an
array of arrays-of-ints. The notation int[3][4] indicates that there are 3 arrays-of-ints in
the array A, and that there are 4 ints in each array-of-ints. However, trying to think in
such terms can get a bit confusing -- as you might have already noticed. So it is
customary to think of a two-dimensional array of items as a rectangular grid or matrix
of items. The notation "new int[3][4]" can then be taken to describe a grid of ints with 3
rows and 4 columns. The following picture might help:
For the most part, you can ignore the reality and keep the picture of a grid in mind.
Sometimes, though, you will need to remember that each row in the grid is really an
array in itself. These arrays can be referred to as A[0], A[1], and A[2]. Each row is in
fact a value of type int[]. It could, for example, be passed to a subroutine that asks for
a parameter of type int[].
The notation A[1] refers to one of the rows of the array A. Since A[1] is itself an array
of ints, you can another subscript to refer to one of the positions in that row. For
example, A[1][3] refers to item number 3 in row number 1. Keep in mind, of course,
that both rows and columns are numbered starting from zero. So, in the above
example, A[1][3] is 5. More generally, A[i][j] refers to the grid position in row number i
and column number j. The 12 items in A are named as follows:
is actually a variable of type int. You can assign integer values to it or use it in
A[i][j]
any other context where an integer variable is allowed.
It might be worth noting that A.length gives the number of rows of A. To get the
number of columns in A, you have to ask how many ints there are in a row; this
number would be given by A[0].length, or equivalently by A[1].length or A[2].length.
(There is actually no rule that says that all the rows of an array must have the same
length, and some advanced applications of arrays use varying-sized rows. But if you
use the new operator to create an array in the manner described above, you'll always
get an array with equal-sized rows.)
It's possible to fill a multi-dimensional array with specified items at the time it is
declared. Recall that when an ordinary one-dimensional array variable is declared, it
can be assigned an "array initializer," which is just a list of values enclosed between
braces, { and }. Array initializers can also be used when a multi-dimensional array is
declared. An initializer for a two-dimensional array consists of a list of one-
dimensional array initializers, one for each row in the two-dimensional array. For
example, the array A shown in the picture above could be created with:
int[][] A = { { 1, 0, 12, -1 },
{ 7, -3, 2, 5 },
{ -5, -2, 2, 9 }
};
The first time the outer for loop executes (with row = 0), the inner for loop fills in the
four values in the first row of A, namely A[0][0] = 0, A[0][1] = 0, A[0][2] = 0, and A[0][3] =
0. The next execution of the outer for loop fills in the second row of A. And the third
and final execution of the outer loop fills in the final row of A.
int sum = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 4; i++)
sum = sum + A[i][j];
To process a three-dimensional array, you would, of course, use triply nested for loops.
A two-dimensional array can be used whenever the data being represented can be
naturally arranged into rows and columns. Often, the grid is built into the problem.
For example, a chess board is a grid with 8 rows and 8 columns. If a class named
ChessPiece is available to represent individual chess pieces, then the contents of a chess
board could be represented by a two-dimensional array:
Or consider the "mosaic" of colored rectangles used as an example in Section 4.6. The
mosaic is implemented by a class named MosaicCanvas. The data about the color of
each of the rectangles in the mosaic is stored in an instance variable named grid of
type Color[][]. Each position in this grid is occupied by a value of type Color. There is
one position in the grid for each colored rectangle in the mosaic. The actual two-
dimensional array is created by the statement:
where ROWS is the number of rows of rectangles in the mosaic and COLUMNS is the
number of columns. The value of the Color variable grid[i][j] is the color of the
rectangle in row number i and column number j. When the color of that rectangle is
changed to some color value, c, the value stored in grid[i][j] is changed with a
statement of the form "grid[i][j] = c;". When the mosaic is redrawn, the values stored in
the two-dimensional array are used to decide what color to make each rectangle. Here
is a simplified version of the code from the MosaicCanvas class that draws all the
colored rectangles in the grid. You can see how it uses the array:
Sometimes two-dimensional arrays are used in problems in which the grid is not so
visually obvious. Consider a company that owns 25 stores. Suppose that the company
has data about the profit earned at each store for each month in the year 2000. If the
stores are numbered from 0 to 24, and if the twelve months from January '00 through
December '00 are numbered from 0 to 11, then the profit data could be stored in an
array, profit, constructed as follows:
profit[3][2]would be the amount of profit earned at store number 3 in March, and more
generally, profit[storeNum][monthNum] would be the amount of profit earned in store
number storeNum in month number monthNum. In this example, the one-dimensional
array profit[storeNum] has a very useful meaning: It is just the profit data for one
particular store for the whole year.
Let's assume that the profit array has already been filled with data. This data can be
processed in a lot of interesting ways. For example, the total profit for the company --
for the whole year from all its stores -- can be calculated by adding up all the entries
in the array:
totalProfit = 0;
for (int store = 0; store < 25; store++) {
for (int month = 0; month < 12; month++)
totalProfit += profit[store][month];
}
Let's extend this idea to create a one-dimensional array that contains the total profit
for each month of the year:
As a final example of processing the profit array, suppose that we wanted to know
which store generated the most profit over the course of the year. To do this, we have
to add up the monthly profits for each store. In array terms, this means that we want to
find the sum of each row in the array. As we do this, we need to keep track of which
row produces the largest total.
total = 0.0;
for (month = 0; month < 12; month++)
total += profit[store][month];
} // end for
For the rest of this section, we'll look at a more substantial example. Here is an applet
that lets two users play checkers against each other. A player moves by clicking on the
piece to be moved and then on the empty square to which it is to be moved. The
squares that the current player can legally click are hilited. A piece that has been
selected to be moved is surrounded by a white border. Other pieces that can legally be
moved are surrounded by a cyan-colored border. If a piece has been selected, each
empty square that it can legally move to is hilited with a green border. The game
enforces the rule that if the current player can jump one of the opponent's pieces, then
the player must jump. When a player's piece becomes a king, by reaching the opposite
end of the board, a big white "K" is drawn on the piece.
I will only cover a part of the programming of this applet. I encourage you to read the
complete source code, Checkers.java. At over 700 lines, this is a more substantial
example than anything you've seen before in this course, but it's an excellent example
of state-based, event-driven programming. The source file defines four classes. The
logic of the game is implemented in a class named CheckersCanvas.
The data about the pieces on the board are stored in a two-dimensional array. Because
of the complexity of the program, I wanted to divide it into several classes. One of
these classes is CheckersData, which handles the data for the board. It is mainly this
class that I want to talk about.
The CheckersData class has an instance variable named board of type int[][]. The value of
board is set to "new int[8][8]", an 8-by-8 grid of integers. The values stored in the grid
are defined as constants representing the possible contents of a square on a
checkerboard:
The constants RED and BLACK are also used in my program (or, perhaps, misused) to
represent the two players in the game. When a game is started, the values in the
variable, board, are set to represent the initial state of the board. The grid of values
looks like
0 1 2 3 4 5 6 6
A black piece can only move "down" the grid. That is, the row number of the square it
moves to must be greater than the row number of the square it comes from. A red
piece can only move up the grid. Kings of either color, of course, can move in both
directions.
One function of the CheckersData class is to take care of all the details of making moves
on the board. An instance method named makeMove() is provided to do this. When a
player moves a piece from one square to another, the values stored at two positions in
the array are changed. But that's not all. If the move is a jump, then the piece that was
jumped is removed from the board. (The method checks whether the move is a jump
by checking if the square to which the piece is moving is two rows away from the
square where it starts.) Furthermore, a RED piece that moves to row 0 or a BLACK
piece that moves to row 7 becomes a king. This is good programming: the rest of the
program doesn't have to worry about any of these details. It just calls this makeMove()
method:
public void makeMove(int fromRow, int fromCol, int toRow, int toCol) {
// Make the move from (fromRow,fromCol) to (toRow,toCol). It is
// ASSUMED that this move is legal! If the move is a jump, the
// jumped piece is removed from the board. If a piece moves
// to the last row on the opponent's side of the board, the
// piece becomes a king.
} // end makeMove()
An even more important function of the CheckersData class is to find legal moves on
the board. In my program, a move in a Checkers game is represented by an object
belonging to the following class:
class CheckersMove {
// A CheckersMove object represents a move in the game of
// Checkers. It holds the row and column of the piece that is
// to be moved and the row and column of the square to which
// it is to be moved. (This class makes no guarantee that
// the move is legal.)
boolean isJump() {
// Test whether this move is a jump. It is assumed that
// the move is legal. In a jump, the piece moves two
// rows. (In a regular move, it only moves one row.)
return (fromRow - toRow == 2 || fromRow - toRow == -2);
}
The CheckersData class has an instance method which finds all the legal moves that are
currently available for a specified player. This method is a function that returns an
array of type CheckersMove[]. The array contains all the legal moves, represented as
CheckersMove objects. The specification for this method reads
Now, what is this "list"? We have to return the legal moves in an array. But since an
array has a fixed size, we can't create the array until we know how many moves there
are, and we don't know that until near the end of the method, after we've already made
the list! A neat solution is to use a ArrayList instead of an array to hold the moves as we
find them. As we add moves to the list, it will grow just as large as necessary. At the
end of the method, we can create the array that we really want and copy the data into
it:
Now, how do we find the legal jumps or the legal moves? The information we need is
in the board array, but it takes some work to extract it. We have to look through all the
positions in the array and find the pieces that belong to the current player. For each
piece, we have to check each square that it could conceivably move to, and check
whether that would be a legal move. There are four squares to consider. For a jump,
we want to look at squares that are two rows and two columns away from the piece.
Thus, the line in the algorithm that says "Find any legal jumps and add them to
moves" expands to:
The line that says "Find any other legal moves and add them to moves" expands to
something similar, except that we have to look at the four squares that are one column
and one row away from the piece. Testing whether a player can legally move from
one given square to another given square is itself non-trivial. The square the player is
moving to must actually be on the board, and it must be empty. Furthermore, regular
red and black pieces can only move in one direction. I wrote the following utility
method to check whether a player can make a given non-jump move:
private boolean canMove(int player, int r1, int c1, int r2, int c2) {
// This is called by the getLegalMoves() method to determine
// whether the player can legally move from (r1,c1) to (r2,c2).
// It is ASSUMED that (r1,c1) contains one of the player's
// pieces and that (r2,c2) is a neighboring square.
if (board[r2][c2] != EMPTY)
return false; // (r2,c2) already contains a piece.
if (player == RED) {
if (board[r1][c1] == RED && r2 > r1)
return false; // Regular red piece can only move down.
return true; // The move is legal.
}
else {
if (board[r1][c1] == BLACK && r2 < r1)
return false; // Regular black piece can only move up.
return true; // The move is legal.
}
} // end canMove()
/* If any jump moves were found, then the user must jump, so we
don't add any regular moves. However, if no jumps were found,
check for any legal regular moves. Look at each square on
the board. If that square contains one of the player's pieces,
look at a possible move in each of the four directions from
that square. If there is a legal move in that direction,
put it in the moves ArrayList.
*/
if (moves.size() == 0) {
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
if (board[row][col] == player
|| board[row][col] == playerKing) {
if (canMove(player,row,col,row+1,col+1))
moves.add(new CheckersMove(row,col,row+1,col+1));
if (canMove(player,row,col,row-1,col+1))
moves.add(new CheckersMove(row,col,row-1,col+1));
if (canMove(player,row,col,row+1,col-1))
moves.add(new CheckersMove(row,col,row+1,col-1));
if (canMove(player,row,col,row-1,col-1))
moves.add(new CheckersMove(row,col,row-1,col-1));
}
}
}
}
if (moves.size() == 0)
return null;
else {
CheckersMove[] moveArray = new CheckersMove[moves.size()];
for (int i = 0; i < moves.size(); i++)
moveArray[i] = (CheckersMove)moves.get(i);
return moveArray;
}
} // end getLegalMoves
CHAPTER SEVEN
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.
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.. 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.
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
import java.awt.*;
import java.applet.*;
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:
and here is the source code for this applet, including the init() method:
import java.awt.*;
import java.applet.*;
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:
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 javax.swing.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.
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. 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.
getContentPane().add(bttn);
} // end init()
HTML Basics
<HEAD>
<TITLE>page-title</TITLE>
</HEAD>
<BODY>
page-contents
</BODY>
</HTML>
Web browsers are not very picky about enforcing this structure; you can probably get
away with leaving out everything but the actual page contents. But it is good form to
follow this structure for your pages.
The <BODY> tag can take a number of modifiers that affect the appearance of the
page when it is displayed. The modifier named BGCOLOR can be used to set the
background color of the page. For example,
<BODY bgcolor=white>
will ensure that the background color for the page is white. You can add modifiers to
control the color of regular text (TEXT), hypertext links (LINK), and links to pages
that have already been visited (VLINK). When the user clicks and holds the mouse
button on a link, the link is said to be active; you can control the color of active links
with the ALINK modifier. For example, how about a page with a black background,
white text, blue links, red active links, and gray visited links:
<BODY bgcolor=black text=white link=blue alink=red vlink=gray>
There are several standard color names that you can use in this context, but if you
want complete control, you'll have to learn how to specify colors using hexadecimal
numbers. It is also possible to use an image for the background of the page, instead of
a solid color. Look up the details if you are interested.
Lists
There are several tags for producing lists of items. The most widely used of these are
<UL> and <OL>. The <OL> tag gives an "ordered list", in which the items are
numbered consecutively. The item numbers are provided by the browser. The <UL>
tag gives an "unordered list", in which the items are all marked with the same special
symbol. In the HTML source code, each list item is indicated by placing a <LI> tag at
the beginning of the item. The end of the list is marked by the appropriate closing tag,
</OL> or </UL>. For example, the following source code:
<UL>
<LI>Isaac Asimov
<LI>Ursula Leguin
<LI>Greg Bear
<LI>C. J. Cherryh
</UL>
produces this list:
Isaac Asimov
Ursula Leguin
Greg Bear
C. J. Cherryh
Links
The most distinctive feature of HTML is that documents can contain links to other
documents. The user can follow links from page to page and in the process visit pages
from all over the Internet.
The <A> tag is used to create a link. The text between the <A> and its matching </A>
appears on the page. Usually, it is underlined and in a special color. The user can
follow the link by clicking on this text. The <A> tag uses the modifier HREF to say
which document the link should connect to. The value for HREF must be a URL
(Uniform Resource Locator). A URL is a coded set of instructions for finding a
document on the Internet. For example, the URL for my own "home page" is
http://math.hws.edu/eck/
To make a link to this page, such as David's Home Page, I would use the HTML
source code
<A HREF="http://math.hws.edu/eck/">David's Home Page</A>
The best place to find URLs is on existing Web pages. Most browsers display the
URL for the page you are currently viewing, and they can display the URL of a link if
you point to the link with the mouse.
If you are writing an HTML document and you want to make a link to another
document that is in the same directory, you can use a relative URL. A relative URL
consists of just the name of the file. For example, the page you are now viewing
comes from a directory that also contains the other sections in this chapter.in the
above chapters, which is in a file named s1.html, the relative URL would be just
"s1.html", and the complete link would look like
<A HREF="s1.html">Section 1</A>
There are also relative URLs for linking to files that are in other directories. Using
relative URLs is a good idea, since if you use them, you can move a whole collection
of files without changing any of the links between them (as long as you don't change
the relative locations of the files).
When you type a URL into a Web browser, you can omit the "http://" at the beginning
of the URL. However, in an <A> tag in an HTML document, the "http://" can only be
omitted if the URL is a relative URL. For a normal URL, it is required.
Images
You can add images to a Web page with the <IMG> tag. (This is a tag that has no
matching closing tag.) The actual image must be stored in a separate file from the
HTML document. The <IMG> tag has a required modifier, named SRC, to specify the
URL of the image file. For most browsers, the image should be in one of the formats
GIF (with a file name ending in ".gif") or JPEG (with a file name ending in ".jpeg" or
".jpg"). A so-called animated gif file actually contains a series of images that the
browser will display as an animation. Usually, the image is stored in the same place as
the HTML document, and a relative URL is used to specify the image file.
The <IMG> tag also has several optional modifiers. It's a good idea to always include
the HEIGHT and WIDTH modifiers, which specify the size of the image in pixels.
Some browsers, including Netscape, handle images better if they know in advance
how big they are. For browsers that can't display images, you can use the ALT
modifier to specify a string that will be displayed by the browser in place of the
image.
The ALIGN modifier can be used to affect the placement of the image.
"ALIGN=RIGHT" will shove the image to the right edge of the page, and the text on
the page will flow around the image. "ALIGN=LEFT" works similarly.
(Unfortunately, "ALIGN=CENTER" doesn't have the meaning you would expect.
Browsers treat images as if they are just big characters. Images can occur inside
paragraphs, links, and headings, for example. Alignment values of CENTER, TOP,
and BOTTOM are used to specify how the image should line up with other characters
in a line of text: Should the baseline of the text be at the center, the top, or the bottom
of the image? Alignment values of RIGHT and LEFT were added to HTML later, but
they are the most useful values.)
For example, here is HTML code that will place an image from a file named
figure1.gif on the page.
<IMG SRC="figure1.gif" ALIGN=RIGHT HEIGHT=150
WIDTH=100 ALT="Figure 1">
The image is 100 pixels wide and 150 pixels high. It will appear on the right edge of
the page. If a browser can't display images, it will display the string "Figure 1"
instead.
There are many places on the Web where you can get graphics for use on your Web
pages. For example, http://www.iconbazaar.com makes a large number of images
available. You should, of course, check on the owner's copyright policy before using
someone else's images on your pages.
Coordinates
The screen of a computer is a grid of little squares called pixels. The color of each
pixel can be set individually, and drawing on the screen just means setting the colors
of individual pixels.
A graphics context draws in a rectangle made up of pixels. A position in the rectangle
is specified by a pair of integer coordinates, (x,y). The upper left corner has
coordinates (0,0). The x coordinate increases from left to right, and the y coordinate
increases from top to bottom. The illustration on the right shows a 12-by-8 pixel
component (with very large pixels). A small line, rectangle, and oval are shown as
they would be drawn by coloring individual pixels. (Note that, properly speaking, the
coordinates don't belong to the pixels but to the grid lines between them.)
For any component, you can find out the size of the rectangle that it occupies by
calling the instance method getSize(). This method returns an object that belongs to
the class, java.awt.Dimension. A Dimension object has two integer instance variables,
width and height. The width of the component is getSize().width pixels, and its height
is getSize().height pixels.
When you are writing an applet, you don't necessarily know the applet's size. The size
of an applet is usually specified in an <APPLET> tag in the source code of a Web
page, and it's easy for the Web-page author to change the specified size. In some
cases, when the applet is displayed in some other kind of window instead of on a Web
page, the applet can even be resized while it is running. So, it's not good form to
depend on the size of the applet being set to some particular value. For other
components, you have even less chance of knowing the component's size in advance.
This means that it's good form to check the size of a component before doing any
drawing on that component. For example, you can use a paintComponent() method
that looks like:
public void paintComponent(Graphics g) {
int width = getSize().width; // Find out the width of component.
int height = getSize().height; // Find out its height.
. . . // Draw the contents of the component.
}
Of course, your drawing commands will have to take the size into account. That is,
they will have to use (x,y) coordinates that are calculated based on the actual height
and width of the applet.
Colors
Java is designed to work with the RGB color system. An RGB color is specified by
three numbers that give the level of red, green, and blue, respectively, in the color. A
color in Java is an object of the class, java.awt.Color. You can construct a new color
by specifying its red, blue, and green components. For example,
myColor = new Color(r,g,b);
There are two constructors that you can call in this way. In the one that I almost
always use, r, g, and b are integers in the range 0 to 255. In the other, they are
numbers of type float in the range 0.0F to 1.0F. (You might recall that a literal of type
float is written with an "F" to distinguish it from a double number.) Often, you can
avoid constructing new colors altogether, since the Color class defines several named
constants representing common colors: Color.white, Color.black, Color.red,
Color.green, Color.blue, Color.cyan, Color.magenta, Color.yellow, Color.pink,
Color.orange, Color.lightGray, Color.gray, and Color.darkGray.
An alternative to RGB is the HSB color system. In the HSB system, a color is
specified by three numbers called the hue, the saturation, and the brightness. The hue
is the basic color, ranging from red through orange through all the other colors of the
rainbow. The brightness is pretty much what it sounds like. A fully saturated color is a
pure color tone. Decreasing the saturation is like mixing white or gray paint into the
pure color. In Java, the hue, saturation and brightness are always specified by values
of type float in the range from 0.0F to 1.0F. The Color class has a static member
function named getHSBColor for creating HSB colors. To create the color with HSB
values given by h, s, and b, you can say:
myColor = Color.getHSBColor(h,s,b);
For example, you could make a random color that is as bright and as saturated as
possible with
myColor = Color.getHSBColor( (float)Math.random(), 1.0F, 1.0F );
The type cast is necessary because the value returned by Math.random() is of type
double, and Color.getHSBColor() requires values of type float. (By the way, you
might ask why RGB colors are created using a constructor while HSB colors are
created using a static member function. The problem is that we would need two
different constructors, both of them with three parameters of type float. Unfortunately,
this is impossible. You can only have two constructors if the number of parameters or
the parameter types differ.)
The RGB system and the HSB system are just different ways of describing the same
set of colors. It is possible to translate between one system and the other. The best
way to understand the color systems is to experiment with them. In the following
applet, you can use the scroll bars to control the RGB and HSB values of a color. A
sample of the color is shown on the right side of the applet. Computer monitors differ
as to the number of different colors they can display, so you might not get to see the
full range of colors in this applet.
One of the instance variables in a Graphics object is the current drawing color, which
is used for all drawing of shapes and text. If g is a graphics context, you can change
the current drawing color for g using the method g.setColor(c), where c is a Color.
For example, if you want to draw in green, you would just say
g.setColor(Color.green) before doing the drawing. The graphics context continues to
use the color until you explicitly change it with another setColor() command. If you
want to know what the current drawing color is, you can call the function
g.getColor(), which returns an object of type Color. This can be useful if you want to
change to another drawing color temporarily and then restore the previous drawing
color.
Every component has an associated foreground color and background color.
Generally, the component is filled with the background color before anything else is
drawn (although some components are "transparent," meaning that the background
color is ignored). When a new graphics context is created for a component, the current
drawing color is set to the foreground color. Note that the foreground color and
background color are properties of the component, not of a graphics context.
The foreground and background colors can be set by instance methods
setForeground(c) and setBackground(c), which are defined in the Component class
and therefore are available for use with any component.
Fonts
A font represents a particular size and style of text. The same character will appear
different in different fonts. In Java, a font is characterized by a font name, a style, and
a size. The available font names are system dependent, but you can always use the
following four strings as font names: "Serif", "SansSerif", "Monospaced", and
"Dialog". In the original Java 1.0, the font names were "TimesRoman", "Helvetica",
and "Courier". You can still use the older names if you want. (A "serif" is a little
decoration on a character, such as a short horizontal line at the bottom of the letter i.
"SansSerif" means "without serifs." "Monospaced" means that all the characters in the
font have the same width. The "Dialog" font is the one that is typically used in dialog
boxes.)
The style of a font is specified using named constants that are defined in the Font
class. You can specify the style as one of the four values:
Font.PLAIN,
Font.ITALIC,
Font.BOLD, or
Font.BOLD + Font.ITALIC.
The size of a font is an integer. Size typically ranges from about 10 to 36, although
larger sizes can also be used. The size of a font is usually about equal to the height of
the largest characters in the font, in pixels, but this is not a definite rule. The size of
the default font is 12.
Java uses the class named java.awt.Font for representing fonts. You can construct a
new font by specifying its font name, style, and size in a constructor:
Font plainFont = new Font("Serif", Font.PLAIN, 12);
Font bigBoldFont = new Font("SansSerif", Font.BOLD, 24);
Every graphics context has a current font, which is used for drawing text. You can
change the current font with the setFont() method. For example, if g is a graphics
context and bigBoldFont is a font, then the command g.setFont(bigBoldFont) will set
the current font of g to bigBoldFont. You can find out the current font of g by calling
the method g.getFont(), which returns an object of type Font.
Every component has an associated font. It can be set with the instance method
setFont(font), which is defined in the Component class. When a graphics context is
created for drawing on a component, the graphic context's current font is set equal to
the font of the component.
Shapes
The Graphics class includes a large number of instance methods for drawing various
shapes, such as lines, rectangles, and ovals. The shapes are specified using the (x,y)
coordinate system described above. They are drawn in the current drawing color of
the graphics context. The current drawing color is set to the foreground color of the
component when the graphics context is created, but it can be changed at any time
using the setColor() method.
Here is a list of some of the most important drawing methods. With all these
commands, any drawing that is done outside the boundaries of the component is
ignored. Note that all these methods are in the Graphics class, so they all must be
called through an object of type Graphics.
drawString(String str, int x, int y) -- Draws the text given by the string str. The string
is drawn using the current color and font of the graphics context. x specifies the
position of the left end of the string. y is the y-coordinate of the baseline of the string.
The baseline is a horizontal line on which the characters rest. Some parts of the
characters, such as the tail on a y or g, extend below the baseline.
drawLine(int x1, int y1, int x2, int y2) -- Draws a line from the point (x1,y1) to the
point (x2,y2). The line is drawn as if with a pen that hangs one pixel to the right and
one pixel down from the (x,y) point where the pen is located. For example, if g refers
to an object of type Graphics, then the command g.drawLine(x,y,x,y), which
corresponds to putting the pen down at a point, draws the single pixel located at the
point (x,y).
drawRect(int x, int y, int width, int height) -- Draws the outline of a rectangle. The
upper left corner is at (x,y), and the width and height of the rectangle are as specified.
If width equals height, then the rectangle is a square. If the width or the height is
negative, then nothing is drawn. The rectangle is drawn with the same pen that is used
for drawLine(). This means that the actual width of the rectangle as drawn is width+1,
and similarly for the height. There is an extra pixel along the right edge and the
bottom edge. For example, if you want to draw a rectangle around the edges of the
component, you can say "g.drawRect(0, 0, getSize().width-1, getSize().height-1);",
where g is a graphics context for the component.
drawOval(int x, int y, int width, int height) -- Draws the outline of an oval. The oval is
one that just fits inside the rectangle specified by x, y, width, and height. If width
equals height, the oval is a circle.
drawRoundRect(int x, int y, int width, int height, int xdiam, int ydiam) -- Draws the
outline of a rectangle with rounded corners. The basic rectangle is specified by x, y,
width, and height, but the corners are rounded. The degree of rounding is given by
xdiam and ydiam. The corners are arcs of an ellipse with horizontal diameter xdiam
and vertical diameter ydiam. A typical value for xdiam and ydiam is 16. But the value
used should really depend on how big the rectangle is.
draw3DRect(int x, int y, int width, int height, boolean raised) -- Draws the outline of a
rectangle that is supposed to have a three-dimensional effect, as if it is raised from the
screen or pushed into the screen. The basic rectangle is specified by x, y, width, and
height. The raised parameter tells whether the rectangle seems to be raised from the
screen or pushed into it. The 3D effect is achieved by using brighter and darker
versions of the drawing color for different edges of the rectangle. The documentation
recommends setting the drawing color equal to the background color before using this
method. The effect won't work well for some colors.
drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) -- Draws part
of the oval that just fits inside the rectangle specified by x, y, width, and height. The
part drawn is an arc that extends arcAngle degrees from a starting angle at startAngle
degrees. Angles are measured with 0 degrees at the 3 o'clock position (the positive
direction of the horizontal axis). Positive angles are measured counterclockwise from
zero, and negative angles are measured clockwise. To get an arc of a circle, make sure
that width is equal to height.
fillRect(int x, int y, int width, int height) -- Draws a filled-in rectangle. This fills in the
interior of the rectangle that would be drawn by drawRect(x,y,width,height). The extra
pixel along the bottom and right edges is not included. The width and height
parameters give the exact width and height of the rectangle. For example, if you
wanted to fill in the entire component, you could say "g.fillRect(0, 0, getSize().width,
getSize().height);"
fillOval(int x, int y, int width, int height) -- Draws a filled-in oval.
fillRoundRect(int x, int y, int width, int height, int xdiam, int ydiam) -- Draws a filled-
in rounded rectangle.
fill3DRect(int x, int y, int width, int height, boolean raised) -- Draws a filled-in three-
dimensional rectangle.
fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) -- Draw a filled-
in arc. This looks like a wedge of pie, whose crust is the arc that would be drawn by
the drawArc method.
Let's use some of the material covered in this section to write a JApplet. Since we will
be drawing on the applet, we will need to create a drawing surface. The drawing
surface will be a JComponent belonging to a subclass of the JPanel class. We will
define this class as a nested class inside the main applet class. . All the drawing is
done in the paintComponent() method of the drawing surface class. I will use nested
classes consistently to define drawing surfaces, although it is perfectly legal to use an
independent class instead of a nested class to define the drawing surface. A nested
class can be either static or non-static. In general, a non-static class must be used if it
needs access to instance variables or instance methods that are defined in the main
class. This will be the case in most of my examples.
The applet will draw multiple copies of a message on a black background. Each copy
of the message is in a random color. Five different fonts are used, with different sizes
and styles. The displayed message is the string "Java!", but a different message can be
specified in an applet param. (Applet params were discussed at the end of the
previous section.) The applet works OK no matter what size is specified for the applet
in the <applet> tag. Here's the applet:
The applet does have a problem. When the drawing surface's paintComponent()
method is called, it chooses random colors, fonts, and locations for the messages. The
information about which colors, fonts, and locations are used is not stored anywhere.
The next time paintComponent() is called, it will make different random choices and
will draw a different picture. For this particular applet, the problem only really
appears when the applet is partially covered and then uncovered. Only the part that
was covered will be redrawn, and in the part that's not redrawn, the old picture will
remain. Try it. You'll see partial messages, cut off by the dividing line between the
new picture and the old. (Actually, in some browsers, the entire applet might be
repainted, even if only part of it was covered.) A better approach would be to compute
the contents of the picture elsewhere, outside the paintComponent() method.
Information about the picture should be stored in instance variables, and the
paintComponent() method should use that information to draw the picture. If
paintComponent() is called twice, it should draw the same picture twice, unless the
data has changed in the meantime. Unfortunately, to store the data for the picture in
this applet, we would need to use either arrays, which will not be covered until
Chapter 8, or off-screen images, which will not be covered until Section 7.1. Other
applets in this chapter will suffer from the same problem.
The source for the applet is shown below. I use an instance variable called message to
hold the message that the applet will display. There are five instance variables of type
Font that represent different sizes and styles of text. These variables are initialized in
the applet's init() method and are used in the drawing surface's paintComponent()
method. I also use the init() method to create the drawing surface, add it to the applet,
and set its background color to black.
The paintComponent() method for the drawing surface simply draws 25 copies of the
message. For each copy, it chooses one of the five fonts at random, and it calls
g.setFont() to select that font for drawing the text. It creates a random HSB color and
uses g.setColor() to select that color for drawing. It then chooses random (x,y)
coordinates for the location of the message. The x coordinate gives the horizontal
position of the left end of the string. The formula used for the x coordinate, "-50 +
(int)(Math.random()*(width+40)" gives a random integer in the range from -50 to
width-10. This makes it possible for the string to extend beyond the left edge or the
right edge of the applet. Similarly, the formula for y allows the string to extend
beyond the top and bottom of the applet.
The drawing surface class, which is named Display, defines the paintComponent()
method that draws all the strings that appear in the applet. The drawing surface is
created in the applet's init() method as an object of type Display. This object is set to
be the "content pane" of the applet. A JApplet's content pane fills the entire applet,
except for an optional menu bar. An applet comes with a default content pane, and
you can add components to that content pane. However, any JComponent can be a
content pane, and in a case like this where a single component fills the applet, it
makes sense to replace the content pane with the setContentPane() method.
The paintComponent() method in the Display class begins with a call to
super.paintComponent(g). The special variable super was discussed in Section 5.5.
The command super.paintComponent(g) simply calls the paintComponent() method
that is defined in the superclass, JPanel. The effect of this is to fill the component with
its background color. Most paintComponent() methods begin with a call to
super.paintComponent(g), but this is not necessary if the drawing commands in the
method cover the background of the component completely.
Here is the complete source code for the RandomStrings applet:
/* This applet displays 25 copies of a message. The color and
position of each message is selected at random. The font
of each message is randomly chosen from among five possible
fonts. The messages are displayed on a black background.
import java.awt.*;
import javax.swing.*;
message = getParameter("message");
if (message == null)
message = "Java!";
// Draw one string. First, set the font to be one of the five
// available fonts, at random.
int x,y;
x = -50 + (int)(Math.random()*(width+40));
y = (int)(Math.random()*(height+20));
g.drawString(message,x,y);
} // end for
} // end paintComponent()
Mouse Events
For an event to have any effect, a program must detect the event and react to it. In
order to detect an event, the program must "listen" for it. Listening for events is
something that is done by an object called an event listener. An event listener object
must contain instance methods for handling the events for which it listens. For
example, if an object is to serve as a listener for events of type MouseEvent, then it
must contain the following method (among several others):
public void mousePressed(MouseEvent evt) { . . . }
The body of the method defines how the object responds when it is notified that a
mouse button has been pressed. The parameter, evt, contains information about the
event. This information can be used by the listener object to determine its response.
The methods that are required in a mouse event listener are specified in an interface
named MouseListener. To be used as a listener for mouse events, an object must
implement this MouseListener interface. Java interfaces were covered in Section 5.6.
(To review briefly: An interface in Java is just a list of instance methods. A class can
"implement" an interface by doing two things. First, the class must be declared to
implement the interface, as in "class MyListener implements MouseListener" or
"class RandomStrings extends JApplet implements MouseListener". Second, the class
must include a definition for each instance method specified in the interface. An
interface can be used as the type for a variable or formal parameter. We say that an
object implements the MouseListener interface if it belongs to a class that implements
the MouseListener interface. Note that it is not enough for the object to include the
specified methods. It must also belong to a class that is specifically declared to
implement the interface.)
Every event in Java is associated with a GUI component. For example, when the user
presses a button on the mouse, the associated component is the one that the user
clicked on. Before a listener object can "hear" events associated with a given
component, the listener object must be registered with the component. If a
MouseListener object, mListener, needs to hear mouse events associated with a
component object, comp, the listener must be registered with the component by
calling "comp.addMouseListener(mListener);". The addMouseListener() method is an
instance method in the class, Component, and so can be used with any GUI
component object. In our first few examples, we will listen for events on a JPanel that
is being used as the drawing surface of a JApplet.
The event classes, such as MouseEvent, and the listener interfaces, such as
MouseListener, are defined in the package java.awt.event. This means that if you
want to work with events, you should include the line "import java.awt.event.*;" at
the beginning of your source code file.
Admittedly, there is a large number of details to tend to when you want to use events.
To summarize, you must
Put the import specification "import java.awt.event.*;" at the beginning of your source
code;
Declare that some class implements the appropriate listener interface, such as
MouseListener;
Provide definitions in that class for the subroutines from the interface;
Register the listener object with the component that will generate the events by calling
a method such as addMouseListener() in the component.
Any object can act as an event listener, provided that it implements the appropriate
interface. A component can listen for the events that it itself generates. An applet can
listen for events from components that are contained in the applet. A special class can
be created just for the purpose of defining a listening object. Many people consider it
to be good form to use anonymous nested classes to define listening objects. (See
Section 5.6 for information on anonymous nested classes.) You will see all of these
patterns in examples in this textbook.
For this version of the applet, we need to make four changes in the source code. First,
add the line "import java.awt.event.*;" before the class definition. Second, declare
that some class implements the MouseListener interface. If we want to use the applet
itself as the listener, we would do this by saying:
class RandomStrings extends JApplet implements MouseListener { ...
Third, define the five methods of the MouseListener interface. Only mousePressed
will do anything. We want to repaint the drawing surface of the applet when the user
clicks the mouse. The drawing surface is represented in this applet by an instance
variable named drawingSurface, so the mousePressed() just needs to call
drawingSurface.repaint() to force the drawing surface to be redrawn. The other mouse
listener methods are empty. The following methods are added to the applet class
definition:
public void mousePressed(MouseEvent evt) {
// When user presses the mouse, tell the system to
// call the drawing surface's paintComponent() method.
drawingSurface.repaint();
}
Often, when a mouse event occurs, you want to know the location of the mouse
cursor. This information is available from the parameter to the event-handling
method, evt. This parameter is an object of type MouseEvent, and it contains instance
methods that return information about the event. To find out the coordinates of the
mouse cursor, call evt.getX() and evt.getY(). These methods return integers which
give the x and y coordinates where the mouse cursor was positioned. The coordinates
are expressed in the coordinate system of the component that generated the event,
where the top left corner of the component is (0,0).
The user can hold down certain modifier keys while using the mouse. The possible
modifier keys include: the Shift key, the Control key, the ALT key (called the Option
key on the Macintosh), and the Meta key (called the Command or Apple key on the
Macintosh and with no equivalent in Windows). You might want to respond to a
mouse event differently when the user is holding down a modifier key. The boolean-
valued instance methods evt.isShiftDown(), evt.isControlDown(), evt.isAltDown(),
and evt.isMetaDown() can be called to test whether the modifier keys are pressed.
You might also want to have different responses depending on whether the user
presses the left mouse button, the middle mouse button, or the right mouse button.
Now, not every mouse has a middle button and a right button, so Java handles the
information in a peculiar way. It treats pressing the right button as equivalent to
holding down the Meta key while pressing the left mouse button. That is, if the right
button is pressed, then the instance method evt.isMetaDown() will return true (even if
the Meta key is not pressed). Similarly, pressing the middle mouse button is
equivalent to holding down the ALT key. In practice, what this really means is that
pressing the right mouse button under Windows is equivalent to holding down the
Command key while pressing the mouse button on Macintosh. A program tests for
either of these by calling evt.isMetaDown().
As an example, consider the following applet. Click on the applet with the left mouse
button to place a red rectangle on the applet. Click with the right mouse button (or
hold down the Command key and click on a Macintosh) to place a blue oval on the
applet. Hold down the Shift key and click to clear the applet.
This applet is a JApplet which uses a nested class named Display to define its drawing
surface. There are many ways to write this applet, but I decided in this case to let the
drawing surface object listen for mouse events on itself. The main applet class does
nothing but set up the drawing surface.
In order to respond to mouse clicks, the Display class implements the MouseListener
interface, and the constructor for the display class includes the command
"addMouseListener(this)". Since this command is in a method in the Display class,
the addMouseListener() method in the display object is being called, and "this" also
refers to the display object. That is, the display object will send any mouse events that
it generates to itself.
The source code for this applet is shown below. You can see how the instance
methods in the MouseEvent object are used. You can also check for the Four Steps of
Event Handling ("import java.awt.event.*", "implements MouseListener",
"addMouseListener", and the event-handling methods).
The Display class in this example violates the rule that all drawing should be done in
a paintComponent() method. The rectangles and ovals are drawn directly in the
mousePressed() routine. To make this possible, I need to obtain a graphics context by
saying "g = getGraphics()". (After using g for drawing, I call g.dispose() to inform the
operating system that I will no longer be using g for drawing. It is a good idea to do
this to free the system resources that are used by the graphics context.) I do not advise
doing this type of direct drawing if it can be avoided, but you can see that it does
work in this case.
By the way, this applet still has the problem that it does not save information about
what has been drawn on the applet. So if the applet is covered up and uncovered, the
contents of the applet are erased.
Here is the source code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
if ( evt.isShiftDown() ) {
// The user was holding down the Shift key. Just
// repaint the panel. Since this class does not
// define a paintComponent() method, the method
// from the superclass, JPanel, is called. That
// method simply fills the panel with its background
// color, which is black. This has the effect of
// erasing the contents of the applet.
repaint();
return;
}
if ( evt.isMetaDown() ) {
// User right-clicked at the point (x,y).
// Draw a blue oval centered at the point (x,y).
// (A black outline around the oval will make it
// more distinct when ovals and rects overlap.)
g.setColor(Color.blue);
g.fillOval( x - 30, y - 15, 60, 30 );
g.setColor(Color.black);
g.drawOval( x - 30, y - 15, 60, 30 );
}
else {
// User left-clicked (or middle-clicked) at (x,y).
// Draw a red rectangle centered at (x,y).
g.setColor(Color.red);
g.fillRect( x - 30, y - 15, 60, 30 );
g.setColor(Color.black);
g.drawRect( x - 30, y - 15, 60, 30 );
}
} // end mousePressed();
You'll find the complete source code for this applet in the file SimplePaint.java. I will
discuss a few aspects of it here, but I encourage you to read it carefully in its entirety.
There are lots of informative comments in the source code. (This is actually an old-
style non-Swing Applet which uses a paint() method to draw on the applet instead of a
paintComponet() method to draw on a drawing surface.)
The applet class for this example is designed to work for any reasonable applet size,
that is, unless the applet is too small. This means that coordinates are computed in
terms of the actual width and height of the applet. (The width and height are obtained
by calling getSize().width and getSize().height.) This makes things quite a bit harder
than they would be if we assumed some particular fixed size for the applet. Let's look
at some of these computations in detail. For example, the command used to fill in the
large white drawing area is
g.fillRect(3, 3, width - 59, height - 6);
There is a 3-pixel border along each edge, so the height of the drawing area is 6 less
than the height of the applet. As for the width: The colored rectangles are 50 pixels
wide. There is a 3-pixel border on each edge of the applet. And there is a 3-pixel
divider between the drawing area and the colored rectangles. All that adds up to make
59 pixels that are not included in the width of the drawing area, so the width of the
drawing area is 59 less than the width of the applet.
The white square labeled "CLEAR" occupies a 50-by-50 pixel region beneath the
colored rectangles. Allowing for this square, we can figure out how much vertical
space is available for the seven colored rectangles, and then divide that space by 7 to
get the vertical space available for each rectangle. This quantity is represented by a
variable, colorSpace. Out of this space, 3 pixels are used as spacing between the
rectangles, so the height of each rectangle is colorSpace - 3. The top of the N-th
rectangle is located (N*colorSpace + 3) pixels down from the top of the applet,
assuming that we start counting at zero. This is because there are N rectangles above
the N-th rectangle, each of which uses colorSpace pixels. The extra 3 is for the border
at the top of the applet. After all that, we can write down the command for drawing
the N-th rectangle:
g.fillRect(width - 53, N*colorSpace + 3, 50, colorSpace - 3);
That was not easy! But it shows the kind of careful thinking and precision graphics
that are sometimes necessary to get good results.
The mouse in this applet is used to do three different things: Select a color, clear the
drawing, and draw a curve. Only the third of these involves dragging, so not every
mouse click will start a dragging operation. The mousePressed routine has to look at
the (x,y) coordinates where the mouse was clicked and decide how to respond. If the
user clicked on the CLEAR rectangle, the drawing area is cleared by calling repaint().
If the user clicked somewhere in the strip of colored rectangles, the selected color is
changed. This involves computing which color the user clicked on, which is done by
dividing the y coordinate by colorSpace. Finally, if the user clicked on the drawing
area, a drag operation is initiated. A boolean variable, dragging, is set to true so that
the mouseDragged and mouseReleased methods will know that a curve is being
drawn. The code for this follows the general form given above. The actual drawing of
the curve is done in the mouseDragged method, which draws a line from the previous
location of the mouse to its current location. Some effort is required to make sure that
the line does not extend beyond the white drawing area of the applet. This is not
automatic, since as far as the computer is concerned, the border and the color bar are
part of the drawing surface. If the user drags the mouse outside the drawing area while
drawing a line, the mouseDragged routine changes the x and y coordinates to make
them lie within the drawing area.
super.init();
Keyboard Events
IN JAVA, EVENTS are associated with GUI components. When the user presses a
button on the mouse, the event that is generated is associated with the component that
contains the mouse cursor. What about keyboard events? When the user presses a key,
what component is associated with the key event that is generated?
A GUI uses the idea of input focus to determine the component associated with
keyboard events. At any given time, exactly one interface element on the screen has
the input focus, and that is where all keyboard events are directed. If the interface
element happens to be a Java component, then the information about the keyboard
event becomes a Java object of type KeyEvent, and it is delivered to any listener
objects that are listening for KeyEvents associated with that component. The necessity
of managing input focus adds an extra twist to working with keyboard events.
It's a good idea to give the user some visual feedback about which component has the
input focus. For example, if the component is the typing area of a word-processor, the
feedback is usually in the form of a blinking text cursor. Another common visual clue
is to draw a brightly colored border around the edge of a component when it has the
input focus, as I do in the sample applet later on this page.
A component that wants to have the input focus can call the method requestFocus(),
which is defined in the Component class. Calling this method does not absolutely
guarantee that the component will actually get the input focus. Several components
might request the focus; only one will get it. This method should only be used in
certain circumstances in any case, since it can be a rude surprise to the user to have
the focus suddenly pulled away from a component that the user is working with. In a
typical user interface, the user can choose to give the focus to a component by
clicking on that component with the mouse. And pressing the tab key will often move
the focus from one component to another.
Some components do not automatically receive the input focus when the user clicks
on them. To solve this problem, a program has to register a mouse listener with the
component to detect user clicks. In response to a user click, the mousePressed()
method should call requestFocus() for the component. This is true, in particular, for
the components that are used as drawing surfaces in the examples in this chapter.
These components are defined as subclasses of JPanel, and JPanel objects do not
receive the input focus automatically. If you want to be able to use the keyboard to
interact with a JPanel named drawingSurface, you have to register a listener to listen
for mouse events on the drawingSurface and call drawingSurface.requestFocus() in
the mousePressed() method of the listener object.
Here is a sample applet that processes keyboard events. If the applet has the input
focus, the arrow keys can be used to move the colored square. Furthermore, pressing
the 'R', 'G', 'B', or 'K' key will set the color of the square to red, green, blue, or black.
When the applet has the input focus, the border of the applet is a bright cyan (blue-
green) color. When the applet does not have the focus, the border is gray, and a
message, "Click to activate," is displayed. When the user clicks on an unfocused
applet, it requests the input focus. (In some browsers, you also have to leave the
mouse positioned inside the applet, in order for it to have the input focus.) The
complete source code for this applet is in the file KeyboardAndFocusDemo.java. I
will discuss some aspects of it below. After reading this section, you should be able to
understand the source code in its entirety.
In Java, keyboard event objects belong to a class called KeyEvent. An object that
needs to listen for KeyEvents must implement the interface named KeyListener.
Furthermore, the object must be registered with a component by calling the
component's addKeyListener() method. The registration is done with the command
"component.addKeyListener(listener);" where listener is the object that is to listen for
key events, and component is the object that will generate the key events (when it has
the input focus). It is possible for component and listener to be the same object. All
this is, of course, directly analogous to what you learned about mouse events in the
previous section. The KeyListener interface defines the following methods, which
must be included in any class that implements KeyListener:
public void keyPressed(KeyEvent evt);
public void keyReleased(KeyEvent evt);
public void keyTyped(KeyEvent evt);
Java makes a careful distinction between the keys that you press and the characters
that you type. There are lots of keys on a keyboard: letter keys, number keys, modifier
keys such as Control and Shift, arrow keys, page up and page down keys, keypad
keys, function keys. In many cases, pressing a key does not type a character. On the
other hand, typing a character sometimes involves pressing several keys. For example,
to type an uppercase 'A', you have to press the Shift key and then press the A key
before releasing the Shift key. On my Macintosh computer, I can type an accented e,
é, by holding down the Option key, pressing the E key, releasing the Option key, and
pressing E again. Only one character was typed, but I had to perform three key-
presses and I had to release a key at the right time. In Java, there are three types of
KeyEvent. The types correspond to pressing a key, releasing a key, and typing a
character. The keyPressed method is called when the user presses a key, the
keyReleased method is called when the user releases a key, and the keyTyped method
is called when the user types a character. Note that one user action, such as pressing
the E key, can be responsible for two events, a keyPressed event and a keyTyped
event. Typing an upper case 'A' could generate two keyPressed, two keyReleased, and
one keyTyped event.
Usually, it is better to think in terms of two separate streams of events, one consisting
of keyPressed and keyReleased events and the other consisting of keyTyped events.
For some applications, you want to monitor the first stream; for other applications,
you want to monitor the second one. Of course, the information in the keyTyped
stream could be extracted from the keyPressed/keyReleased stream, but it would be
difficult (and also system-dependent to some extent). Some user actions, such as
pressing the Shift key, can only be detected as keyPressed events. I have a solitaire
game on my computer that hilites every card that can be moved, when I hold down
the Shift key. You could do something like that in Java by hiliting the cards when the
Shift key is pressed and removing the hilite when the Shift key is released.
There is one more complication. Usually, when you hold down a key on the keyboard,
that key will auto-repeat. This means that it will generate multiple keyPressed events,
as long as it is held down. It can also generate multiple keyTyped events. For the most
part, this will not affect your programming, but you should not expect every
keyPressed event to have a corresponding keyReleased event.
Every key on the keyboard has an integer code number. (Actually, this is only true for
keys that Java knows about. Many keyboards have extra keys that can't be used with
Java.) When the keyPressed or keyReleased method is called, the parameter, evt,
contains the code of the key that was pressed or released. The code can be obtained by
calling the function evt.getKeyCode(). Rather than asking you to memorize a table of
code numbers (which can be different for different platforms in any case), Java
provides a named constant for each key. These constants are defined in the KeyEvent
class. For example the constant for the shift key is KeyEvent.VK_SHIFT. If you want
to test whether the key that the user pressed is the Shift key, you could say "if
(evt.getKeyCode() == KeyEvent.VK_SHIFT)". The key codes for the four arrow keys
are KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT, KeyEvent.VK_UP, and
KeyEvent.VK_DOWN. Other keys have similar codes. (The "VK" stands for "Virtual
Keyboard". In reality, different keyboards use different key codes, but Java translates
the actual codes from the keyboard into its own "virtual" codes. Your program only
sees these virtual key codes, so it will work with various keyboards on various
platforms without modification.)
In the case of a keyTyped event, you want to know which character was typed. This
information can be obtained from the parameter, evt, in the keyTyped method by
calling the function evt.getKeyChar(). This function returns a value of type char
representing the character that was typed.
In the KeyboardAndFocusDemo applet, shown above, I use the keyPressed routine to
respond when the user presses one of the arrow keys. The applet includes instance
variables, squareLeft and squareTop that give the position of the upper left corner of
the square. When the user presses one of the arrow keys, the keyPressed routine
modifies the appropriate instance variable and calls canvas.repaint() to redraw the
whole applet. ("canvas" is the name I use for the drawing surface component in this
applet.) Note that the values of squareLeft and squareRight are restricted so that the
square never moves outside the white area of the applet:
public void keyPressed(KeyEvent evt) {
// Called when the user has pressed a key, which can be
// a special key such as an arrow key. If the key pressed
// was one of the arrow keys, move the square (but make sure
// that it doesn't move off the edge, allowing for a
// 3-pixel border all around the applet). SQUARE_SIZE is
// a named constant that specifies the size of the square.
// squareLeft and squareRight give the position of the
// top-left corner of the square.
} // end keyPressed()
Color changes -- which happen when the user types the characters 'R', 'G', 'B', and 'K',
or the lower case equivalents -- are handled in the keyTyped method. I won't include it
here, since it is so similar to the keyPressed method. Finally, to complete the
KeyListener interface, the keyReleased method must be defined. In the sample applet,
the body of this method is empty since the applet does nothing to respond to
keyReleased events.
Focus Events
If a component is to change its appearance when it has the input focus, it needs some
way to know when it has the focus. In Java, objects are notified about changes of
input focus by events of type FocusEvent. An object that wants to be notified of
changes in focus can implement the FocusListener interface. This interface declares
two methods:
public void focusGained(FocusEvent evt);
public void focusLost(FocusEvent evt);
Furthermore, the addFocusListener() method must be used to set up a listener for the
focus events. When a component gets the input focus, it calls the focusGained()
method of any object that has been registered with that component as a FocusListener.
When it loses the focus, it calls the listener's focusLost() method. Often, it is the
component itself that listens for focus events.
In my sample applet, there is a boolean-valued instance variable named focussed. This
variable is true when the applet has the input focus and is false when the applet does
not have focus. The applet implements the FocusListener interface and listens for
focus events from the canvas. The paintComponent() method of the canvas looks at
the value of focussed to decide what color the border should be. The value of focussed
is set in the focusGained() and focusLost() methods. These methods call
canvas.repaint() so that the drawing surface will be redrawn with the correct border
color. The method definitions are very simple:
public void focusGained(FocusEvent evt) {
// The canvas now has the input focus.
focussed = true;
canvas.repaint(); // redraw with cyan border
}
public void focusLost(FocusEvent evt) {
// The canvas has now lost the input focus.
focussed = false;
canvas.repaint(); // redraw with gray border
}
The other aspect of handling focus is to make sure that the canvas gets the focus when
the user clicks on it. To do this, the applet implements the MouseListener interface
and listens for mouse events on the canvas. It defines a mousePressed routine that
asks that the input focus be given to the canvas:
public void mousePressed(MouseEvent evt) {
canvas.requestFocus();
}
The other four methods of the mouseListener interface are defined to be empty. Note
that the applet implements three listener interfaces, so the class definition begins:
public class KeyboardAndFocusDemo extends JApplet
implements KeyListener, FocusListener, MouseListener
The applet's init() method registers the applet to listen for all three types of events. To
do this, the init() method includes the lines
canvas.addFocusListener(this);
canvas.addKeyListener(this);
canvas.addMouseListener(this);
There are, of course, other ways to organize this applet. It would be possible, for
example, to use the canvas object instead of the applet object to listen for events. Or
anonymous classes could be used to define separate listening objects.
State Machines
The information stored in an object's instance variables is said to represent the state of
that object. When one of the object's methods is called, the action taken by the object
can depend on its state. (Or, in the terminology we have been using, the definition of
the method can look at the instance variables to decide what to do.) Furthermore, the
state can change. (That is, the definition of the method can assign new values to the
instance variables.) In computer science, there is the idea of a state machine, which is
just something that has a state and can change state in response to events or inputs.
The response of a state machine to an event or input depends on what state it's in. An
object is a kind of state machine. Sometimes, this point of view can be very useful in
designing classes.
The state machine point of view can be especially useful in the type of event-oriented
programming that is required by graphical user interfaces. When designing an applet,
you can ask yourself: What information about state do I need to keep track of? What
events can change the state of the applet? How will my response to a given event
depend on the current state? Should the appearance of the applet be changed to reflect
a change in state? How should the paintComponent() method take the state into
account? All this is an alternative to the top-down, step-wise-refinement style of
program design, which does not apply to the overall design of an event-oriented
program.
In the KeyboardAndFocusDemo applet, shown above, the state of the applet is
recorded in the instance variables focussed, squareLeft, and squareTop. These state
variables are used in the paintComponent() method to decide how to draw the applet.
They are set in the various event-handling methods.
In the rest of this section, we'll look at another example, where the state of the applet
plays an even bigger role. In this example, the user plays a simple arcade-style game
by pressing the arrow keys. The example is based on one of my frameworks, called
KeyboardAnimationApplet2. (See Section 3.7 for a discussion of frameworks and a
sample framework that supports animation.) The game is written as an extension of
the KeyboardAnimationApplet2 class. It includes a method, drawFrame(), that draws
one frame in the animation. It also defines keyPressed to respond when the user
presses the arrow keys. The source code for the game is in the file
SubKillerGame.java. You can also look at the source code in
KeyboardAnimationApplet2.java, but it uses some advanced techniques that I haven't
covered yet.
You have to click on the game to activate it. The applet shows a black "submarine"
moving back and forth erratically near the bottom. Near the top, there is a blue "boat".
You can move this boat back and forth by pressing the left and right arrow keys.
Attached to the boat is a red "depth charge." You can drop the depth charge by hitting
the down arrow key. The objective is to blow up the submarine by hitting it with the
depth charge. If the depth charge falls off the bottom of the screen, you get a new one.
If the sub explodes, a new sub is created and you get a new depth charge. Try it! Make
sure to hit the sub at least once, so you can see the explosion.
Let's think about how this applet can be programmed. What constitutes the "state" of
the applet? That is, what things change from time to time and affect the appearance or
behavior of the applet? Of course, the state includes the positions of the boat,
submarine, and depth charge, so I need instance variables to store the positions.
Anything else, possibly less obvious? Well, sometimes the depth charge is falling, and
sometimes it's not. That is a difference in state. Since there are two possibilities, I
represent this aspect of the state with a boolean variable, bombIsFalling. Sometimes
the submarine is moving left and sometimes it is moving right. The difference is
represented by another boolean variable, subIsMovingLeft. Sometimes, the sub is
exploding. This is also part of the state, but representing it requires a little more
thought. While an explosion is in progress, the sub looks different in each frame, since
the size of the explosion increases. Also, I need to know when the explosion is over so
that I can go back to drawing the sub as usual. So, I use a variable,
explosionFrameNumber, of type int, which tells how many frames have been drawn
since the explosion started. I represent the fact that no explosion is happening by
setting the value of explosionFrameNumber to zero. Alternatively, I could have used
another boolean variable to keep track of whether or not an explosion is in progress.
How and when do the values of these instance variables change? Some of them can
change when the user presses certain keys. In the program, this is checked in the
keyPressed() method. If the user presses the left or right arrow key, the position of the
boat is changed. If the user presses the down arrow key, the depth charge changes
from not-falling to falling. This is coded as follows:
public void keyPressed(KeyEvent evt) {
if (code == KeyEvent.VK_LEFT) {
// Move the boat left.
boatCenterX -= 15;
}
else if (code == KeyEvent.VK_RIGHT) {
// Move the boat right.
boatCenterX += 15;
}
else if (code == KeyEvent.VK_DOWN) {
// Start the bomb falling, if it is not already falling.
if ( bombIsFalling == false )
bombIsFalling = true;
}
} // end keyPressed()
Note that it's not necessary to call repaint() when the state changes, since this applet is
an animation that is constantly being redrawn anyway. Any changes in the state will
become visible to the user as soon as the next frame is drawn. At some point in the
program, I have to make sure that the user does not move the boat off the screen. I
could have done this in keyPressed(), but I choose to check for this in another routine,
just before drawing the boat.
Other aspects of the state are changed in the drawFrame() routine. From the point of
view of programming, this method is handling an event ("Hey, it's time to draw the
next frame!"). It just happens to be an event that is generated by the
KeyboardAnimationApplet2 framework rather than by the user. In my applet, the
drawFrame() routine calls three other methods that I wrote to organize the process of
computing and drawing a new frame: doBombFrame(), doBoatFrame(), and
doSubFrame().
Consider doBombFrame(). This routine draws the depth charge. What happens in this
routine depends on the current state, and the routine can make changes to the state
when it is executed. The state of the bomb can be falling or not-falling, as recorded in
the variable, bombIsFalling. If bombIsFalling is false, then the bomb is simply drawn
at the bottom of the boat. If bombIsFalling is true, the vertical coordinate of the bomb
has to be increased by some amount to make the bomb move down a bit from one
frame to the next. Several other things can also happen. If the bomb has fallen off the
bottom of the applet -- something that we can test by looking at its vertical coordinate
-- then bombIsFalling becomes false. This puts the bomb back at the boat in the next
frame. Also, the bomb might hit the sub. This can be tested by comparing the
locations of the bomb and the sub. If the bomb hits the sub, then the state changes in
two ways: the bomb is no longer falling and the sub is exploding. These state changes
are implemented by setting bombIsFalling to false and explosionFrameNumber to 1.
Most interesting is the submarine. What happens with the submarine depends on
whether it is exploding or not. If it is (that is, if explosionFrameNumber > 0), then
yellow and red ovals are drawn at the sub's position. The sizes of these ovals depend
on the value of explosionFrameNumber, so they grow with each frame of the
explosion. After the ovals are drawn, the value of explosionFrameNumber is
incremented. If its value has reached 14, it is reset to 0. This reflects a change of state:
The sub is no longer exploding. It's important for you to understand what is happening
here. There is no loop in the program to draw the stages of the explosion. Each frame
is a new event and is drawn separately, based on values stored in instance variables.
The state can change, which will make the next frame look different from the current
one.
In a frame where the sub is not exploding, it moves left or right. This is accomplished
by adding or subtracting a small amount to the horizontal coordinate of the sub.
Whether it moves left or right is determined by the value of the variable,
subIsMovingLeft. It's interesting to consider how and when this variable changes
value. If the sub reaches the left edge of the applet, subIsMovingLeft is set to false to
make the sub start moving right. Similarly, if the sub reaches the right edge. But the
sub can also reverse direction at random times. The way this is implemented is that in
each frame, there is a small chance that the sub will reverse direction. This is done
with the statement
if ( Math.random() < 0.04 )
sumIsMovingLeft = !subIsMovingLeft;
Since Math.random() is between 0 and 1, the condition "Math.random() < 0.04" has a
4 in 100, or 1 in 25, chance of being true. In those frames where this conditions
happens to evaluate to true, the sub reverses direction. (The value of the expression "!
subIsMovingLeft" is false when subIsMovingLeft is true, and it is true when
subIsMovingLeft is false, so it effectively reverses the value of subIsMovingLeft.)
While it's not very sophisticated as arcade games go, the SubKillerGame applet does
use some interesting programming. And it nicely illustrates how to apply state-
machine thinking in event-oriented programming.
Another aspect of GUI programming is laying out components on the screen, that is,
deciding where they are drawn and how big they are. You have probably noticed that
computing coordinates can be a difficult problem, especially if you don't assume a
fixed size for the applet. Java has a solution for this, as well.
Components are the visible objects that make up a GUI. Some components are
containers, which can hold other components. An applet's content pane is an example
of a container. The standard class JPanel, which we have only used as a drawing
surface up till now, is another example of a container. Because a JPanel object is a
container, it can hold other components. So JPanels are dual purpose: You can draw
on them, and you can add other components to them. Because a JPanel is itself a
component, you can add a JPanel to an applet's content pane or even to another
JPanel. This makes complex nesting of components possible. JPanels can be used to
organize complicated user interfaces.
The components in a container must be "laid out," which means setting their sizes and
positions. It's possible to program the layout yourself, but ordinarily layout is done by
a layout manager. A layout manager is an object associated with a container that
implements some policy for laying out the components in that container. Different
types of layout manager implement different policies.
In this section, we'll look at a few examples of using components and layout
managers, leaving the details until Section 7.2 and Section 7.3. The applets that we
look at in this section have a large drawing area with a row of controls below it.
Our first example is rather simple. It's another "Hello World" applet, in which the
color of the message can be changed by clicking one of the buttons at the bottom of
the applet:
In the previous JApplets that we've looked at, the entire applet was filled with a
JPanel that served as a drawing surface. In this example, there are two JPanels: the
large black area at the top that displays the message and the smaller area at the bottom
that holds the three buttons.
Let's first consider the panel that contains the buttons. This panel is created in the
applet's init() method as a variable named buttonBar, of type JPanel:
JPanel buttonBar = new JPanel();
When a panel is to be used as a drawing surface, it is necessary to create a subclass of
the JPanel class and include a paintComponent() method to do the drawing. However,
when a JPanel is just being used as a container, there is no need to create a subclass. A
standard JPanel is already capable of holding components of any type.
Once the panel has been created, the three buttons are created and are added to the
panel. A button is just an object belonging to the class javax.swing.JButton. When a
button is created, the text that will be shown on the button is provided as a parameter
to the constructor. The first button in the panel is created with the command:
JButton redButton = new JButton("Red");
This button is added to the buttonBar panel with the command:
buttonBar.add(redButton);
Every JPanel comes automatically with a layout manager. This default layout manager
will simply line up the components that are added to it in a row. That's exactly the
behavior we want here, so there is nothing more to do. If we wanted a different kind
of layout, it's possible to change the panel's layout manager.
One more step is required to make the button useful: an object must be registered with
the button to listen for ActionEvents. The button will generate an ActionEvent when
the user clicks on it. ActionEvents are similar to MouseEvents or KeyEvents. To use
them, a class should import java.awt.event.*. The object that is to do the listening
must implement an interface named ActionListener. This interface requires a
definition for the method "public void actionPerformed(ActionEvent evt);". Finally,
the listener must be registered with the button by calling the button's
addActionListener() method. In this case, the applet itself will act as listener, and the
registration is done with the command:
redButton.addActionListener(this);
After doing the same three commands for each of the other two buttons -- and setting
the background color for the sake of aesthetics -- the buttonBar panel is ready to use.
It just has to be added to the applet.
As we have seen, components are not added directly to an applet. Instead, they are
added to the applet's content pane, which is itself a container. The content pane comes
with a default layout manager that is capable of displaying up to five components.
Four of these components are placed along the edges of the applet, in the so-called
"North", "South", "East", and "West" positions. A component in the "Center" position
fills in all the remaining space. This type of layout is called a BorderLayout. In our
example, the button bar occupies the "South" position and the drawing area fills the
"Center" position. When you add a component to a BorderLayout, you have to specify
its position using a constant such as BorderLayout.SOUTH or
BorderLayout.CENTER. In this example, buttonBar is added to the applet with the
command:
getContentPane().add(buttonBar, BorderLayout.SOUTH);
The display area of the applet is a drawing surface like those we have seen in other
examples. A nested class named Display is created as a subclass of JPanel, and the
display area is created as an object belonging to that class. The applet class has an
instance variable named display of type Display to represent the drawing surface. The
display object is simply created and added to the applet with the commands:
display = new Display();
getContentPane().add(display, BorderLayout.CENTER);
Putting this all together, the complete init() method for the applet becomes:
public void init() {
getContentPane().add(display, BorderLayout.CENTER);
// Adds the display panel to the CENTER position of the
// JApplet's content pane.
buttonBar.setBackground(Color.gray);
// Change the background color of the button panel
// so that the buttons will stand out better.
JButton redButton = new JButton("Red");
// Create a new button. "Red" is the text
// displayed on the button.
redButton.addActionListener(this);
// Set up the button 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,
// so action events from the button will be handled by
// calling the actionPerformed() method in this class.
buttonBar.add(redButton);
// Add the button to the buttonBar panel.
getContentPane().add(buttonBar, BorderLayout.SOUTH);
// Add button panel to the bottom of the content pane.
} // end init()
Notice that the variables buttonBar, redButton, greenButton, and blueButton are local
to the init() method. This is because once the buttons and panel have been added to
the applet, the variables are no longer needed. The objects continue to exist, since they
have been added to the applet. But they will take care of themselves, and there is no
need to manipulate them elsewhere in the applet. The display variable, on the other
hand, is an instance variable that can be used throughout the applet. This is because
we are not finished with the display object after adding it to the applet. When the user
clicks a button, we have to change the color of the display. We need a way to keep the
variable around so that we can refer to it in the actionPerformed() method. In general,
you don't need an instance variable for every component in an applet -- just for the
components that will be referred to outside the init() method.
The drawing surface in our example is defined by a nested class named Display which
is a subclass of JPanel. The class contains a paintComponent() method that is
responsible for drawing the message "Hello World" on a black background. The
Display class also contains a variable that it uses to remember the current color of the
message and a method that can be called to change the color. This class is more self-
contained than than most of the drawing surface classes that we have looked at, and in
fact it could have been defined as an independent class instead of as a nested class.
Here is the definition of the nested class, Display:
class Display extends JPanel {
// This nested class defines a component that displays
// the string "Hello World". The color and font for
// the string are recorded in the variables colorNum
// and textFont.
Display() {
// Constructor for the Display class. Set the background
// color and assign initial values to the instance
// variables, colorNum and textFont.
setBackground(Color.black);
colorNum = 1; // The color of the message is set to red.
textFont = new Font("Serif",Font.BOLD,36);
// Create a font object representing a big, bold font.
}
The main class has an instance variable named display of type Display. When the user
clicks one of the buttons in the applet, this variable is used to call the setColor()
method in the drawing surface object. This is done in the applet's actionPerformed()
method. This method is called when the user clicks any one of the three buttons, so it
needs some way to tell which button was pressed. This information is provided in the
parameter to the actionPerformed() method. This parameter contains an "action
command," which in the case of a button is just the string that is displayed on the
button:
public void actionPerformed(ActionEvent evt) {
// This routine is called by the system when the user clicks
// on one of the buttons. The response is to set the display's
// color accordingly.
} // end actionPerformed()
We have now looked at all the pieces of the sample applet. You can find the entire
source code in the file HelloWorldJApplet.java.
For a second example, let's look at something a little more interesting. Here's a simple
card game in which you look at a playing card and try to predict whether the next card
will be higher or lower in value. (Aces have the lowest value in this game.) You've
seen a text-oriented version of the same game in Section 5.3. That section also defined
Deck, Hand, and Card classes that are used in this applet. In this GUI version of the
game, you click on a button to make your prediction. If you predict wrong, you lose.
If you make three correct predictions, you win. After completing one game, you can
click the "New Game" button to start a new game. Try it! See what happens if you
click on one of the buttons at a time when it doesn't make sense to do so.
The overall form of this applet is the same as that of the previous example: It has
three buttons in a panel at the bottom of the applet and a large drawing surface that
displays the cards and a message. However, I've organized the code a little differently
in this example. In this case, it's the drawing surface object, rather than the applet, that
listens for events from the buttons, and I've put almost all the programming into the
display surface class. The applet object is only responsible for creating the
components and adding them to the applet. This is done in the following init()
method, which has almost the same form as the init() method in the previous example:
public void init() {
// The init() method lays out the applet. A HighLowCanvas
// occupies the CENTER position of the layout. On the
// bottom is a panel that holds three buttons. The
// HighLowCanvas object listens for ActionEvents from the
// buttons and does all the real work of the program.
} // end init()
As a final example, let's look quickly at an improved paint program, similar to the one
from Section 4. The user can draw on the large white area. In this version, the user
selects the drawing color from the pop-up menu at the bottom-left of the applet. If the
user hits the "Clear" button, the drawing area is filled with the background color. I've
added one feature: If the user hits the "Set Background" button, the background color
of the drawing area is set to the color currently selected in the pop-up menu, and the
drawing area is cleared. This lets you draw in cyan on a magenta background if you
have a mind to.
The drawing area in this applet is a component, belonging to the nested class
SimplePaintCanvas. I wrote this class, as usual, as a sub-class of JPanel and
programmed it to listen for mouse events and to respond by drawing a curve. As in the
HighLowGUI applet, all the action takes place in the nested class. The main applet
class just does the set up. One new feature of interest is the pop-up menu. This
component is an object belonging to the standard class, JComboBox. We'll cover this
component class in Chapter 7.
What you should note about this version of the paint applet is that in many ways, it
was easier to write than the original. There are no computations about where to draw
things and how to decode user mouse clicks. We don't have to worry about the user
drawing outside the drawing area. The graphics context that is used for drawing on
the canvas can only draw on the canvas. If the user tries to extend a curve outside the
canvas, the part that lies outside the canvas is automatically ignored. We don't have to
worry about giving the user visual feedback about which color is selected. That is
handled by the text displayed on the pop-up menu.
CHAPTER EIGHT
IN THIS SECTION, we'll look at some additional aspects of graphics in Java. Most of
the section deals with Images, which are pictures stored in files or in the computer's
memory. But we'll also consider a few other techniques that can be used to draw better
or more efficiently.
Images
To a computer, an image is just a set of numbers. The numbers specify the color of
each pixel in the image. The numbers that represent the image on the computer's
screen are stored in a part of memory called a frame buffer. Many times each second,
the computer's video card reads the data in the frame buffer and colors each pixel on
the screen according to that data. Whenever the computer needs to make some change
to the screen, it writes some new numbers to the frame buffer, and the change appears
on the screen a fraction of a second later, the next time the screen is redrawn by the
video card.
Since it's just a set of numbers, the data for an image doesn't have to be stored in a
frame buffer. It can be stored elsewhere in the computer's memory. It can be stored in
a file on the computer's hard disk. Just like any other data file, an image file can be
downloaded over the Internet. Java includes standard classes and subroutines that can
be used to copy image data from one part of memory to another and to get data from
an image file and use it to display the image on the screen.
The standard class java.awt.Image is used to represent images. A particular object of
type Image contains information about some particular image. There are actually two
kinds of Image objects. One kind represents an image in an image data file. The
second kind represents an image in the computer's memory. Either type of image can
be displayed on the screen. The second kind of Image can also be modified while it is
in memory. We'll look at this second kind of Image below.
Every image is coded as a set of numbers, but there are various ways in which the
coding can be done. For images in files, there are two main coding schemes which are
used in Java and on the Internet. One is used for GIF images, which are usually stored
in files that have names ending in ".gif". The other is used for JPEG images, which
are stored in files that have names ending in ".jpg" or ".jpeg". Both GIF and JPEG
images are compressed. That is, redundancies in the data are exploited to reduce the
number of numbers needed to represent the data. In general, the compression method
used for GIF images works well for line drawings and other images with large patches
of uniform color. JPEG compression generally works well for photographs.
The Applet class defines a method, getImage, that can be used for loading images
stored in GIF and JPEG files. (As we will see later, stand-alone applications use a
different technique for loading image files.) For example, suppose that the image of
an ace of clubs, shown at the right, is contained in a file named "ace.gif". And suppose
that img is a variable of type Image. Then the following command could be used in
the source code of your applet:
img = getImage( getCodeBase(), "ace.gif" );
This would create an Image object to represent the ace. The second parameter is the
name of the file that contains the image. The first parameter specifies the directory
that contains the image file. The value "getCodeBase()" specifies that the image file is
in the code base directory for the applet. Assuming that the applet is in the default
package, as usual, that just means that the image file is in the same directory as the
compiled class file of the applet.
Once you have an object of type Image, however you obtain it, you can draw the
image in any graphics context. Most commonly, this will be done in the
paintComponent() method of a JPanel (or some other JComponent.) If g is the
Graphics object that is provided as a parameter to the paintComponent() method, then
the command:
g.drawImage(img, x, y, this);
will draw the image img in a rectangular area in the component. The parameters x and
y give the position of the upper-left corner of the rectangle in which the image is
displayed, and the rectangle is just large enough to hold the image. The fourth
parameter, this, is the special variable from Section 5.5 that refers to the component
itself. This parameter is there for technical reasons having to do with the funny way
Java treats image files. (Although you don't really need to know this, here is how it
works: When you use getImage() to create an Image object from an image file, the file
is not downloaded immediately. The Image object simply remembers where the file is.
The file will be downloaded the first time you draw the image. However, when the
image needs to be downloaded, the drawImage() method only initiates the
downloading. It doesn't wait for the data to arrive. So, after drawImage() has finished
executing, it's quite possible that the image has not actually been drawn! But then,
when does it get drawn? That's where the fourth parameter to the drawImage()
command comes in. The fourth parameter is something called an ImageObserver.
After the image has been downloaded, the system will inform the ImageObserver that
the image is available, and the ImageObserver will actually draw the image at that
time. For large images, it's even possible that the image will be drawn in several parts
as it is downloaded. Any JComponent object can act as an ImageObserver. If you are
sure that the image that you are drawing has already been downloaded, you can set the
fourth parameter of drawImage() to null.)
There are a few useful variations of the drawImage() command. For example, it is
possible to scale the image as it is drawn to a specified width and height. This is done
with the command
g.drawImage(img, x, y, width, height, this);
The parameters width and height give the size of the rectangle in which the image is
displayed. Another version makes it possible to draw just part of the image. In the
command:
g.drawImage(img, dest_x1, dest_y1, dest_x2, dest_y2,
source_x1, source_y1, source_x2, source_y2, this);
the integers source_x1, source_y1, source_x2, and source_y2 specify the top-left and
bottom-right corners of a rectangular region in the source image. The integers
dest_x1, dest_y1, dest_x2, and dest_y2 specify the corners of a region in the
destination graphics context. The specified rectangle in the image is drawn, with
scaling if necessary, to the specified rectangle in the graphics context. For an example
in which this is useful, consider a card game that needs to display 52 different cards.
Dealing with 52 image files can be cumbersome and inefficient, especially for
downloading over the Internet. So, all the cards might be put into a single image:
Now, only one Image object is needed. Drawing one card means drawing a
rectangular region from the image. This technique is used in the following version of
the HighLow card game from Section 6.6:
In this applet, the cards are drawn by the following method. The variable, cardImages,
is a variable of type Image that represents the image of 52 cards that is shown above.
Each card is 40 by 60 pixels. These numbers are used, together with the suit and value
of the card, to compute the corners of the source and destination rectangles for the
drawImage() command:
void drawCard(Graphics g, Card card, int x, int y) {
// Draws a card as a 40 by 60 rectangle with
// upper left corner at (x,y). The card is drawn
// in the graphics context g. If card is null, then
// a face-down card is drawn. The cards are taken
// from an Image object that loads the image from
// the file smallcards.gif.
if (card == null) {
// Draw a face-down card
g.setColor(Color.blue);
g.fillRect(x,y,40,60);
g.setColor(Color.white);
g.drawRect(x+3,y+3,33,53);
g.drawRect(x+4,y+4,31,51);
}
else {
int row = 0; // Which of the four rows contains this card?
switch (card.getSuit()) {
case Card.CLUBS: row = 0; break;
case Card.HEARTS: row = 1; break;
case Card.SPADES: row = 2; break;
case Card.DIAMONDS: row = 3; break;
}
int sx, sy; // Coords of upper left corner in the source image.
sx = 40*(card.getValue() - 1);
sy = 60*row;
g.drawImage(cardImages, x, y, x+40, y+60,
sx, sy, sx+40, sy+60, this);
}
} // end drawCard()
The variable cardImages is defined as an instance variable in the applet, and the
image object is created in the init() method of the applet with the command:
cardImages = getImage( getCodeBase(), "smallcards.gif" );
The complete source code for this applet can be found in HighLowGUI2.java.
Swing's double buffering uses an off-screen image. Sometimes, it's useful to create
your own off-screen images for other purposes. An off-screen Image object can be
created by calling the instance method createImage(). This method is defined in the
Component class, and so can be used just about anywhere in an applet's source code.
The createImage() method takes two parameters to specify the width and height of the
image to be created. For example,
Image offScreenImage = createImage(width, height);
Drawing to an off-screen image is done in the same way as any other drawing in Java,
by using a graphics context. The Image class defines an instance method
getGraphics() that returns a Graphics object that can be used for drawing on the off-
screen image. (This works only for off-screen images. If you try to do this with an
Image from a file, an error will occur.) That is, if offScreenImage is a variable of type
Image that refers to an off-screen image, you can say
Graphics offscreenGraphics = offScreenImage.getGraphics();
Then, any drawing operations performed with the graphics context offscreenGraphics
are applied to the off-screen image. For example,
"offscreenGraphics.drawRect(10,10,50,100);" will draw a 50-by-100-pixel rectangle
on the off-screen image. Once a picture has been drawn on the off-screen image, the
picture can be copied into another graphics context, using the graphics context's
drawImage() method. For example: g.drawImage(offScreenImage,0,0,null). For an
off-screen image, the file parameter to drawImage() can be null. (Since the image is
already in memory, there is no need for an "ImageObserver" to wait for the image to
be loaded from a file.)
Off-screen images can be used to solve one problem that we have seen in many of our
sample applets. In many cases, we have had no convenient way of remembering what
was drawn on an applet, so that we were unable restore the drawing when necessary.
For example, in the paint applet in Section 6.6, the user's sketch will disappear if the
applet is covered up and then uncovered. An off-screen image can be used to solve
this problem. The idea is simple: Keep a copy of the drawing in an off-screen image.
When the component needs to be redrawn, copy the off-screen image onto the screen.
This method is used in the improved paint program at the end of this section.
When used in this way, the off-screen image should always contain a copy of the
picture on the screen. The paintComponent() method copies this off-screen image to
the screen. This will refresh the picture when it is covered and uncovered. The actual
drawing of the picture should take place elsewhere. (Occasionally, it makes sense to
draw some extra stuff on the screen, on top of the image from the off-screen image.
For example, a hilite or a shape that is being dragged might be treated in this way.
These things are not permanently part of the image. The permanent image is safe in
the off-screen image, and it can be used to restore the on-screen image when the hilite
is removed or the shape is dragged to a different location. We will use this technique
in the next example.)
There are two approaches to keeping the image on the screen synchronized with the
image in the off-screen image. In the first approach, in order to change the image, you
make the change to the off-screen image and then call repaint() to copy the modified
image to the screen. This is safe and easy, but not always efficient. The second
approach is to make every change twice, once to the off-screen image and once to the
screen. This keeps the two images the same, but it requires some care to make sure
that exactly the same drawing is done in both (and it violates the rule about doing
drawing operations only inside paintComponent() methods).
When using an off-screen image as a backup for the picture displayed on a
component, the size of the off-screen image should be the same as the size of the
component. This raises the problem of where in the program the image should be
created. If the off-screen image is to fill an entire applet, then the image can be
created in the applet's init() method with the command:
offScreenImage = createImage(getSize().width,getSize().height);
However, components other than applets do not have convenient init() methods for
initialization. They have constructors, but the size of a component is not known when
its constructor is executed, so the above command will not work in a constructor. An
alternative is to create the off-screen image on demand, when it is needed. We can
even allow for changes in size of a component if we make a new off-screen image
whenever the size changes. Here is some sample code that implements this idea. A
method named checkOffScreenImage() will create the off-screen image when
necessary. This method should always be called before using the off-screen image.
For example, it is called in the paintComponent() method before copying the image to
the screen.
void checkOffScreenImage() {
// This method will create the off-screen image if it has not
// already been created or if the component's size has changed.
// It should always be called before using the off-screen
// image in any way.
if (OSI == null || widthOfOSI != getSize().width
|| heightOfOSI != getSize().height) {
// OSI doesn't yet exist, or else it exists but has a
// different size from the component's current size.
// Create a new OSI, and fill it with the component's
// background color.
OSI = null; // If OSI already exists, this frees up the memory.
widthOfOSI = getSize().width;
heightOfOSI = getSize().height;
OSI = createImage(widthOfOSI, heightOfOSI);
Graphics OSGr = OSC.getGraphics();
OSGr.setColor(getBackground());
OSGr.fillRect(0, 0, widthOfOSC, heightOfOSC);
OSGr.dispose(); // Free operating system resources.
}
}
checkOffScreenImage();
g.drawImage(OSI, 0, 0, null); // Copy OSI onto the screen.
Note that the contents of the off-screen image are lost if the size changes. If this is a
problem, you can consider copying the contents of the old off-screen image to the new
one before discarding the old image. You can do this with drawImage(), and you can
even scale the image to fit the new size if you want. However, the results of scaling
are not always attractive.
Here is an applet that demonstrates some of these ideas. Draw red lines by clicking
and dragging on the applet. Draw blue rectangles by right-clicking and dragging. Hold
down the shift key and click to clear the applet. Notice that as you drag the mouse, the
figure that you are drawing stretches between the current mouse position and the point
where you started dragging. This effect is sometimes called a rubber band cursor:
In this applet, a copy of the picture that you've drawn is kept in an off-screen image. If
you cover the applet and uncover it, the picture is restored by copying this backup
image onto the screen. When you drag the mouse, the figure that you are drawing is
not added to the off-screen image. The paintComponent() method simply draws the
new figure on top of the backup image. The backup image is not changed, and as you
move the mouse around, you can see that it is still there, "underneath" the figure you
are sketching. The new figure is only added to the off-screen image when you release
the mouse button. To see how all this works in detail, check the source code,
RubberBand.java.
There is one other point of interest in the above applet. To draw a rectangle in Java,
you need to know the coordinates of the upper left corner, the width, and the height.
However, when a rectangle is drawn in this applet, the available data consists of two
corners of the rectangle: the starting position of the mouse and its current position.
From these two corners, the left edge, the top edge, the width, and the height of the
rectangle have to be computed. This can be done as follows:
void drawRectUsingCorners(Graphics g, int x1, int y1, int x2, int y2) {
// Draw a rectangle with corners at (x1,y1) and (x2,y2).
int x,y; // Coordinates of the top-left corner.
int w,h; // Width and height of rectangle.
if (x1 < x2) { // x1 is the left edge
x = x1;
w = x2 - x1;
}
else { // x2 is the left edge
x = x2;
w = x1 - x2;
}
if (y1 < y2) { // y1 is the top edge
y = y1;
h = y2 - y1;
}
else { // y2 is the top edge
y = y2;
h = y1 - y2;
}
g.drawRect(x, y, w, h); // Draw the rect.
}
The source code for this improved paint applet is in the file SimplePaint3.java. It uses
an off-screen image pretty much in the way described above. The paintComponent()
method copies the off-screen image to the screen, and as the user drags the mouse,
clipping is used to restrict the drawing to the region that actually needs to be changed.
In this applet, curves are handled differently from the other shapes. Suppose that the
user is sketching a curve and that the user moves the mouse from the point
(prevX,prevY) to the point (mouseX,mouseY). The applet responds to this by drawing
a line segment in the off-screen image from (prevX,prevY) to (mouseX,mouseY). To
make this change appear on the screen, a rectangle that contains these two points must
be copied from the off-screen image onto the screen. This is accomplished in the
applet by calling repaint(x,y,w,h) with appropriate values for the parameters.
When the user is sketching one of the other shapes in the applet, the rubber band
cursor technique is used. That is, while the user is dragging the mouse, the shape is
drawn by the paintComponent() method on top of the picture from the off-screen
image. Let's say, for example, that the user is drawing a rectangle. Suppose that the
user starts by pressing the mouse at the point (startX,startY). Consider what happens
later, when the user drags the mouse from the point (prevX,prevY) to the point
(mouseX,mouseY). At the beginning of this motion, a rectangle is shown on the
screen with corners at (startX,startY) and (prevX,prevY). In response to the motion,
this rectangle must be removed and a new one with corners at (startX,startY) and
(mouseX,mouseY) should appear. This can be accomplished by changing the values
of the variables that tell paintComponent() where to draw the rectangle and by calling
repaint(x,y,w,h) twice: once to repaint the area occupied by the old rectangle and once
to repaint the area that will be occupied by the new rectangle. (The system will
actually combine the two operations into a single call to paintComponent().)
This version of "SimplePaint" is not really all that simple. There are a lot of details to
take care of. I urge you to look at the source code to see how it's done.
FontMetrics
In the rest of this section, we turn from Images to look briefly at another aspect of
Java graphics.
Often, when drawing a string, it's important to know how big the image of the string
will be. You need this information if you want to center a string on an applet. Or if
you want to know how much space to leave between two lines of text, when you draw
them one above the other. Or if the user is typing the string and you want to position a
cursor at the end of the string. In Java, questions about the size of a string are
answered by an object belonging to the standard class java.awt.FontMetrics.
There are several lengths associated with any given font. Some of them are shown in
this illustration:
The red lines in the illustration are the baselines of the two lines of text. The
suggested distance between two baselines, for single-spaced text, is known as the
lineheight of the font. The ascent is the distance that tall characters can rise above the
baselines, and the descent is the distance that tails like the one on the letter g can
descend below the baseline. The ascent and descent do not add up to the lineheight,
because there should be some extra space between the tops of characters in one line
and the tails of characters on the line above. The extra space is called leading. All
these quantities can be determined by calling instance methods in a FontMetrics
object. There are also methods for determining the width of a character and the width
of a string.
If F is a font and g is a graphics context, you can get a FontMetrics object for the font
F by calling g.getFontMetrics(F). If fm is a variable that refers to the FontMetrics
object, then the ascent, descent, leading, and lineheight of the font can be obtained by
calling fm.getAscent(), fm.getDescent(), fm.getLeading(), and fm.getHeight(). If ch is
a character, then fm.charWidth(ch) is the width of the character when it is drawn in
that font. If str is a string, then fm.stringWidth(str) is the width of the string. For
example, here is a paintComponent() method that shows the message "Hello World"
in the exact center of the component:
public void paintComponent(Graphics g) {
int width, height; // Width and height of the string.
int x, y; // Starting point of baseline of string.
Font F = g.getFont(); // What font will g draw in?
FontMetrics fm = g.getFontMetrics(F);
width = fm.stringWidth("Hello World");
height = fm.getAscent(); // Note: There are no tails on
// any of the chars in the string!
x = getSize().width / 2 - width / 2; // Go to center and back up
// half the width of the
// string.
y = getSize().height / 2 + height / 2; // Go to center, then move
// down half the height of
// the string.
g.drawString("Hello World", x, y);
FlowLayout
A FlowLayout simply lines up its components without trying to be particularly neat
about it. After laying out as many items as will fit in a row across the container, it will
move on to the next row. The components in a given row can be either left-aligned,
right-aligned, or centered, and there can be horizontal and vertical gaps between
components. If the default constructor, "new FlowLayout()" is used, then the
components on each row will be centered and the horizontal and vertical gaps will be
five pixels. The default layout for a JPanel uses gaps of this size. The constructor
FlowLayout(int align, int hgap, int vgap)
can be used to specify alternative alignment and gaps. The possible values of align are
FlowLayout.LEFT, FlowLayout.RIGHT, and FlowLayout.CENTER. A nifty trick is
to use a very large value of hgap. This forces the FlowLayout to put exactly one
component in each row, since there won't be room on a single row for two
components and the horizontal gap between them. The appropriate add() method for
FlowLayouts has a single parameter of type Component, specifying the component to
be added.
For example, suppose that we wanted an applet to contain one button, located in the
upper right corner of the applet. The default layout manager for an applet's content
pane is a BorderLayout. We need to give the content pane a FlowLayout with right
alignment. This will shove the button to the right edge of the applet. The following
init() method will do this:
public void init() {
getContentPane().setLayout( new FlowLayout(FlowLayout.RIGHT, 5, 5) );
getConetntPane().add( new JButton("Press me!") );
}
Note again that it is the applet's content pane that actually holds components, and it is
the content pane that needs a layout manager. It is an error to try to set a layout
manager for a JApplet itself.
BorderLayout
A BorderLayout places one component in the center of a container. This
central component is surrounded by up to four other components that border
it to the "North", "South", "East", and "West", as shown in the diagram at
the right. Each of the four bordering components is optional. The layout manager first
allocates space to the bordering components. Any space that is left over goes to the
center component.
If a container uses a BorderLayout, then components should be added to the container
using a version of the add() method that has two parameters. The first parameter is the
component that is being added to the container. The second parameter specifies where
the component is to be placed. It must be one of the constants
BorderLayout.CENTER, BorderLayout.NORTH, BorderLayout.SOUTH,
BorderLayout.EAST, or BorderLayout.WEST. If the second parameter is omitted,
then BorderLayout.CENTER is used by default. For example, the following code
creates a panel with drawArea as its center component and with scroll bars to the right
and below:
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
// To use BorderLayout with a JPanel, you have
// to change the panel's layout manager; otherwise,
// a FlowLayout is used. Alternatively, you
// can provide the layout manager as a
// parameter to the constructor:
// panel = new JPanel( new BorderLayout() );
panel.add(drawArea, BorderLayout.CENTER);
// Assume drawArea already exists.
panel.add(hScroll, BorderLayout.SOUTH);
// Assume hScroll is a horizontal scroll bar
// component that already exists.
panel.add(vScroll, BorderLayout.EAST);
// Assume vScroll is a vertical scroll bar
// component that already exists.
Sometimes, you want to leave space between the components in a container. You can
specify horizontal and vertical gaps in the constructor of a BorderLayout object. For
example, if you say
panel.setLayout(new BorderLayout(5,7));
then the layout manager will insert horizontal gaps of 5 pixels between components
and vertical gaps of 7 pixels between components. The horizontal gap is inserted
between the center and west components and between the center and east
components; the vertical gap is inserted between the center and north components and
between the center and south components. (The default layout for a JApplet's content
pane is a BorderLayout with no horizontal or vertical gap.)
GridLayout
A GridLayout lays out components in a grid of equal sized rectangles. The illustration
shows how the components would be arranged in a grid layout with 3 rows and 2
columns. If a container uses a GridLayout, the appropriate add method takes a single
parameter of type Component (for example: add(myButton)). Components are added
to the grid in the order shown; that is, each row is filled from left to right before going
on the next row.
The constructor for a GridLayout with R rows and C columns takes the form "new
GridLayout(R,C)". If you want to leave horizontal gaps of H pixels between columns
and vertical gaps of V pixels between rows, use "new GridLayout(R,C,H,V)" instead.
When you use a GridLayout, it's probably good form to add just enough components
to fill the grid. However, this is not required. In fact, as long as you specify a non-zero
value for the number of rows, then the number of columns is essentially ignored. The
system will use just as many columns as are necessary to hold all the components that
you add to the container. If you want to depend on this behavior, you should probably
specify zero as the number of columns. You can also specify the number of rows as
zero. In that case, you must give a non-zero number of columns. The system will use
the specified number of columns, with just as many rows as necessary to hold the
components that are added to the container.
Horizontal grids, with a single row, and vertical grids, with a single column, are very
common. For example, suppose that button1, button2, and button3 are buttons and
that you'd like to display them in a horizontal row in a panel. If you use a horizontal
grid for the panel, then the buttons will completely fill that panel and will all be the
same size. The panel can be created as follows:
JPanel buttonBar = new JPanel();
buttonBar.setLayout(new GridLayout(1,3));
// (Note: The "3" here is pretty much ignored, and
// you could also say "new GridLayout(1,0)".
// To leave gaps between the buttons, you could use
// "new GridLayout(1,0,5,5)".)
buttonBar.add(button1);
buttonBar.add(button2);
buttonBar.add(button3);
You might find this button bar to be more attractive than the ones in the examples in
the Section 6.6, which used the default FlowLayout layout manager.
GridBagLayout
A GridBagLayout is similar to a GridLayout in that the container is broken down into
rows and columns of rectangles. However, a GridBagLayout is much more
sophisticated because the rows do not all have to be of the same height, the columns
do not all have to be of the same width, and a component in the container can spread
over several rows and several columns. There is a separate class, GridBagConstraints,
that is used to specify the position of a component, the number of rows and columns
that it occupies, and several additional properties of the component.
Using a GridBagLayout is rather complicated, and I have used it on exactly two
occasions in my own Java programming career. I will not explain it here; if you are
interested, you should consult a Java reference.
CardLayout
CardLayouts differ from other layout managers in that in a container that uses a
CardLayout, only one of its components is visible at any given time. Think of the
components as a set of "cards". Only one card is visible at a time, but you can flip
from one card to another. Methods are provided in the CardLayout class for flipping
to the first card, to the last card, and to the next card in the deck. A name can be
specified for each card as it is added to the container, and there is a method in the
CardLayout class for flipping directly to the card with a specified name.
Suppose, for example, that you want to create a JPanel that can show any one of three
JPanels: panel1, panel2, and panel3. Assume that panel1, panel2, and panel3 have
already been created:
cardPanel = new JPanel();
// assume cardPanel is declared as an instance variable
// so that it can be used in other methods
cards = new CardLayout();
// assume cards is declared as an instance variable
// so that it can be used in other methods
cardPanel.setLayout(cards);
cardPanel.add(panel1, "First");
// add panel1 with name "First"
cardPanel.add(panel2, "Second");
// add panel2 with name "Second"
cardPanel.add(panel3, "Third");
// add panel3 with name "Third"
Elsewhere in your program, you could show panel1 by saying
cards.show(cardPanel, "First");
or
cards.first(cardPanel);
Other methods that are available are cards.last(cardPanel), cards.next(cardPanel), and
cards.previous(cardPanel). Note that each of these methods takes the container as a
parameter. To use a CardLayout effectively, you'll need to have instance variables to
record both the layout manager (cards in the example) and the container (cardPanel in
the example). You need both of these objects in order to flip from one card to another.
An Example
To finish this survey of layout managers, here is an applet that demonstrates layout
managers of various types:
The applet itself uses a BorderLayout with vertical gaps of 3 pixels. These gaps show
up in blue. The Center component of the applet is a JPanel, which uses a CardLayout
as its layout manager. The layout contains eight cards. Each card is itself another
panel that contains several buttons. Each card uses a different type of layout manager
(several of which are extremely stupid choices for laying out buttons).
The North component of the applet is a JComboBox, which contains the names of the
eight panels in the card layout. The user can switch among the cards by selecting
items from this menu. The South component of the applet is a JLabel that displays an
appropriate message whenever the user clicks on a button or chooses an item from the
JComboBox.
The source code for this applet is in the file LayoutDemo.java. It consists mainly of a
long init() method that creates all the buttons, panels, and other components and lays
out the applet.
Borders and Insets
Swing makes it very easy to add decorative borders around the edges of a
JComponent. The class javax.swing.BorderFactory contains a large number of static
methods for creating borders. For example, the function
BorderFactory.createLineBorder(Color.black)
returns an object that represents a one-pixel wide black line around the outside of a
component. If comp is a JComponent, a border can be added to comp using its
setBorder() method. For example:
comp.setBorder( BorderFactory.createLineBorder(Color.black) );
When a border has been set for a JComponent, the border is drawn automatically,
without any further effort on the part of the programmer. The border is drawn along
the edges of the component, just inside its boundary. The layout manager of a JPanel
or other container will take the space occupied by the border into account. The
components that are added to the container will be displayed in the area inside the
border. I don't recommend using a border on a JPanel that is being used as a drawing
surface. However, if you do this, you should take the border into account. If you draw
in the area occupied by the border, that part of your drawing will be covered by the
border.
Here are some of the static methods that can be used to create borders:
BorderFactory.createEmptyBorder(top,left,bottom,right) -- leaves an empty border
around the edges of a component. Nothing is drawn in this space, so the background
color will appear in the area occupied by the border. The parameters are integers that
give the width of the border along the top, left, bottom, and right edges of the
component. This is actually very useful when used on a JPanel that contains other
components. It puts some space between the components and the edge of the panel.
BorderFactory.createLineBorder(color,thickness) -- draws a line around all four edges
of a component. The first parameter is of type Color and specifies the color of the
line. The second parameter is an integer that specifies the thickness of the border. If
the second parameter is omitted, a line of thickness 1 is drawn.
BorderFactory.createMatteBorder(top,left,bottom,right,color) -- is similar to
createLineBorder, except that you can specify individual thicknesses for the top, left,
bottom, and right edges of the component.
BorderFactory.createEtchedBorder() -- creates a border that looks like a groove
etched around the boundary of the component. The effect is achieved using lighter
and darker shades of the component's background color, and it does not work well
with every background color.
BorderFactory.createLoweredBevelBorder() -- gives a component a three-dimensional
effect that makes it look like it is lowered into the computer screen. As with an
EtchedBorder, this only works well for certain background colors.
BorderFactory.createRaisedBevelBorder() -- similar to a LoweredBevelBorder, but
the component looks like it is raised above the computer screen.
BorderFactory.createTitledBorder(title) -- creates a border with a title. The title is a
String, which is displayed in the upper left corner of the border.
There are many other methods in the BorderFactory class, most of them providing
variations of the basic border styles given here. The following applet shows six
components with six different border styles. The text in each component is the
command that created the border for that component:
Since a JApplet is not a JComponent, it's not possible to set a Border object for a
JApplet. There is, however, another way to add a border of color around the edges. An
applet can use "insets" to leave space around the edges of the applet where the
background color of the applet will show through. To do this, define the method
public Insets getInsets() in your subclass of JApplet. This method should return an
object of type Insets, which specifies the width of the border along the top, left,
bottom, and right edges of the applet. The system will call your method to determine
how much space to leave. For example, if your subclass of JApplet includes the
method definition:
public Insets getInsets() {
return new Insets(5,5,5,5);
}
then there will be a 5-pixel-wide border around the edges of the applet where the
background color of the applet will show. To specify the color, you can set the applet's
background color in its init() method. Note that Insets should not be used with
JComponents. For a JComponent, you can use BorderFactory.createEmptyBorder() to
accomplish the same thing.
The LayoutDemo applet uses Insets to leave a 3-pixel border around the outside of the
applet, where the blue background color of the applet shows through. This is different
from the 3-pixel blue gap between the components in the applet's content pane, where
the blue gap is a feature of the content pane's BorderLayout. It's the background color
of the content pane, not of the applet, that shows though the spaces in the
BorderLayout. To set up the colors, the init() method of the applet sets the background
color for both the applet and for its content pane to blue. Since the default layout used
for a content pane has no vertical gap, the init() method also installs a different layout
manager for the content pane. All this is done with the following commands:
setBackground(Color.blue);
getContentPane().setBackground(Color.blue);
getContentPane().setLayout(new BorderLayout(3,3));
THIS SECTION DISCUSSES some of the GUI interface elements that are
represented by subclasses of JComponent. The treatment here is brief and covers only
the basic uses of each component type. After you become familiar with the basics, you
might want to consult a Java reference for more details. I will give some examples of
programming with components in the next section.
The exact appearance of a Swing component and the way that the user interacts with
the component are not fixed. They depend on the look-and-feel of the user interface.
While Swing supports a default look-and-feel, which is probably the one that you will
see most often, it is possible to change the look-and-feel. For example, a Windows
look-and-feel could be used to make a Java program that is running on a Windows
computer look more like a standard Windows program. While this can improve the
user's experience, it means that some of the details that I discuss will have to be
qualified with the phrase "depending on the look-and-feel."
The JComponent class itself defines many useful methods that can be used with
components of any type. We've already used some of these in examples. Let comp be
a variable that refers to any JComponent. Then the following methods are available
(among many others):
comp.getSize() is a function that returns an object belonging to the class Dimension.
This object contains two instance variables, comp.getSize().width and
comp.getSize().height, that give the current size of the component. You can also get
the height and width more directly by calling comp.getHeight() and comp.getWidth().
One warning: When a component is first created, its size is zero. The size will be set
later, probably by a layout manager. A common mistake is to check the size of a
component before that size has been set, such as in a constructor.
comp.setEnabled(true) and comp.setEnabled(false) can be used to enable and disable
the component. When a component is disabled, its appearance changes, and the user
cannot do anything with it. There is a boolean-valued function, comp.getEnabled()
that you can call to discover whether the component is enabled.
comp.setVisible(true) and comp.setVisible(false) can be called to hide or show the
component.
comp.setBackground(color) and comp.setForeground(color) set the background and
foreground colors for the component. If no colors are set for a component, the colors
are determined by the look-and-feel.
comp.setOpaque(true) tells the component that the area occupied by the component
should be filled with the component's background color before the content of the
component is painted. In the default look-and-feel, only JLabels are non-opaque. A
non-opaque, or "transparent", component ignores its background color and simply
paints its content over the content of its container. This usually means that it inherits
the background color from its container.
comp.setFont(font) sets the font that is used for text displayed on the component. The
parameter is an object of type java.awt.Font.
comp.setToolTipText(string) sets the specified string as a "tool tip" for the component.
The tool tip is displayed if mouse cursor is in the component and the mouse is not
moved for a few seconds. The tool tip should give some information about the
meaning of the component or how to use it.
comp.setCursor(cursor) sets the cursor image that represents the mouse position when
the mouse cursor is inside this component. The parameter is an object belonging to
the class java.awt.Cursor. Generally, this parameter takes the form
Cursor.getPredefinedCursor(id) where id is one of several constants defined in the
Cursor class. The most useful values are probably Cursor.HAND_CURSOR,
Cursor.CROSSHAIR_CURSOR, Cursor.WAIT_CURSOR, and
Cursor.DEFAULT_CURSOR. For example, if you would like the cursor to appear as
a little pointing hand when the mouse is in the component comp, you can use:
comp.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
comp.setPreferredSize(size) sets the size at which the component should be displayed,
if possible. The parameter is of type Dimension, and a call to this method usually
looks something like "setPreferredSize(new Dimension(100,50))". The preferred size
is used as a hint by layout managers, but will not be respected in all cases. In a
BorderLayout, for example, the preferred size of the Center component is irrelevant,
but the preferred sizes of the North, South, East, and West components are used by the
layout manager to decide how much space to allow for those components. Standard
components generally compute a correct preferred size automatically, but it can be
useful to set it in some cases. For example, if you use a JPanel as a drawing surface, it
might be a good idea to set a preferred size for it.
comp.getParent() is a function that returns a value of type java.awt.Container. The
return value is the container that directly contains the component, if any. For a top-
level component such as a JApplet, the value will be null.
comp.getLocation() is a function that returns the location of the top-left corner of the
component. The location is specified in the coordinate system of the component's
parent. The returned value is an object of type Point. An object of type Point contains
two instance variables, x and y.
For the rest of this section, we'll look at subclasses of JComponent that represent
common GUI components. Remember that using any component is a multi-step
process. The component object must be created with a constructor. It must be added to
a container. In many cases, a listener must be registered to respond to events from the
component. And in some cases, a reference to the component must be saved in an
instance variable so that the component can be manipulated by the program after it
has been created.
The source code for the applet is in the file RadioButtonDemo.java. Just as for
checkboxes, it is not always necessary to register listeners for radio buttons. In many
cases, you can simply check the state of each button when you need to know it, using
the isSelected() method.
In this applet, the second slider is decorated with ticks, and the third one is decorated
with labels. It's possible for a single slider to have both types of decorations.
The most commonly used constructor for JSliders specifies the start and end of the
range of values for the slider and its initial value when it first appears on the screen:
JSlider(int minimum, int maximum, int value)
If the parameters are omitted, the values 0, 100, and 50 are used. By default, a slider is
horizontal, but you can make it vertical by calling its method
setOrientation(JSlider.VERTICAL). The current value of a JSlider can be read at any
time with its getValue() method. This method returns a value of type int. If you want
to change the value, you can do so with the method setValue(n), which takes a
parameter of type int.
If you want to respond immediately when the user changes the value of a slider, you
can register a listener with the slider. JSliders, unlike other components we have seen,
do not generate ActionEvents. Instead, they generate events of type ChangeEvent.
ChangeEvent and related classes are defined in the package javax.swing.event rather
than java.awt.event, so if you want to use ChangeEvents, you should import
javax.swing.event.* at the beginning of your program. You must also define some
object to implement the ChangeListener interface, and you must register the change
listener with the slider by calling its addChangeListener() method. A ChangeListener
must provide a definition for the method:
void stateChanged(ChangeEvent evt)
This method will be called whenever the value of the slider changes. (Note that it will
be called when you change the value with the setValue() method, as well as when the
user changes the value.) In the stateChanged() method, you can call evt.getSource() to
find out which object generated the event.
Using tick marks on a slider is a two-step process: Specify the interval between the
tick marks, and tell the slider that the tick marks should be displayed. There are
actually two types of tick marks, "major" tick marks and "minor" tick marks. You can
have one or the other or both. Major tick marks are a bit longer than minor tick marks.
The method setMinorTickSpacing(i) indicates that there should be a minor tick mark
every i units along the slider. The parameter is an integer. (The spacing is in terms of
values on the slider, not pixels.) For the major tick marks, there is a similar command,
setMajorTickSpacing(i). Calling these methods is not enough to make the tick marks
appear. You also have to call setPaintTicks(true). For example, the second slider in the
above applet was created and configured using the commands:
slider2 = new JSlider();
slider2.addChangeListener(this);
slider2.setMajorTickSpacing(25);
slider2.setMinorTickSpacing(5);
slider2.setPaintTicks(true);
getContentPane().add(slider2);
Labels on a slider are handled similarly. You have to specify the labels and tell the
slider to paint them. Specifying labels is a tricky business, but the JSlider class has a
method to simplify it. Create a set of labels and add them to a slider named sldr with
the command:
sldr.setLabelTable( sldr.createStandardLabels(i) );
where i is an integer giving the spacing between the labels. To arrange for the labels to
be displayed, call setPaintLabels(true). For example, the third slider in the above
applet was created and configured with the commands:
slider3 = new JSlider(2000,2100,2002);
slider3.addChangeListener(this);
slider3.setLabelTable(slider3.createStandardLabels(50));
slider3.setPaintLabels(true);
getContentPane().add(slider3);
The position of the tab specifies the currently selected value. The user can move the
tab by dragging it or by clicking on any of the other parts of the scroll bar. The size of
the tab tells what portion of a scrolling region is currently visible. It is actually the
position of the bottom or left edge of the tab that represents the currently selected
value.
A scroll bar has four associated integer values:
min, which specifies the starting point of the range of values represented by the
scrollbar, corresponding to the left or bottom edge of the bar
max, which specifies the end point of the range of values, corresponding to the right
or top edge of the bar
visible, which specifies the size of the tab
value, which gives the currently selected value, somewhere in the range between min
and (max - visible).
Note that the largest possible value is (max - visible), not max, since the value
represents the position of the left or bottom edge of the tab. The largest possible value
allows space for the tab, whose size is given by visible.
The four values can be specified when the scroll bar is created. The constructor takes
the form
JScrollBar(int orientation, int value, int visible, int min, int max);
The orientation, which specifies whether the scroll bar is horizontal or vertical, must
be one of the constants JScrollBar.HORIZONTAL or JScrollBar.VERTICAL. The
value must be between min and (max - visible). You can leave out all the int
parameters to get a scroll bar with default values. You can set the value of the scroll
bar at any time with the method setValue(int). Similarly, the other values can be set
with setMinimum(int), setMaximum(int), and setVisibleAmount(int). You can also set
all four values at once by calling:
void setValues(int value, int visible, int min, int max);
Methods getValue(), getVisibleAmount(), getMinimum() and getMaximum() are
provided for reading the current values of each of these parameters.
The user can drag the tab or click elsewhere on the scroll bar. How far does the tab
move when the user clicks on the up-arrow or down-arrow or in the page-up or page-
down region of a scrollbar? The amount by which the value changes when the user
clicks on the up-arrow or down-arrow is called the unit increment. The amount by
which it changes when the user clicks in the page-up or page-down region is called
the block increment. By default, both of these values are 1. They can be set using the
methods:
void setUnitIncrement(int unitIncrement);
void setBlockIncrement(int blockIncrement);
Let's look at an example. Suppose that you want to use a very large drawing area,
which is too large to fit on the screen. You might decide to display only part of the
JPanel and to provide scroll bars to allow the user to scroll through the entire panel.
Let's say that the actual panel is 1000 by 1000 pixels, and that you will show a 200-
by-200 region of the panel at any one time. Let's look at how you would set up the
vertical scroll bar. The horizontal bar would be essentially the same.
The visible of the scroll bar would be 200, since that is how many pixels would
actually be displayed. The value of the scroll bar would represent the vertical
coordinate of the pixel that is at the top of the display. (Whenever the value changes,
you have to redraw the display.) The min would be 0, and the max would be 1000.
The range of values that can be set on the scroll bar is from 0 to 800. (Remember that
the largest possible value is the maximum minus the visible amount.)
The page increment for the scroll bar could be set to some value a little less than 200,
say 190 or 175. Then, when the user clicks in the page-up or page-down region, the
display will scroll by an amount almost equal to its size. The line increment could be
left at 1, but it is likely that this would be too small since it represents a scrolling
increment of just one pixel. A line increment of 15 would be better, since then the
display would scroll by a more reasonable 15 pixels when the user clicks the up-arrow
or down-arrow. (Of course, all these values would have to be reset if the display area
is resized.)
A scroll bar generates an event of type AdjustmentEvent whenever the user changes
the value of the scroll bar. The associated AdjustmentListener interface defines one
method, "adjustmentValueChanged(AdjustmentEvent evt)", which is called by the
scroll bar to notify the listener that the value on the scroll bar has been changed. This
method should repaint the display or make whatever other change is appropriate for
the new value. The method evt.getValue() returns the current value on the scroll bar. If
you are using more than one scroll bar and need to determine which scroll bar
generated the event, use evt.getSource() to determine the source of the event.
Scrolling is complicated. Fortunately, Swing provides a class that can take care of
many of the details. A JScrollPane is is a component that provides scrolling for
another component. That component is specified as a parameter to the constructor:
JScrollPane(Component content)
The content component appears in the center of the scroll pane. If it is too large to be
displayed entirely, then horizontal and/or vertical scroll bars will appear that can be
used for scrolling the content. You have to add the scroll pane to a container to make
both the scroll pane and its content appear on the screen. This makes scrolling very
easy, and makes it unusual to work with scroll bars directly.
A JScrollPane can use any component as content, but several Swing components,
including the JTextArea that will be discussed below, are designed specifically to
work with JScrollPane.
THE TWO PREVIOUS SECTIONS described some raw materials that are available
in the form of layout managers and standard GUI components. This section presents
some programming examples that make use of those raw materials.
When designing an applet such as this one, you should start by asking yourself
questions like: How will the user interact with the applet? What components will I
need in order to support that interaction? What events can be generated by user
actions, and what will the applet do in response? What data will I have to keep in
instance variables to keep track of the state of the applet? What information do I want
to display to the user? Once you have answered these questions, you can decide how
to lay out the components. You might want to draw the layout on paper. At that point,
you are ready to begin writing the program.
In the simple calculator applet, the user types in two numbers and clicks a button. The
computer responds by doing a computation with the user's numbers and displaying the
result. The program uses two JTextField components to get the user's input. The
JTextFields do a lot of work on their own. They respond to mouse, focus, and
keyboard events. They show blinking cursors when they are active. They collect and
display the characters that the user types. The program only has to do three things
with each JTextField: Create it, add it to the applet, and get the text that the user has
input by calling its getText() method. The first two things are done in the applet's
init() method. The third -- getting the user's input from the input boxes -- is done in an
actionPerformed() method, which responds when the user clicks on one of the
buttons. When a component is created in one method and used in another, as the input
boxes are in this case, we need an instance variable to refer to it. In this case, I use
two instance variables, xInput and yInput, of type JTextField to refer to the input
boxes. The JLabel that is used to display the result is treated similarly: A JLabel is
created and added to the applet in the init() method. When an answer is computed in
the actionPerformed() method, the JLabel's setText() method is used to display the
answer in the label. I use an instance variable named answer, of type JLabel, to refer
to the label.
The applet also has four JButtons and two more JLabels. (The two extra labels display
the strings "x =" and "y =".) I use local variables rather than instance variables for
these components because I don't need to refer to them outside the init() method.
The applet as a whole uses a GridLayout with four rows and one column. The bottom
row is occupied by the JLabel, answer. The other three rows each contain several
components. Each of the first three rows is filled by a JPanel, which has its own
layout manager and contains several components. The row that contains the four
buttons is a JPanel which uses a GridLayout with one row and four columns. The
JPanels that contain the input boxes use BorderLayouts. The input box occupies the
Center position of the BorderLayout, with a JLabel on the West. (This example shows
that BorderLayouts are more versatile than it might appear at first.) All the work of
setting up the applet is done in its init() method:
public void init() {
setBackground(Color.gray);
content.setBackground(Color.gray);
/* Create the input boxes, and make sure that their background
color is white. (They are likely to be white by default.) */
/* Create panels to hold the input boxes and labels "x =" and
"y = ". By using a BorderLayout with the JTextField in the
Center position, the JTextField will take up all the space
left after the label is given its preferred size. */
JPanel xPanel = new JPanel();
xPanel.setLayout(new BorderLayout());
xPanel.add( new Label(" x = "), BorderLayout.WEST );
xPanel.add(xInput, BorderLayout.CENTER);
content.setLayout(new GridLayout(4,1,2,2));
content.add(xPanel);
content.add(yPanel);
content.add(buttonPanel);
content.add(answer);
xInput.requestFocus();
} // end init()
The action of the applet takes place in the actionPerformed() method. The algorithm
for this method is simple:
get the number from the input box xInput
get the number from the input box yInput
get the action command (the name of the button)
if the command is "+"
add the numbers and display the result in the answer label
else if the command is "-"
subtract the numbers and display the result in the label
else if the command is "*"
multiply the numbers and display the result in the label
else if the command is "/"
divide the numbers and display the result in the label
There is only one problem with this. When we call xInput.getText() and
yInput.getText() to get the contents of the input boxes, the results are Strings, not
numbers. We need a method to convert a string such as "42.17" into the number that it
represents. The standard class Double contains a static method,
Double.parseDouble(String) for doing just that. So we can get the first number
entered by the user with the commands: f
String xStr = xInput.getText();
x = Double.parseDouble(xStr);
where x is a variable of type double. Similarly, if we wanted to get an integer value
from the string, xStr, we could use a static method in the standard Integer class:
x = Integer.parseInt(xStr). This makes it easy to get numerical values from a
JTextField, but one problem remains: We can't be sure that the user has entered a
string that represents a legal real number. We could ignore this problem and assume
that a user who doesn't enter a valid input shouldn't expect to get an answer. However,
a more friendly program would notice the error and display an error message to the
user. This requires using a "try...catch" statement, which is not covered until Chapter 9
of this book. My program does in fact use a try...catch statement to handle errors, so
you can get a preview of how it works. Here is the actionPerformed() method that
responds when the user clicks on one of the buttons in the applet:
public void actionPerformed(ActionEvent evt) {
// When the user clicks a button, get the numbers
// from the input boxes and perform the operation
// indicated by the button. Put the result in
// the answer label. If an error occurs, an
// error message is put in the label.
try {
String xStr = xInput.getText();
x = Double.parseDouble(xStr);
}
catch (NumberFormatException e) {
// The string xStr is not a legal number.
answer.setText("Illegal data for x.");
return;
}
try {
String yStr = yInput.getText();
y = Double.parseDouble(yStr);
}
catch (NumberFormatException e) {
answer.setText("Illegal data for y.");
return;
}
String op = evt.getActionCommand();
if (op.equals("+"))
answer.setText( "x + y = " + (x+y) );
else if (op.equals("-"))
answer.setText( "x - y = " + (x-y) );
else if (op.equals("*"))
answer.setText( "x * y = " + (x*y) );
else if (op.equals("/")) {
if (y == 0)
answer.setText("Can't divide by zero!");
else
answer.setText( "x / y = " + (x/y) );
}
} // end actionPerformed()
The complete source code for the applet can be found in the file
SimpleCalculator.java. (It contains very little in addition to the two methods shown
above.)
The layout manager for the applet is a GridLayout with one row and three columns.
The first column contains a JPanel, which in turn contains the JSliders. This panel
uses another GridLayout, with three rows and one column. The second column, which
contains the JLabels, is similar. The third column contains the colored rectangle. The
component in this column is a JPanel which contains no components. The displayed
color is the background color of the JPanel. When the user changes the color, the
background color of the panel is changed and the panel is repainted to show the new
color. This is one of the few cases where an object of type JPanel is used without
either making a subclass or adding components to it.
When the user changes the value on a JSlider, an event of type ChangeEvent is
generated. In order to respond to such events, the applet implements the
ChangeListener interface, which specifies the method "public void
stateChanged(ChangeEvent evt)". The applet registers itself to listen for change
events from each slider. The applet has instance variables to refer to the sliders, the
labels, and the color patch. Note that since the ChangeEvent and ChangeListener
classes are defined in the package javax.swing.event, the command
"import javax.swing.event.*;" is added to the beginning of the program.
Let's look at the code from the init() method for setting up one of the JSliders,
redSlider:
redSlider = new JSlider(0, 255, 0);
redSlider.addChangeListener(this);
The first line constructs a horizontal slider whose value can range from 0 to 255.
These are the possible values of the red level in a color. The initial value of the slider,
which is specified by the third parameter to the constructor, is 0. The second line
registers the applet ("this") to listen for change events from the slider. The other two
sliders are initialized in a similar way.
In the stateChanged() method, the applet must respond to the fact that the user has
changed the value of one of the sliders. The response is to read the values of all the
sliders, set the labels to display those values, and change the color displayed on the
color patch. (This is slightly lazy programming, since only one of the labels actually
needs to be changed. However, there is no rule against setting the text of a label to the
same text that it is already displaying.)
public void stateChanged(ChangeEvent evt) {
// This is called when the user has changed the value on
// one of the sliders. All the sliders are checked,
// the labels are set to display the correct values, and
// the color patch is set to correspond to the new color.
int r = redSlider.getValue();
int g = greenSlider.getValue();
int b = blueSlider.getValue();
redLabel.setText(" R = " + r);
greenLabel.setText(" G = " + g);
blueLabel.setText(" B = " + b);
colorPatch.setBackground(new Color(r,g,b));
} // end stateChanged()
The complete source code can be found in the file RGBColorChooser.java.
public StopWatch() {
// Constructor.
super(" Click to start timer. ", JLabel.CENTER);
addMouseListener(this);
}
} // end StopWatch
Don't forget that since StopWatch is a subclass of JLabel, you can do anything with a
StopWatch that you can do with a JLabel. You can add it to a container. You can set its
font, foreground color, and background color. You can set the text that it displays
(although this would interfere with its stopwatch function). You can even add a
Border if you want.
Let's look at one more example of defining a custom component. Suppose that -- for
no good reason whatsoever -- I want a component that acts like a JLabel except that it
displays its text in mirror-reversed form. Since no standard component does anything
like this, the MirrorLabel class is defined as a subclass of JPanel. It has a constructor
that specifies the text to be displayed and a setText() method that changes the
displayed text. The paintComponent() method draws the text mirror-reversed, in the
center of the component. This uses techniques discussed in Section 1. Information
from a FontMetrics object is used to center the text in the component. The reversal is
achieved by using an off-screen image. The text is drawn to the off-screen image, in
the usual way. Then the image is copied to the screen with the following command,
where OSC is the variable that refers to the off-screen image:
g.drawImage(OSC, widthOfOSC, 0, 0, heightOfOSC,
0, 0, widthOfOSC, heightOfOSC, this);
This is the version of drawImage() that specifies corners of destination and source
rectangles. The corner (0,0) in OSC is matched to the corner (widthOfOSC,0) on the
screen, while (widthOfOSC,heightOfOSC) is matched to (0,heightOfOSC). This
reverses the image left-to-right. Here is the complete class:
import java.awt.*;
import javax.swing.*;
This class defines the method "public Dimension getPreferredSize()". This method is
called by a layout manager when it wants to know how big the component would like
to be. Standard components come with a way of computing a preferred size. For a
custom component based on a JPanel, it's a good idea to provide a custom preferred
size. As I mentioned in Section 1, every component has a method setPrefferedSize()
that can be used to set the preferred size of the component. For our MirrorLabel
component, however, the preferred size depends the font and the text of the
component, and these can change from time to time. We need a way to compute a
preferred size on demand, based on the current font and text. That's what we do by
defining a getPreferredSize() method. The system calls this method when it wants to
know the preferred size of the component. In response, we can compute the preferred
size based on the current font and text.
The StopWatch and MirrorLabel class define components. Components don't stand on
their own. You have to add them to an applet or other container. Here is an applet that
demonstrates a MirrorLabel and a StopWatch component:
The source code for this applet is in the file ComponentTest.java. The applet uses a
FlowLayout, so the components are not arranged very neatly. The applet also contains
a button, which is there to illustrate another fine point of programming with
components. If you click the button labeled "Change Text in this Applet", the text in
all the components will be changed. You can also click on the "Timing..." label to start
and stop the StopWatch. When you do any of these things, you will notice that the
components will be rearranged to take the new sizes into account. This is known as
"validating" the container. This is done automatically when a standard component
changes in some way that requires a change in preferred size or location. This may or
may not be the behavior that you want. (Validation doesn't always cause as much
disruption as it does in this applet. For example, in a GridLayout, where all the
components are displayed at the same size, it will have no effect at all. I've chosen a
FlowLayout for this example to make the effect more obvious.) A custom component
such as MirrorLabel can call the revalidate() method to indicate that the container that
contains the component should be validated. In the MirrorLabel class, revalidate() is
called in the setText() method.
In the init() method of this applet, the components are created and added to the applet.
Then the setBounds() method of each component is called to set the size and position
of the component:
public void init() {
getContentPane().setBackground(new Color(0,150,0));
// Set a dark green background.
/* Create the components and add them to the content pane. If you
don't add them to the a container, they won't appear, even if
you set their bounds! */
board.setBounds(20,20,164,164);
newGameButton.setBounds(210, 60, 120, 30);
resignButton.setBounds(210, 120, 120, 30);
message.setBounds(0, 200, 330, 30);
It's reasonably easy, in this case, to get an attractive layout. It's much more difficult to
do your own layout if you want to allow for changes of size. In that case, you have to
respond to changes in the container's size by recomputing the sizes and positions of
all the components that it contains. If you want to respond to changes in a container's
size, you can register an appropriate listener with the container. Any component
generates an event of type ComponentEvent when its size changes (and also when it is
moved, hidden, or shown). You can register a ComponentListener with the container
and respond to size change events by recomputing the sizes and positions of all the
components in the container. Consult a Java reference for more information about
ComponentEvents. However, my real advice is that if you want to allow for changes
in the container's size, try to find a layout manager to do the work for you.
This is a much improved version of the ShapeDraw applet from Section 5.4. You can
add shapes to the large white drawing area and drag them around. To add a shape,
select one of the commands in the "Add" menu. The other menus allow you to control
the properties of the shapes and set the background color of the drawing area.
This applet illustrates many ideas related to menus. There is a menu bar. A menu bar
serves as a container for menus. In this case, there are three menus in the menu bar.
The menus have titles: "Add", "Color", and "Options". When you click on one of
these titles, the menu items in the menu appear. Each menu has an associated
mnemonic, which is a character that is underlined in the name. Instead of clicking on
the menu, you can select it by pressing the mnemonic key while holding down the
ALT key. (This assumes that the applet has the keyboard focus.)
Once the menu has appeared, you can select an item in the menu by clicking on it, or
by using the arrow keys to select the item and then pressing return. It is possible to
assign mnemonics to individual items in a menu, but I haven't done that in this
example. The commands in the "Add" menu and the "Clear" command do have
accelerators. An accelerator is a key or combination of keys that can be pressed to
invoke a menu item without ever opening the menu. The accelerator is shown in the
menu, next to the name of the item. For example, the accelerator for the "Rectangle"
command in the "Add" menu is "Ctrl-R". This means that you can invoke the
command by holding down the Control key and pressing the R key. (Again, this
assumes that the applet has the keyboard focus. The accelerators might not function at
all in an applet. If so, you'll see how they work in Section 7)
The commands in the "Color" menu act like a set of radio buttons. Only one item in
the menu can be selected at a given time. The selected item in this menu determines
the color of newly added shapes. Similarly, two of the commands in the "Options"
menu act just like checkboxes. The first of these items determines whether newly
added shapes will be large or small. The second determines whether newly added
shapes will have a black border drawn around them.
The last item in the "Options" menu is actually another menu. This is called a sub-
menu. When you select this item, the sub-menu will appear. Select an item from the
sub-menu to set the background color of the drawing area.
This applet also demonstrates a pop-up menu. The pop-up menu appears when you
click on one of the shapes in just the right way. The exact action you have to take
depends on the look-and-feel and is called the pop-up trigger. The pop-up trigger is
probably either clicking with the right mouse button, clicking with the middle mouse
button, or clicking while holding down the Control key. The pop-up menu in this
example contains commands for editing the shape on which you clicked.
In the rest of this section, we'll look at how all this can be programmed. If you would
like to see the complete source code of the applet, you will find it in the file
ShapeDrawWithMenus.java. The source code is just over 600 lines long. The menus
are created and configured in a very long init() method.
Accelerators
A menu item in a JMenu can have an accelerator. The accelerator is a key, possibly
with some modifiers such as ALT or Control, that the user can press to invoke the
menu item without opening the menu. The menu item is processed in exactly the same
way whether it is invoked with an accelerator, with a mnemonic, or with the mouse.
An accelerator can be described by a string that specifies the key to be pressed and
any modifiers that must be held down while the key is pressed. Modifiers are
specified by the words shift, alt, ctrl, and meta. These must be lower case. The key is
specified by an upper case letter or by the name of certain special keys including:
HOME, END, DELETE, INSERT, LEFT, RIGHT, UP, DOWN, F1, F2, .... The
string that describes an accelerator consists of as many modifiers as you want,
followed by any one key specification. You don't use the string directly to create an
accelerator. The string is passed as a parameter to the static method
KeyStroke.getKeyStroke(String), which returns an object of type KeyStroke. The
KeyStroke object can be used to add an accelerator to a JMenuItem. This is done by
calling the JMenuItem's setAccelerator() method, which requires a parameter of type
KeyStroke. For example, the first menu item in the "Add" menu of the sample applet
was created with the commands:
JMenuItem rect = new JMenuItem("Rectangle");
rect.setAccelerator( KeyStroke.getKeyStroke("ctrl R") );
The menu item will be invoked if the user holds down the Control key and presses the
R key. Although it's unfortunate that you have to go through the KeyStroke class, it's
really not all that complicated. Here are a few more examples of accelerators:
menuitem.setAccelerator( KeyStroke.getKeyStroke("shift ctrl S") );
// User must hold down both SHIFT and
// Control, while pressing the S key.
menuitem.setAccelerator( KeyStroke.getKeyStroke("HOME") );
// User can invoke the menu item just by pressing
// the HOME key.
Pop-up Menus
A pop-up menu is an object belonging to the class JPopupMenu. It can be created with
a constructor that has no parameters. Menu items, sub-menus, and separating lines can
be added to a JPopupMenu in exactly the same way that they would be added to a
JMenu. Menu items in a JPopupMenu generate ActionEvents, just as they would if
they were in a JMenu. However, a JPopupMenu is not added to a menu bar. In fact, it
is not added to any container at all. A JPopupMenu has a show() method that you can
call to make it appear on the screen. Once it has appeared, the user can invoke an item
in the menu in the usual way. When the user makes a selection, the menu disappears.
The user can click outside the menu or hit the Escape key to dismiss the menu without
making any selection from it.
The show() method takes three parameters. The first parameter is a Component. Since
a JPopupMenu is not contained in any component, you have to tell it which
component it will be associated with when it appears on the screen. The next two
parameters of show() are integers that specify where the popup should appear on the
screen. The integers give the coordinates of the point where the upper left corner of
the popup menu will be located. The coordinates are specified in the coordinate
system of the component that is provided as the first parameter to show().
You can call show() any time you like. Usually, though, it's done in response to a
mouse click. In that case, the first parameter to show() is generally the component on
which the user clicked, and the next two parameters are the x and y coordinates where
the mouse was clicked. (Actually, I usually use something like x-10 and y-2 so that
the mouse position will be inside the popup menu, rather than exactly at the upper left
corner. This tends to work better.)
Suppose, for example, that you want to show the menu when the user right-clicks on a
component. You need to set up a mouse listener for the component and call the popup
menu's show() method in the mousePressed() method of the listener. Let's say that
popup is the variable of type JPopupMenu that refers to the popup menu and that
comp is the variable of type JComponent that refers to the component. Then the
mousePressed() method could be written as:
public void mousePressed(MouseEvent evt) {
if (evt.isMetaDown()) { // This tests for a right-click
int x = evt.getX(); // X-coord of mouse click
int y = evt.getY(); // Y-coord of mouse click
popup.show( comp, x-10, y-2 );
}
}
If the component is also serving as the mouse listener, you could replace
popup.show(comp,x-10,y-2) with popup.show(this,x-10,y-2). Note that the only thing
you do in response to the user's click is show the popup. The commands in the popup
have to be handled elsewhere, such as in the actionPerformed() method of an
ActionListener that has been registered to receive action events from the menu items
in the popup menu.
This will work, but it's not the best style for handling popup menus. The problem is
that different platforms have different standard techniques for calling up popup
menus. Under Windows, the user expects a right-click to call up a menu. Under
MacOS, the user would expect to hold down the Control key while clicking. If you
want your program to work in a natural way on all platforms, you can call
evt.isPopupTrigger() to determine whether a given mouse event is the proper "trigger"
for calling up a popup menu in the current look-and-feel. Unfortunately, to do things
right, you have to check for the popup trigger in both mousePressed() and in
mouseReleased(), since a given look-and-feel might use either type of event as a
trigger. So, the code for showing the popup becomes:
public void mousePressed(MouseEvent evt) {
if (evt.isPopupTrigger()) {
int x = evt.getX(); // X-coord of mouse click
int y = evt.getY(); // Y-coord of mouse click
popup.show( comp, x-10, y-2 );
}
}
Here is part of the source code for this applet, omitting the definition of the nested
class that defines the drawing surface:
public class HelloWorldSpectrum extends JApplet {
getContentPane().add(display, BorderLayout.CENTER);
// Adds the display panel to the CENTER position of the
// JApplet's content pane.
} // end init()
void startAnimation() {
// Start the animation, unless it is already running.
// We can check if it is running since the value of
// timer is non-null when the animation is running.
// (It should be impossible for this to be called
// when an animation is already running... but it
// doesn't hurt to check!)
if (timer == null) {
// Start the animation by creating a Timer that
// will fire an event every 50 milliseconds, and
// will send those events to timerListener.
timer = new Timer(50, timerListener);
timer.start(); // Make the time start running.
startStopButton.setText("Stop");
}
}
void stopAnimation() {
// Stop the animation by stopping the timer, unless the
// animation is not running.
if (timer != null) {
timer.stop(); // Stop the timer.
timer = null; // Set timer variable to null, so that we
// can tell that the animation isn't running.
startStopButton.setText("Start");
}
}
You can find the source code in the file ScrollingHelloWorld.java, but the relevant
part here is the start() and stop() methods:
Using Threads
Although Timers can replace threads in some cases, there are times when direct use of
threads is necessary. When a Timer is used, the processing is done in an event handler.
This means that the processing must be something that can be done quickly. An event
handler should always finish its work quickly, so that the system can move on to
handle the next event. If an event handler runs for a long time, it will block other
events from being processed, and the program will become unresponsive. So, in a
GUI application, any computation or process that will take a long time to complete
should be run in a separate thread. Then the event-handling thread can continue to run
at the same time, responding to user actions as they occur.
As a short and incomplete introduction to threads, we'll look at one example. The
example requires some explanation, but the main point for our discussion of threads is
that it is a realistic example of a long computation that requires a separate thread. The
example is based on the Mandelbrot set, a mathematical curiosity that has become
familiar because it can be used to produce a lot of pretty pictures. The Mandelbrot set
has to do with the following simple algorithm:
Start with a point (x,y) in the plane, where x and y are real numbers.
Let zx = x, and let zy = y.
Repeat the following:
Replace (zx,zy) with ( zx*zx - zy*zy + x, 2*zx*zy + y )
The question is, what will happen to the point (zx,zy) as the loop is repeated over and
over? The answer depends on the initial point (x,y). For some initial points (x,y), the
point (zx,zy) will, sooner or later, move arbitrarily far away from the origin, (0,0). For
other starting points, the point (zx,zy) will stay close to (0,0) no matter how many
times you repeat the loop. The Mandelbrot set consists of the (x,y) points for which
(zx,zy) stays close to (0,0) forever. This would probably not be very interesting,
except that the Mandelbrot set turns out to have an incredibly intricate and quite pretty
structure.
To get a pretty picture from the Mandelbrot set, we change the question, just a bit.
Given a starting point (x,y), we ask, how many steps does it take, up to some specified
maximum number, before the point (zx,zy) moves some set distance away from (0,0)?
We then assign the point a color, depending on the number of steps. If we do this for
each (x,y), we get a kind of picture of the set. For a point in the Mandelbrot set, the
count always reaches the maximum (since for such points, (zx,zy) never moves far
away from zero). For other points, in general, the closer the point is to the Mandelbrot
set, the more steps it will take.
With all that said, here is an applet that computes a picture of the Mandelbrot set. It
will begin its computation when you press the "Start" button. (Eventually, the color of
every pixel in the applet will be computed, but the applet actually computes the colors
progressively, filling the applet with smaller and smaller blocks of color until it gets
down to the single pixel level.) The applet represents a region of the plane with
-1.25 <= x <= 1.0 and -1.25 <= y <= 1.25. The Mandelbrot set is colored purple.
Points outside the set have other colors. Try it:
void stopRunning() {
// A simple method that is called to stop the computational
// thread. This is done by setting the value of the
// variable, running. The thread checks this value
// regularly and will terminate when running becomes false.
running = false;
}
There are a few more details of threads that you need to understand before looking at
the run() method from the applet. First, on some platforms, once a thread starts
running it grabs control of the CPU, and no other thread can run until it yields control.
In Java, a thread can yield control, and allow other threads to run, by calling the static
method Thread.yield(). I do this regularly in the run() method of the applet. If I did
not do this, then, on some platforms, the computational thread would block the rest of
the program from running. Another way for a thread to yield control is to go to sleep
for a specified period of time by calling Thread.sleep(time), where time is the number
of milliseconds for which the thread will be inactive. The thread in a Timer, for
example, sleeps between events, since it has nothing else to do.
Another issue concerns the use of threads with Swing. There is a rule in Swing: Don't
touch any GUI components, or any data used by them, except in the event-handling
thread, that is, in event-handling methods or in paintComponent(). The reason for this
is that Swing is not thread-safe. If more than one thread plays with Swing's data
structures, then the data can be corrupted. (This is done for efficiency. Making Swing
thread-safe would slow it down significantly.) To solve this problem, Swing has a way
for another thread to get the event-handling thread to run a subroutine for it. The
subroutine must be a run() method in a Runnable object. When a thread calls the static
method
void SwingUtilities.invokeAndWait(Runnable runnableObject)
the run() method of runnableObject will be executed in the event-handling thread,
where it can safely do anything it wants to Swing components and their data. The
invokeAndWait method, as the name indicates, does not return until the run() method
has been executed. (The invokeAndWait method can produce an exeception, and so
must be called inside a try...catch statement. I will cover try...catch statements in
Chapter 9. You can ignore it for now.)
The run() method for the thread in the Mandelbrot applet uses
SwingUtilities.invokeAndWait() to color a square on the screen. Here, finally, is that
run() method (which will still take some work to understand):
public void run() {
// This is the run method that is executed by the
// computational thread. It draws the Mandelbrot
// set in a series of passes of increasing resolution.
// In each pass, it fills the applet with squares
// that are colored to represent the Mandelbrot set.
// The size of the squares is cut in half on each pass.
OSI = createImage(getWidth(),getHeight());
// Create the off-screen image where the picture will
// be stored, and fill it with black to start.
OSG = OSI.getGraphics();
OSG.setColor(Color.black);
OSG.fillRect(0,0,width,height);
} // end run()
APPLETS ARE A FINE IDEA. It's nice to be able to put a complete program in a
rectangle on a Web page. But more serious, large-scale programs have to run in their
own windows, independently of a Web browser. In Java's Swing GUI library, an
independent window is represented by an object of type JFrame. A stand-alone GUI
application can open one or more JFrames to provide the user interface. It is even
possible for an applet to open a frame. The frame will be a separate window from the
Web browser window in which the applet is running. Any frame created by an applet
includes a warning message such as "Warning: Insecure Applet Window." The
warning is there so that you can always recognize windows created by applets. This is
just one of the security restrictions on applets, which, after all, are programs that can
be downloaded automatically from Web sites that you happen to stumble across
without knowing anything about them.
Here is an applet that contains just one small button. When you click this "Launch
ShapeDraw" button, a JFrame will be opened:
The frame that is created when you click the button is almost identical to the
ShapeDrawWithMenus applet from Section 5, and it is used in the same way.
However, you can change the size of the window, and you can make the window go
away by clicking its close box.
The window in this example belongs to a class named ShapeDrawFrame, which is
defined as a subclass of JFrame. The structure of a JFrame is almost identical to a
JApplet, and the programming is almost the same. In fact, only a few changes had to
be made to the applet class, ShapeDrawWithMenus, to convert it from a JApplet to a
JFrame. First, a frame does not have an init() method, so the initialization for
ShapeDrawFrame is done in a constructor instead of in init(). In fact, the only real
change necessary to convert a typical applet class into a frame class is to convert the
applet's init() method into a constructor, and to add a bit of frame-specific
initialization to the constructor. Everything that you learned about creating and
programming GUI components and adding them to a content pane applies to frames
as well. Menus are also handled in exactly the same way. So, we really only need to
look at the additional programming that is necessary for frames.
One significant difference is that the size and location of an applet are determined
externally to the applet, by the HTML code for a Web page and by the browser that
displays the page. The size of a frame, on the other hand, has to be set by the frame
itself or by the program that creates the frame. Often, the size is set in the frame's
constructor. (If you forget to do this, the frame will have size zero and all you will see
on the screen is a tiny border.) There are two methods in the JFrame class that can be
used to set the size of a frame:
void setSize(int width, int height);
and
void pack();
Use setSize() if you know exactly what size the frame should be. The pack() method
is more interesting. It should only be called after all GUI components have been
added to the frame. Calling pack() will make the frame just big enough to hold all the
components. It will determine the size of the frame by checking the preferred size of
each of the components that it contains. (As mentioned in Section 3, standard GUI
components come with a preferred size. When you create your own drawing surface
or custom component, you can set its preferred size by calling its setPreferredSize()
method or by definining a getPreferredSize() method to compute the size.)
You can also set the location of the frame. This can be done with by calling the
JFrame method:
void setLocation(int x, int y);
The parameters, x and y give the position of the upper left corner of the frame on the
screen. They are given in terms of pixel coordinates on the screen as a whole, where
the upper left corner of the screen is (0,0).
Creating a frame object does not automatically make a window appear on the screen.
Initially, the window is invisible, You must make it visible by calling its method
void show();
This can be called at the end of the frame's constructor, but it can also be reasonable
to leave it out. In that case, the constructor will produce an invisible window, and the
program that creates the frame is responsible for calling its show() method.
A frame has a title, a string that appears in the title bar at the top of the window. This
title can be provided as an argument to the constructor or it can be set by calling the
method:
void setTitle(String title);
(In the ShapeDrawFrame class, I set the title of the frame to be "Shape Draw". I do
this by calling a constructor in the superclass with the command:
super("Shape Draw");
at the beginning of the ShapeDrawFrame constructor.)
Now you know how to get a frame onto the screen and how to give it a title. There is
still the matter of getting rid of the frame. You can hide a frame by calling its hide()
method. If you do this, you can make it visible again by calling show(). If you are
completely finished with the window, you can call its dispose() method to close the
window and free the system resources that it uses. After calling dispose(), you should
not use the frame object again. You also have to be prepared for the fact that the user
can click on the window's close box to indicate that it should be closed. By default,
the system will hide the window when the user clicks its close box. However, you can
tell the system to handle this event differently. Sometimes, it makes more sense to
dispose of the window or even to call System.exit() and end the program entirely. It is
even possible, as we will see below, to set up a listener to listen for the event, and to
program any response you want. You can set the default response to a click in a
frame's close box by calling:
void setDefaultCloseOperation(int operation);
where the parameter, operation is one of the constants
JFrame.HIDE_ON_CLOSE -- just hide the window, so it can be opened again
JFrame.DISPOSE_ON_CLOSE -- destroy the window, but don't end the program
JFrame.EXIT_ON_CLOSE -- terminate the Java interpretor by calling System.exit()
JFrame.DO_NOTHING_ON_CLOSE -- no automatic response; your program is
responsible for closing the window.
If a frame is opened by a main program, and if the program has only one window, it
might make sense to use EXIT_ON_CLOSE. However, note that this option is illegal
for a frame that is created by an applet, since an applet is not allowed to shut down the
Java interpreter.
In case you are curious, here are the lines that I added to the end of the
ShapeDrawFrame constructor:
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocation(20,50);
setSize(550,420);
show();
I also added a main() routine to the class. This means that it is possible to run
ShapeDrawFrame as a stand-alone application. In a typical command-line
environment, you would do this with the command:
java ShapeDrawFrame
It has been a while since we looked at a stand-alone program with a main() routine,
and we have never seen a stand-alone GUI program. It's easy for a stand-alone
program to use a graphical user interface -- all it has to do is open a frame. Since a
ShapeDrawFrame makes itself visible when it is created, it is only necessary to create
the frame object with the command "new ShapeDrawFrame();". The complete main
routine in this case looks like:
public static void main(String[] args) {
new ShapeDrawFrame();
}
It might look a bit unusual to call a constructor without assigning the result to a
variable, but it is perfectly legal and in this case we have no need to store the value.
The main routine ends as soon as the frame is created, but the frame continues to exist
and the program will continue running. Since the default close operation for the frame
has been set to EXIT_ON_CLOSE, the frame will close and the program will be
terminated when the user clicks the close box of the window. It might seem a bit odd
to have this main() routine in the same class that defines ShapeDrawFrame, and in
fact it could just as easily be in a separate class. But there is no real need to create an
extra class, as long as you understand what is going on. When you type "java
ShapeDrawFrame" on the command line, the system looks for a main routine in the
ShapeDrawFrame class and executes it. If the main routine happens to create an
object belonging to the same class, it's not a problem. It's just a command to be
executed.
The source code for the frame class is in the file ShapeDrawFrame.java. The applet,
shown above, which opens a frame of this type is in ShapeDrawLauncher.java.
We'll look at a few more fine points of programming with frames by looking at
another example. In this case, it's a frame version of the HighLowGUI2 applet from
Section 1. Click on this button to open the frame:
The frame in this example is defined in the file HighLowFrame.java. In many ways,
this example is similar to the previous one, but there are several differences. You can
resize the frame in the first example by dragging its border or corner, but if you try to
resize the "High Low" frame, you will find that it is impossible. A frame is resizable
by default. You can make it non-resizable by calling setResizable(false). I do this in
the constructor of the HighLowFrame class. Another difference shows up if you click
the frame's close box. This will not simply close the window. Instead a new window
will open to ask you whether you really want to close the HighLow frame. The new
window is an example of a "dialog box". You will learn about dialog boxes later in
this section. To proceed, you have to click a button in the dialog box. If you click on
"Yes", the HighLow frame will be closed; if not, the frame will remain open. (This
would be more useful if, for example, you wanted to give the user a chance to save
some unsaved work before closing the window.) To get this behavior, I had to turn off
the system's default handling of the close box with the command:
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
and I had to program my own response instead. I did this by registering a window
listener for the frame. When certain operations are performed on a window, the
window generates an event of type WindowEvent. You can program a response to
such events in the usual way: by registering a listening object of type WindowListener
with the frame. The JFrame class has an addWindowListener()method for this
purpose. The WindowListener must define seven event-handling methods, including
the poorly named
public void windowClosing(WindowEvent evt)
and
public void windowClosed(WindowEvent evt)
The windowClosing event is generated when the user clicks the close box of the
window. The windowClosed event is generated when the window is actually being
disposed. The other five methods in the WindowListener interface are more rarely
used. Fortunately, you don't have to worry about them if you use the WindowAdapter
class. The WindowAdapter class implements the WindowListener interface, but
defines all the WindowListener methods to be empty. You can define a
WindowListener by creating a subclass of WindowAdapter and providing definitions
for just those methods that you actually need. In the HighLowFrame class, I need a
listener to respond to the windowClosing event that is generated when the user clicks
the close box. The listener is created in the constructor using an anonymous subclass
of WindowAdapter with a command of the form:
addWindowListener( new WindowAdapter() {
// This window listener responds when the user
// clicks the window's close box by giving the
// user a chance to change his mind.
public void windowClosing(WindowEvent evt) {
.
. // Show the dialog box, and respond to it.
.
}
});
Another window listener is used in the little applet that appears on this page as the
"Launch HighLow" button, above. This applet is defined in the file
HighLowLauncher.java. Note that when you click on the button to open the frame, the
name of the button changes to "Close HighLow". You can close the frame by clicking
the button again, as well as by clicking the frame's close box. When the frame is
closed, for either reason, the name of the button changes back to "Launch HighLow".
The question is, how does the applet know to change the button's name, when the user
closes the frame by clicking its close box? That doesn't seem to have anything to do
with the applet. The trick is to use an event listener. When the applet creates the
frame, it also creates a WindowListener and registers it with the frame. This
WindowListener is programmed to respond to the windowClosed event by changing
the name of the button. This is a nice example of the sort of communication between
objects that can be done with events. You can check the source code to see exactly
how it's done.
Images in Applications
In Section 1, we saw how to load an image file into an applet. The JApplet class has a
method, getImage(), that can be used for this purpose. The JFrame class does not
provide this method, so some other technique is needed for using images in frames.
The standard class java.awt.Toolkit makes it possible to load an image into a stand-
alone application. A Toolkit object has a getImage() method for reading an Image
from an image file. To use this method, you must first obtain a Toolkit, and you have
to do this by calling the static method Toolkit.getDefaultToolkit(). (Any running GUI
program already has a toolkit, which is used to perform various platform-dependent
functions. You don't need to construct a new toolkit. Toolkit.getDefaultToolkit()
returns a reference to the toolkit that already exists.) Once you have a toolkit, you can
use its getImage() method to create an Image object from a file. This getImage
method takes one parameter, which specifies the name of the file. For example:
Toolkit toolkit = getDefaultToolkit();
Image cards = toolkit.getImage( "smallcards.gif" );
or, in one line,
Image cards = Toolkit.getDefaultToolkit().getImage( "smallcards.gif" );
Once the Image has been created, it can be used in the same way, whether it has been
created by an applet or a standalone application.
Note that an applet's getImage() method is used to load an image from a Web server,
while a Toolkit's getImage() loads an image from the same computer on which the
program is running. An applet cannot, in general, use a Toolkit to load an image,
since, for security reasons, an applet is not usually allowed to read files from the
computer on which it is running.
The HighLowFrame example uses an image file named "smallcards.gif" for the cards
that it displays. I designed HighLowFrame with a main() routine so that it can be run
as a stand-alone application. (When it is run as an application, the "smallcards.gif" file
must be in the same directory with the class files.) But a HighLowFrame can also be
opened by an applet, as is done in the example on this page. When it is run as an
application, the image file must be loaded by a Toolkit. When it is opened by an
applet, the image file must be loaded by the getImage() method of the applet. How
can this be handled? I decided to do it by making the Image object a parameter to the
HighLowFrame constructor. The Image must be loaded before the frame is
constructed, so that it can be passed as a parameter to the constructor. The main()
routine in HighLowFrame does this using a Toolkit:
Image cards = Toolkit.getDefaultToolkit().getImage("smallcards.gif");
HighLowFrame game = new HighLowFrame(cards);
The HighLowLauncher applet, on the other hand, loads the image with its own
getImage() method:
Image cards = getImage(getCodeBase(),"smallcards.gif");
highLow = new HighLowFrame(cards);
Dialogs
In addition to JFrame, there is another type of window in Swing. A dialog box is a
type of window that is generally used for short, single purpose interactions with the
user. For example, a dialog box can be used to display a message to the user, to ask
the user a question, or to let the user select a color. In Swing, a dialog box is
represented by an object belonging to the class JDialog.
Like a frame, a dialog box is a separate window. Unlike a frame, however, a dialog
box is not completely independent. Every dialog box is associated with a frame (or
another dialog box), which is called its parent. The dialog box is dependent on its
parent. For example, if the parent is closed, the dialog box will also be closed. It is
possible to create a dialog box without specifying a parent, but in that case a default
frame is used or an invisible frame is created to serve as the parent.
Dialog boxes can be either modal or modeless. When a modal dialog is created, its
parent frame is blocked. That is, the user will not be able to interact with the parent
until the dialog box is closed. Modeless dialog boxes do not block their parents in the
same way, so they seem a lot more like independent windows. In practice, modal
dialog boxes are easier to use and are much more common than modeless dialogs. All
the examples we will look at are modal.
Aside from having a parent, a JDialog can be created and used in the same way as a
JFrame. However, we will not be using JDialog directly. Swing has many convenient
methods for creating many common types of dialog boxes. For example, the
JColorChooser class has the static method:
Color JColorChooser.showDialog(JFrame parent, Color initialColor)
When you call this method, a dialog box appears that allows the user to select a color.
The first parameter specifies the parent of the dialog, or it can be null. When the
dialog first appears, initialColor is selected. The dialog has a sophisticated interface
that allows the user to change the selection. When the user presses an "OK" button,
the dialog box closes and the selected color is returned as the value of the method.
The user can also click a "Cancel" button or close the dialog box in some other way;
in that case, null is returned as the value of the method. By using this predefined color
chooser dialog, you can write one line of code that will let the user select an arbitrary
color.
The following applet demonstrates a JColorChooser dialog and three other, simpler
standard dialog boxes. When you click one of the buttons, a dialog box appears. The
label at the top of the applet gives you some feedback about what is happening:
The three simple dialogs in this applet are created by static methods in the class
JOptionPane. This class includes many methods for making dialog boxes, but they are
all variations on the three basic types shown here: a "message" dialog, a "confirm"
dialog, and an "input" dialog. (The variations allow you to provide a title for the
dialog box, to specify the icon that appears in the dialog, and to add other components
to the dialog box. I will only cover the most basic forms here.)
A message dialog simply displays a message string to the user. The user (hopefully)
reads the message and dismisses the dialog by clicking the "OK" button. A message
dialog can be shown by calling the method:
void JOptionPane.showMessageDialog(JFrame parent, String message)
The parent, as usual, can be null. The message can be more than one line long. Lines
in the message should be separated by newline characters, \n. New lines will not be
inserted automatically, even if the message is very long.
An input dialog displays a question or request and lets the user type in a string as a
response. You can show an input dialog by calling:
String JOptionPane.showInputDialog(JFrame parent, String question)
Again, the parent can be null, and the question can include newline characters. The
dialog box will contain an input box and an "OK" button and a "Cancel" button. If the
user clicks "Cancel", or closes the dialog box in some other way, then the return value
of the method is null. If the user clicks "OK", then the return value is the string that
was entered by the user. Note that the return value can be an empty string (which is
not the same as a null value), if the user clicks "OK" without typing anything in the
input box. If you want to use an input dialog to get a numerical value from the user,
you will have to convert the return value into a number. A technique for doing this can
be found in the first example in Section 4.
Finally, a confirm dialog presents a question and three response buttons: "Yes", "No",
and "Cancel". A confirm dialog can be shown by calling:
int JOptionPane.showConfirmDialog(JFrame parent, String question)
The return value tells you the user's response. It is one of the following constants:
JOptionPane.YES_OPTION -- the user clicked the "Yes" button
JOptionPane.NO_OPTION -- the user clicked the "No" button
JOptionPane.CANCEL_OPTION -- the user clicked the "Cancel" button
JOptionPane.CLOSE_OPTION -- the user closed the dialog in some other way.
I use a confirm dialog in the HighLowFrame example, earlier on this page. When the
user clicks the close box of a HighLowFrame, I display a confirm dialog to ask
whether the user really wants to quit. The frame will only be closed if the return value
is JOptionPane.YES_OPTION.
By the way, it is possible to omit the Cancel button from a confirm dialog by calling
one of the other methods in the JOptionPane class. Just call:
JOptionPane.showConfirmDialog(
parent, question, title, JOptionPane.YES_NO_OPTION )
The final parameter is a constant which specifies that only a "Yes" button and a "No"
button should be used. The third parameter is a string that will be displayed as the title
of the dialog box window.
If you would like to see how dialogs are created and used in the sample applet, you
can find the source code in the file SimpleDialogDemo.java.