Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
3K views

CIT 212 Object Oriented Programming With Java

Introduction to basic programing
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
3K views

CIT 212 Object Oriented Programming With Java

Introduction to basic programing
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 273

UNIVERSITYCOMPUTING CENTER LTD

DIPLOMA INCOMPUTING AND INFORMATION


TECHNOLOGY

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

The Basic Java Application

A PROGRAM IS A SEQUENCE OF INSTRUCTIONS that a computer can execute


to perform some task. A simple enough idea, but for the computer to make any use of
the instructions, they must be written in a form that the computer can use. This means
that programs have to be written in programming languages. Programming languages
differ from ordinary human languages in being completely unambiguous and very
strict about what is and is not allowed in a program. The rules that determine what is
allowed are called the syntax of the language. Syntax rules specify the basic
vocabulary of the language and how programs can be constructed using things like
loops, branches, and subroutines. A syntactically correct program is one that can be
successfully compiled or interpreted; programs that have syntax errors will be rejected
(hopefully with a useful error message that will help you fix the problem).
So, to be a successful programmer, you have to develop a detailed knowledge of the
syntax of the programming language that you are using. However, syntax is only part
of the story. It's not enough to write a program that will run. You want a program that
will run and produce the correct result! That is, the meaning of the program has to be
right. The meaning of a program is referred to as its semantics. A semantically correct
program is one that does what you want it to.
When I introduce a new language feature in these notes, I will explain both the syntax
and the semantics of that feature. You should memorize the syntax; that's the easy
part. Then you should try to get a feeling for the semantics by following the examples
given, making sure that you understand how they work, and maybe writing short
programs of your own to test your understanding.
Of course, even when you've become familiar with all the individual features of the
language, that doesn't make you a programmer. You still have to learn how to
construct complex programs to solve particular problems. For that, you'll need both
experience and taste. You'll find hints about software development throughout this
textbook.

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 {

// A program to display the message


// "Hello World!" on standard output

public static void main(String[] args) {


System.out.println("Hello World!");
}

} // end of class HelloWorld


The command that actually displays the message is:
System.out.println("Hello World!");
This command is an example of a subroutine call statement. It uses a "built-in
subroutine" named System.out.println to do the actual work. Recall that a subroutine
consists of the instructions for performing some task, chunked together and given a
name. That name can be used to "call" the subroutine whenever that task needs to be
performed. A built-in subroutine is one that is already defined as part of the language
and therefore automatically available for use in any program.
When you run this program, the message "Hello World!" (without the quotes) will be
displayed on standard output. Unfortunately, I can't say exactly what that means! Java
is meant to run on many different platforms, and standard output will mean different
things on different platforms. However, you can expect the message to show up in
some convenient place. (If you use a command-line interface, like that in Sun
Microsystem's Java Development Kit, you type in a command to tell the computer to
run the program. The computer will type the output from the program, Hello World!,
on the next line.)
You must be curious about all the other stuff in the above program. Part of it consists
of comments. Comments in a program are entirely ignored by the computer; they are
there for human readers only. This doesn't mean that they are unimportant. Programs
are meant to be read by people as well as by computers, and without comments, a
program can be very difficult to understand. Java has two types of comments. The
first type, used in the above program, begins with // and extends to the end of a line.
The computer ignores the // and everything that follows it on the same line. Java has
another style of comment that can extend over many lines. That type of comment
begins with /* and ends with */.
Everything else in the program is required by the rules of Java syntax. All
programming in Java is done inside "classes." The first line in the above program says
that this is a class named HelloWorld. "HelloWorld," the name of the class, also
serves as the name of the program. Not every class is a program. In order to define a
program, a class must include a subroutine called main, with a definition that takes the
form:
public static void main(String[] args) {
statements
}
When you tell the Java interpreter to run the program, the interpreter calls the main()
subroutine, and the statements that it contains are executed. These statements make up
the script that tells the computer exactly what to do when the program is executed.
The main() routine can call subroutines that are defined in the same class or even in
other classes, but it is the main() routine that determines how and in what order the
other subroutines are used.
The word "public" in the first line of main() means that this routine can be called from
outside the program. This is essential because the main() routine is called by the Java
interpreter. The remainder of the first line of the routine is harder to explain at the
moment; for now, just think of it as part of the required syntax. The definition of the
subroutine -- that is, the instructions that say what it does -- consists of the sequence
of "statements" enclosed between braces, { and }. Here, I've used statements as a
placeholder for the actual statements that make up the program. Throughout this
textbook, I will always use a similar format: anything that you see in this style of text
(which is green if your browser supports colored text) is a placeholder that describes
something you need to type when you write an actual program.
As noted above, a subroutine can't exist by itself. It has to be part of a "class". A
program is defined by a public class that takes the form:
public class program-name {

optional-variable-declarations-and-subroutines

public static void main(String[] args) {


statements
}

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:

The immense popularity of Java is a confluence of many circumstances, such as


developers sick of the complexity and largess of C++; PC programmers tired of
dealing with an arcane OLE and goofy Hungarian notation; window mavens ho-
humming Motif and X Window; corporate IT architects complaining of the

awkwardness of writing multi-platform software; programmers weary of developing


distributed applications with RPC and XDR; users and advertisers worrying about the
lack of interactivity and security with the Web; hardware vendors drooling over the
idea of ubiquitous computing devices; and probably not least of all, the growing anti-
Microsoft sentiment (after all, it's human nature to root for the little guy, and there's
nothing little about Microsoft).
Hypermedia + interactivity = hyperactivity
Imagine that there is a system that allows one to interact with all sorts of applications
on the Internet. And not only does this system allow you to write programs that run
over the Internet, it also provides a high degree of security to programs and users,
protects programmers from their own mistakes and offers neat multimedia
functionality to display images, play audio and video clips. But wait, there's more!
This ideal technology also runs on many different types of machines like PCs,
Macintoshes and powerful Sun workstations -- without any additional programming
wizardry. Heck, it even will run on machines that haven't been invented yet!
This is what Java technology promises, but does it deliver the goods?
Java is a general-purpose, object-oriented computer programming language that offers
special features that allow programs to take advantage of the power and flexibility of
the Internet.
Apps and AppNots
There are four different types of programs you can write using Java: applications,
applets, content handlers, and protocol handlers.
Java applications are standalone programs that require the assistance of the Java
interpreter to run. The HotJava Web browser is an example of a Java application. On a
Solaris machine, the "HotJava" program is actually a shell script wrapper that invokes
the Java interpreter (Java) with the "compiled" HotJava application code (i.e., its class
file) as an argument. Java applications are analogous to C/C++ applications; they run
independently of any Web browser.
Java applets are small applications that are embedded on Web pages. Applets are more
security-conscious than Java applications; there are many restrictions on the behavior
of applets. For example, unlike applications, applets cannot dynamically link in older
C or C++ code. A Java applet requires a browser (or another Java application) to run.
Java applets are given a piece of screen real estate in which to draw and a thread of
execution, and require the use of another Java program (such as a browser) to actually
run.
The remaining two types of Java programs, content and protocol handlers, are special-
purpose Java programs that allow Web browsers to dynamically understand new data
types such as QuickTime movies, voice recognition or PhotoCD data and new
protocols like MIDI or a proprietary stock trading protocol. These types of Java
programs make it possible for Java-compliant web browsers to dynamically handle
new types of data on the fly. Got a cool site that's offering music in MIDI format, but
your browser doesn't know how to handle it? No problem if you have Java. The MIDI
handler would be downloaded to your browser along with the data for the handler.
Handlers are similar in philosophy to "helper apps" in Netscape, except they are
infinitely more secure.
While not as popular as Java applications and applets, handlers are critical
components for internet appliances. They would allow new and safe behaviour to be
added dynamically to a consumer product that would be a maintenance and security
nightmare if implemented in a more rigid technology.

Key Features of Java Technology

Key Features

The Power of Server-Side Java


Java has traditionally been known for providing great Web client-side application
support. Java is also a great platform for writing the server side of your Web-based
applications. JavaServer Pages offer Web builders a very powerful way of dealing
with unknown or thin client requirements. The same features that make Java an
excellent platform for writing client applications make it excellent for writing server
applications. Your server applications will benefit from Java's rapid development
features such as type safety, absence of memory leaks and multithreading support
even more than your client applications did. Additionally, the Java platform provides
extensibility into the enterprise. JSP technology is a key component of the Java 2
Enterprise Edition platform. Using JSP technology, organizations are able to leverage
existing Java platform expertise and create highly scalable enterprise applications.
Easy and Rapid Web Development, Deployment and Maintenance
JavaServer Pages simplify and speed the development process for developers and
page authors alike. Instead of writing a Java program, page authors simply write a
page using: HTML and then add the XML-like tags and, if necessary, scriptlets to tie
everything together. Additionally by supporting component-based development and
customized tag libraries, JSP pages not only simplify page authoring but also provide
a strong foundation for a wide range of page authoring tools. Once developed, JSP
pages are easy to maintain because of the separation of the application logic (typically
residing within customized tag libraries or Beans) and the page design/content.
Emphasizing Reusable Components
Most JSP pages rely on reusable, cross-platform components (JavaBeans or Enterprise
JavaBeansTM components) to perform the more complex processing required of the
application. Developers can share and exchange components that perform common
operations, or make them available to larger user or customer communities. The
component-based approach speeds overall development and lets organizations
leverage their existing expertise and development efforts for optimal results.
Separating Content Generation from Presentation
Using JSP technology, web page developers use HTML or XML tags to design and
format the Web page. They use JSP tags or scriptlets to generate the dynamic content
on the page (the content that changes according to the request, such as requested
account information or the price of a specific bottle of wine). The logic that generates
the content is encapsulated in tags and JavaBeans components and tied together in
scriptlets, all of which are executed on the server side. If the core logic is
encapsulated in tags and Beans, then other individuals, such as web masters and page
designers, can edit and work with the JSP page without affecting the generation of the
content. This helps authors protect their own proprietary code while ensuring
complete portability for any HTML-based web browser.

Open Development and Widespread Industry Support


The JSP specification is developed under the Java Community Process. This
guarantees that the specification has a broad spectrum of industry input and support.
This widespread support helps to ensure that JSP technology is supported in a wide
variety of Web and application servers. Additionally, the reference implementation is
now developed openly under the Apache process. By working through the open
process of the Apache Software Foundation, the latest JSP technology will have a
world-class implementation available as soon as possible. Sun Microsystems is
committed to maintaining the portability and openness of the JSP specification and
development process.

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.

Simplifying Page Development with Tags


Web page developers are not always programmers familiar with scripting languages.
The JavaServer Pages technology encapsulates much of the functionality required for
dynamic content generation in easy-to-use, JSP-specific XML tags. Standard JSP tags
can access and instantiate JavaBeans components, set or retrieve bean attributes,
download applets, and perform other functions that are otherwise more difficult and
time-consuming to code. The JSP technology is extensible through the development
of customized tag libraries. Over time, third-party developers and others will create
their own tag libraries for common functions. This lets web page developers work
with familiar tools and constructs, such as tags, to perform sophisticated functions.

Functions Of Java Virtual machine(JVM)


A Java Virtual Machine (JVM), originally developed by Sun Microsystems, is a
virtual machine that executes Java bytecode. This code is most often generated by
Java language compilers, although the JVM has also been targeted by compilers of
other languages.
The JVM is a crucial component of the Java Platform. The availability of JVMs on
many types of hardware and software platforms enables Java to function both as
middleware and a platform in its own right. Hence the expression "Write once, run
anywhere."
Starting with J2SE 5.0, changes to the JVM specification have been developed under
the Java Community Process as JSR 924[1]. As of 2006, changes to specification to
support changes proposed to the class file format (JSR 202[2]) are being done as a
maintenance release of JSR 924. The specification for the JVM is published in book
form[3], known as "blue book". The preface states:
We intend that this specification should sufficiently document the Java Virtual
Machine to make possible compatible clean-room implementations. Sun provides tests
which verify the proper operation of implementations of the Java Virtual Machine.
Kaffe is an example of a clean-room Java implementation. Sun retains control over
the Java trademark, which it uses to certify implementation suites as fully compatible
with Sun's specification.
Contents
1 Execution environment
1.1 Bytecode verifier
1.2 Bytecodes
1.3 Secure execution of remote code
2 References
3 See also
4 External links

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

MACHINE LANGUAGE CONSISTS of very simple instructions that can be


executed directly by the CPU of a computer. Almost all programs, though, are written
in high-level programming languages such as Java, Pascal, or C++. A program written
in a high-level language cannot be run directly on any computer. First, it has to be
translated into machine language. This translation can be done by a program called a
compiler. A compiler takes a high-level-language program and translates it into an
executable machine-language program. Once the translation is done, the machine-
language program can be run any number of times, but of course it can only be run on
one type of computer (since each type of computer has its own individual machine
language). If the program is to run on another type of computer it has to be re-
translated, using a different compiler, into the appropriate machine language.
There is an alternative to compiling a high-level language program. Instead of using a
compiler, which translates the program all at once, you can use an interpreter, which
translates it instruction-by-instruction, as necessary. An interpreter is a program that
acts much like a CPU, with a kind of fetch-and-execute cycle. In order to execute a
program, the interpreter runs in a loop in which it repeatedly reads one instruction
from the program, decides what is necessary to carry out that instruction, and then
performs the appropriate machine-language commands to do so.
One use of interpreters is to execute high-level language programs. For example, the
programming language Lisp is usually executed by an interpreter rather than a
compiler. However, interpreters have another purpose: they can let you use a
machine-language program meant for one type of computer on a completely different
type of computer. For example, there is a program called "Virtual PC" that runs on
Macintosh computers. Virtual PC is an interpreter that executes machine-language
programs written for IBM-PC-clone computers. If you run Virtual PC on your
Macintosh, you can run any PC program, including programs written for Windows.
(Unfortunately, a PC program will run much more slowly than it would on an actual
IBM clone. The problem is that Virtual PC executes several Macintosh machine-
language instructions for each PC machine-language instruction in the program it is
interpreting. Compiled programs are inherently faster than interpreted programs.)

The designers of Java chose to use a combination of compilation and interpretation.


Programs written in Java are compiled into machine language, but it is a machine
language for a computer that doesn't really exist. This so-called "virtual" computer is
known as the Java virtual machine. The machine language for the Java virtual
machine is called Java bytecode. There is no reason why Java bytecode could not be
used as the machine language of a real computer, rather than a virtual computer. In
fact, Sun Microsystems -- the originators of Java -- have developed CPU's that run
Java bytecode as their machine language.
However, one of the main selling points of Java is that it can actually be used on any
computer. All that the computer needs is an interpreter for Java bytecode. Such an
interpreter simulates the Java virtual machine in the same way that Virtual PC
simulates a PC computer.
Of course, a different Jave bytecode interpreter is needed for each type of computer,
but once a computer has a Java bytecode interpreter, it can run any Java bytecode
program. And the same Java bytecode program can be run on any computer that has
such an interpreter. This is one of the essential features of Java: the same compiled
program can be run on many different types of computers.

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

Java allows the creating of user-defined types . A user-defined types is created by


defining a class . For example, by defining a class classed Foo, we introduce an new
``type'' that can be used to declare a variable like this:
Foo f;
In Java, every variable that is not one of the primitive types is a reference type . Such
a variable can be thought of as a reference to (or a pointer to ) an object of the
appropriate type. For example, the variable f defined above is a reference to an object
instance of the class Foo.
In Java, class instances must be explicitly created. An instance of a class is created
using the new operator like this:
f = new Foo ();
If we follow this with an assignment statement such as
Foo g = f;
then both f and g refer to the same object! Note that this is very different from what
happens when you assign one primitive type to another.
A comparison of the the form
if (f == g)
{ /* ... */ }
tests whether the f and g refer to the same object instances. If f and g refer to distinct
object instances that happen to be equal, the test still fails. To test whether two distinct
object instances are equal, it is necessary to invoke the equals method like this:
if (f.equals(g))
{ /* ... */ }

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.

Class Members: Fields and Methods


A class groups a set of values and a set of operations. The values and the operations of
a class are called its members. Fields implement the values and methods implement
the operations.
Suppose we wish to define a class to represent complex numbers . The Complex class
definition shown in Program illustrates how this can be done. Two fields, real and
imag, are declared. These represent the real and imaginary parts of a complex number
(respectively). Program also defines two methods, setReal and setImag, which can
be used to assign values to the real and imaginary parts of a complex number
(respectively).

Program: Complex class fields and methods.


Every object instance of the Complex class contains its own fields. Consider the
following variable declarations:
Complex c = new Complex ();
Complex d = new Complex ();
Both c and d refer to distinct instances of the Complex class. Therefore, each of them
has its own real and imag field. The fields of an object are accessed using the dot
operator. For example, c.real refers to the real field of c and d.imag refers to the imag
field of d.
Program also defines the methods setReal and setImag. In general, a method
performs some operation on an instance of the class. Again, the dot operator is used to
specify the object on which the operation is performed. For example, c.SetReal(1.0)
invokes the setReal method on c and d.toString() invokes the toString method on d.

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.

The No-Arg Constructor


The constructor which takes no arguments is called the no-arg constructor . For
example, the no-arg constructor is invoked when a variable is declared like this:
Complex c = new Complex ();
If there are no constructors defined in a Java class, the Java compiler provides a
default no-arg constructor . The default no-arg constructor does nothing. The fields
simply the retain their initial, default values.
Program: Complex constructors.
Program gives an implementation for the no-arg constructor. of the Complex class
(lines 12-13). This constructor simply invokes the method called this. In Java one
constructor can invoke another constructor by calling the this method as its first
executable statement. In this case, the no-arg constructor invokes the two-arg
constructor to set both real and imag fields to zero.

Accessors and Mutators


An accessor is a method that accesses the contents of an object but does not modify
that object. In the simplest case, an accessor just returns the value of one of the fields.
In general, an accessor performs some computation using the fields as long as that
computation does not modify any of the fields.
Program defines the five accessor methods of the Complex class--getReal, getImag,
getR, getTheta, and toString. The getReal and getImag methods just return the values
the real and imaginary parts of a complex number. The getR and getTheta methods
return the polar coordinates of a complex number. Finally, the toString method returns
a String representation of a complex number.
Program: Complex class accessor methods.
By defining suitable accessors, it is possible to hide the implementation of the class
from the user of that class. Consider the following statements:
System.out.println (c.real);
System.out.println (c.getReal ());
The first statement depends on the implementation of the Complex class. If we change
the implementation of the class from the one given (which uses rectangular
coordinates) to one that uses polar coordinates, then the first statement above must
also be changed. On the other hand, the second statement does not need to be
modified, provided we reimplement the getReal method when we switch to polar
coordinates.

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.

Member Access Control

Every member of a class, be it a field or a method, has an access control attribute


which affects the manner in which that member can be accessed. The members of a
class can be private, public or protected. For example, the fields real and imag
declared in Program are both private. Private members can be used only by
methods of the class in which the member is declared.
On the other hand, public members of a class can be used by any method in any class.
All of the methods defined in Programs , , and all declared to be public.
In effect, the public part of a class defines the interface to that class and the private
part of the class encapsulates the implementation of that class. By making the
implementation of a class private, we ensure that the code which uses the class
depends only on the interface and not on the implementation of the class.
Furthermore, we can modify the implementation of the class without affecting the
code of the user of that class.
Protected members are similar to private members. That is, they can be used by
methods of the class in which the member is declared. In addition, protected members
can also be used by methods of all the classes derived from the class in which the
member is declared. The protected category is discussed again in Section .
Java introduces the notion of a package . A Java package is a collection of related
classes. Unless declared otherwise, the members of a class are accessible only by the
methods of classes in the same package. In this text, we do not use packages
explicitly. For convenience, you should consider all the classes discussed in this book
to be elements of the same package.

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.

Static Inner Classes


Non-Static Inner Classes

Static Inner Classes


Consider the following Java code fragment:
public class A
{
int y;

public static class B


{
int x;

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

Inheritance and Polymorphism

Derivation and Inheritance


Polymorphism
Multiple Inheritance
Run-Time Type Information and Casts

Derivation and Inheritance


This section reviews the concept of a derived class. Derived classes are an extremely
useful feature of Java because they allow the programmer to define new classes by
extending existing classes. By using derived classes, the programmer can exploit the
commonalities that exist among the classes in a program. Different classes can share
values, operations, and interfaces.
Derivation is the definition of a new class by extending an existing class. The new
class is called the derived class and the existing class from which it is derived is
called the base class . In Java there can be only one base class (single inheritance ).
Consider the Person class defined in Program and the Parent class defined in
Program . Because parents are people too, the Parent class is derived from the
Person class. Derivation in Java is indicated using the keyword extends.

Program: Person class.

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.

Program: GraphicsPrimitives interface.


The draw method is invoked in order to draw a graphical object. The erase method is
invoked in order to erase a graphical object. The moveTo method is used to move an
object to a specified position in the drawing. The argument of the moveTo method is a
Point. Program defines the Point class which represents a position in a drawing.

Program: Point class.

Abstract Methods and Abstract Classes


Consider the GraphicalObject class defined in Program . The GraphicalObject class
implements the GraphicsPrimitives interface.
Program: GraphicalObject class.
The GraphicalObject class has a single field, center, which is a Point that represents
the position in a drawing of the center-point of the graphical object. The constructor
for the GraphicalObject class takes as its argument a Point and initializes the center
field accordingly.
Program shows a possible implementation for the erase method: In this case we
assume that the image is drawn using an imaginary pen. Assuming that we know how
to draw a graphical object, we can erase the object by changing the color of the pen so
that it matches the background color and then redrawing the object.
Once we can erase an object as well as draw it, then moving it is easy. Just erase the
object, change its center point, and then draw it again. This is how the moveTo
method shown in Program is implemented.
We have seen that the GraphicalObject class provides implementations for the erase
and moveTo methods. However, the GraphicalObject class does not provide an
implementation for the draw method. Instead, the method is declared to be abstract.
We do this because until we know what kind of object it is, we cannot possibly know
how to draw it!
Consider the Circle class defined in Program . The Circle class extends the
GraphicalObject class. Therefore, it inherits the field center and the methods erase and
moveTo. The Circle class adds an additional field, radius, and it overrides the draw
method. The body of the draw method is not shown in Program . However, we shall
assume that it draws a circle with the given radius and center point.
Program: Circle class.
Using the Circle class defined in Program we can write code like this:
Circle c = new Circle (new Point (0, 0), 5);
c.draw ();
c.moveTo (new Point (10, 10));
c.erase ();
This code sequence declares a circle object with its center initially at position (0,0)
and radius 5. The circle is then drawn, moved to (10,10), and then erased.
Program defines the Rectangle class and Program defines the Square class. The
Rectangle class also extends the GraphicalObject class. Therefore, it inherits the field
center and the methods erase and moveTo. The Rectangle class adds two additional
fields, height and width, and it overrides the draw method. The body of the draw
method is not shown in Program . However, we shall assume that it draws a
rectangle with the given dimensions and center point.

Program: Rectangle class.


The Square class extends the Rectangle class. No new fields or methods are declared--
those inherited from GraphicalObject or from Rectangle are sufficient. The
constructor simply arranges to make sure that the height and width of a square are
equal!

Program: Square class.

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 CONSISTS OF INSTRUCTIONS for performing some task,


chunked together and given a name. "Chunking" allows you to deal with a potentially
very complicated task as a single concept. Instead of worrying about the many, many
steps that the computer might have to go though to perform that task, you just need to
remember the name of the subroutine. Whenever you want your program to perform
the task, you just call the subroutine. Subroutines are a major tool for dealing with
complexity.

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:

The interface of a black box should be fairly straightforward, well-defined, and


easy to understand.

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.

In fact, it should be possible to change the implementation, as long as the behavior of


the box, as seen from the outside, remains unchanged. For example, when the insides
of TV sets went from using vacuum tubes to using transistors, the users of the sets
didn't even need to know about it -- or even know what it means. Similarly, it should
be possible to rewrite the inside of a subroutine, to use more efficient code, for
example, without affecting the programs that use that subroutine.

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.

Static Subroutines and Static Variables

A subroutine definition in Java takes the form:

modifiers return-type subroutine-name ( parameter-list ) {


statements
}

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

public void changeChannel(int channelNum) {...}

This declaration specifies that changeChannel() has a parameter named channelNum


of type int. However, channelNum does not yet have any particular value. A value for
channelNum is provided when the subroutine is called; for example:
changeChannel(17);

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".

Parameters are covered in more detail in the next section.

Here are a few examples of subroutine definitions, leaving out the statements that
define what the subroutines do:

public static void playGame() {


// "public" and "static" are modifiers; "void" is the
// return-type; "playGame" is the subroutine-name;
// the parameter-list is empty
. . . // statements that define what playGame does go
here
}

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

public static void main(String[] args) { .... }

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().

More generally, a subroutine call statement takes the form

subroutine-name(parameters);

if the subroutine that is being called is in the same class, or

class-name.subroutine-name(parameters);

if the subroutine is a static subroutine defined elsewhere, in a different class. (Non-


static methods belong to objects rather than classes, and they are called using object
names instead of class names. More on that later.) Note that the parameter list can be
empty, as in the playGame() example, but the parentheses must be there even if there
is nothing between them.

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:

Pick a random number


while the game is not over:
Get the user's guess
Tell the user whether the guess is high, low, or correct.
The test for whether the game is over is complicated, since the game ends if either the
user makes a correct guess or the number of guesses is six. As in many cases, the
easiest thing to do is to use a "while (true)" loop and use break to end the loop
whenever we find a reason to do so. Also, if we are going to end the game after six
guesses, we'll have to keep track of the number of guesses that the user has made.
Filling out the algorithm gives:

Let computersNumber be a random number between 1 and 100


Let guessCount = 0
while (true):
Get the user's guess
Count the guess by adding 1 to guess count
if the user's guess equals computersNumber:
Tell the user he won
break out of the loop
if the number of guesses is 6:
Tell the user he lost
break out of the loop
if the user's guess is less than computersNumber:
Tell the user the guess was low
else if the user's guess is higher than computersNumber:
Tell the user the guess was high

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.

static void playGame() {


int computersNumber; // A random number picked by the
computer.
int usersGuess; // A number entered by user as a
guess.
int guessCount; // Number of guesses the user has
made.
computersNumber = (int)(100 * Math.random()) + 1;
// The value assigned to computersNumber is a
randomly
// chosen integer between 1 and 100, inclusive.
guessCount = 0;
TextIO.putln();
TextIO.put("What is your first guess? ");
while (true) {
usersGuess = TextIO.getInt(); // get the user's guess
guessCount++;
if (usersGuess == computersNumber) {
TextIO.putln("You got it in " + guessCount
+ " guesses! My number was " +
computersNumber);
break; // the game is over; the user has won
}
if (guessCount == 6) {
TextIO.putln("You didn't get the number in 6
guesses.");
TextIO.putln("You lose. My number was " +
computersNumber);
break; // the game is over; the user has lost
}
// If we get to this point, the game continues.
// Tell the user if the guess was too high or too low.
if (usersGuess < computersNumber)
TextIO.put("That's too low. Try again: ");
else if (usersGuess > computersNumber)
TextIO.put("That's too high. Try again: ");
}
TextIO.putln();
} // end of playGame()

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).

public class GuessingGame {

public static void main(String[] args) {


TextIO.putln("Let's play a game. I'll pick a number
between");
TextIO.putln("1 and 100, and you try to guess it.");
boolean playAgain;
do {
playGame(); // call subroutine to play one game
TextIO.put("Would you like to play again? ");
playAgain = TextIO.getlnBoolean();
} while (playAgain);
TextIO.putln("Thanks for playing. Goodbye.");
} // end of main()

static void playGame() {


int computersNumber; // A random number picked by the
computer.
int usersGuess; // A number entered by user as a
guess.
int guessCount; // Number of guesses the user has
made.
computersNumber = (int)(100 * Math.random()) + 1;
// The value assigned to computersNumber is a
randomly
// chosen integer between 1 and 100,
inclusive.
guessCount = 0;
TextIO.putln();
TextIO.put("What is your first guess? ");
while (true) {
usersGuess = TextIO.getInt(); // get the user's guess
guessCount++;
if (usersGuess == computersNumber) {
TextIO.putln("You got it in " + guessCount
+ " guesses! My number was " +
computersNumber);
break; // the game is over; the user has won
}
if (guessCount == 6) {
TextIO.putln("You didn't get the number in 6
guesses.");
TextIO.putln("You lose. My number was " +
computersNumber);
break; // the game is over; the user has lost
}
// If we get to this point, the game continues.
// Tell the user if the guess was too high or too low.
if (usersGuess < computersNumber)
TextIO.put("That's too low. Try again: ");
else if (usersGuess > computersNumber)
TextIO.put("That's too high. Try again: ");
}
TextIO.putln();
} // end of playGame()

} // end of class GuessingGame

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.

You can try out a simulation of this program here:

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:

static int numberOfPlayers;


static String usersName;
static double velocity, time;

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.

Here's a revised version of GuessingGame.java that includes the gamesWon variable.


The changes from the above version are shown in red:

public class GuessingGame2 {

static int gamesWon; // The number of games won by


// the user.
public static void main(String[] args) {
gamesWon = 0; // This is actually redundant, since 0 is
// the default initial
value.
TextIO.putln("Let's play a game. I'll pick a number
between");
TextIO.putln("1 and 100, and you try to guess it.");
boolean playAgain;
do {
playGame(); // call subroutine to play one game
TextIO.put("Would you like to play again? ");
playAgain = TextIO.getlnBoolean();
} while (playAgain);
TextIO.putln();
TextIO.putln("You won " + gamesWon + " games.");
TextIO.putln("Thanks for playing. Goodbye.");
} // end of main()

static void playGame() {


int computersNumber; // A random number picked by the
computer.
int usersGuess; // A number entered by user as a
guess.
int guessCount; // Number of guesses the user has
made.
computersNumber = (int)(100 * Math.random()) + 1;
// The value assigned to computersNumber is a
randomly
// chosen integer between 1 and 100,
inclusive.
guessCount = 0;
TextIO.putln();
TextIO.put("What is your first guess? ");
while (true) {
usersGuess = TextIO.getInt(); // get the user's guess
guessCount++;
if (usersGuess == computersNumber) {
TextIO.putln("You got it in " + guessCount
+ " guesses! My number was " +
computersNumber);
gamesWon++; // Count this game by incrementing
gamesWon.
break; // the game is over; the user has won
}
if (guessCount == 6) {
TextIO.putln("You didn't get the number in 6
guesses.");
TextIO.putln("You lose. My number was " +
computersNumber);
break; // the game is over; the user has lost
}
// If we get to this point, the game continues.
// Tell the user if the guess was too high or too low.
if (usersGuess < computersNumber)
TextIO.put("That's too low. Try again: ");
else if (usersGuess > computersNumber)
TextIO.put("That's too high. Try again: ");
}
TextIO.putln();
} // end of playGame()
} // end of class GuessingGame2

Parameters

IF A SUBROUTINE IS A BLACK BOX, then a parameter provides a mechanism for


passing information from the outside world into the box. Parameters are part of the
interface of a subroutine. They allow you to customize the behavior of a subroutine to
adapt it to a particular situation.

As an analogy, consider a thermostat -- a black box whose task it is to keep your


house at a certain temperature. The thermostat has a parameter, namely the dial that is
used to set the desired temperature. The thermostat always performs the same task:
maintaining a constant temperature. However, the exact task that it performs -- that is,
which temperature it maintains -- is customized by the setting on its dial.

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:

static void Print3NSequence(int startingValue) {

// Prints a 3N+1 sequence to standard output, using


// startingValue as the initial value of N. It also
// prints the number of terms in the sequence.
// The value of the parameter, startingValue, must
// be a positive integer.

int N; // One of the terms in the sequence.


int count; // The number of terms.

N = startingValue; // The first term is whatever value


// is passed to the subroutine as
// a parameter.

int count = 1; // We have one term, the starting value,


so far.

TextIO.putln("The 3N+1 sequence starting from " + N);


TextIO.putln();
TextIO.putln(N); // print initial term of sequence

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:

public static void main(String[] args) {


TextIO.putln("This program will print out 3N+1
sequences");
TextIO.putln("for starting values that you specify.");
TextIO.putln();
int K; // Input from user; loop ends when K < 0.
do {
TextIO.putln("Enter a starting value;")
TextIO.put("To end the program, enter 0: ");
K = TextIO.getInt(); // get starting value from user
if (K > 0) // print sequence, but only if K is > 0
Print3NSequence(K);
} while (K > 0); // continue only if K > 0
} // end main()

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

static void doTask(int N, double x, boolean test) {


// statements to perform the task go here
}

This subroutine might be called with the statement

doTask(17, Math.sqrt(z+1), z >= 10);

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
}

(There are a few technical differences between this and


"doTask(17,Math.sqrt(z+1),z>=10);" -- besides the amount of typing -- because
of questions about scope of variables and what happens when several variables or
parameters have the same name.)

Beginning programming students often find parameters to be surprisingly confusing.


Calling a subroutine that already exists is not a problem -- the idea of providing
information to the subroutine in a parameter is clear enough. Writing the subroutine
definition is another matter. A common mistake is to assign values to the formal
parameters at the beginning of the subroutine, or to ask the user to input their values.
This represents a fundamental misunderstanding. When the statements in the
subroutine are executed, the formal parameters will already have values. The values
come from the subroutine call statement. Remember that a subroutine is not
independent. It is called by some other routine, and it is the calling routine's
responsibility to provide appropriate values for the parameters.
In order to call a subroutine legally, you need to know its name, you need to know
how many formal parameters it has, and you need to know the type of each parameter.
This information is called the subroutine's signature. The signature of the subroutine
doTask can be expressed as as: doTask(int,double,boolean). Note that the signature
does not include the names of the parameters; in fact, if you just want to use the
subroutine, you don't even need to know what the formal parameter names are, so the
names are not part of the interface.

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:

putln(int) putln(int,int) putln(double)


putln(String) putln(String,int) putln(char)
putln(boolean) putln(boolean,int) putln()

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:

int getln() { ... }


double getln() { ... }

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().

Let's do a few examples of writing small subroutines to perform assigned tasks. Of


course, this is only one side of programming with subroutines. The task performed by
a subroutine is always a subtask in a larger program. The art of designing those
programs -- of deciding how to break them up into subtasks -- is the other side of
programming with subroutines. We'll return to the question of program design in
Section 6.
As a first example, let's write a subroutine to compute and print out all the divisors of
a given positive integer. The integer will be a parameter to the subroutine.

Remember that the format of any subroutine is

modifiers return-type subroutine-name ( parameter-list ) {


statements
}

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

static void printDivisors( int N ) {


statements
}

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:

static void printDivisors( int N ) {


// Print all the divisors of N.
// We assume that N is a positive integer.
int D; // One of the possible divisors of N.
System.out.println("The divisors of " + N + " are:");
for ( D = 1; D <= N; D++ ) {
if ( N % D == 0 )
System.out.println(D);
}
}

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.

As a second short example, consider the assignment: Write a subroutine named


printRow. It should have a parameter ch of type char and a parameter N of type int.
The subroutine should print out a line of text containing N copies of the character ch.

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

static void printRow( char ch, int N ) {


// Write one line of output containing N copies of
the
// character ch. If N <= 0, an empty line is output.
int i; // Loop-control variable for counting off the
copies.
for ( i = 1; i <= N; i++ ) {
System.out.print( ch );
}
System.out.println();
}

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:

static void printRowsFromString( String str ) {


// For each character in str, write a line of output
// containing 25 copies of that character.
int i; // Loop-control variable for counting off the
chars.
for ( i = 0; i < str.length(); i++ ) {
printRow( str.charAt(i), 25 );
}
}

We could use printRowsFromString in a main() routine such as

public static void main(String[] args) {


String inputLine; // Line of text input by user.
TextIO.put("Enter a line of text: ");
inputLine = TextIO.getln();
TextIO.putln();
printRowsFromString( inputLine );
}

Of course, the three routines, main(), printRowsFromString(), and printRow(),


would have to be collected together inside the same class.The program is rather
useless, but it does demonstrate the use of subroutines. You'll find the program in the
file RowsOfChars.java, if you want to take a look. Here's an applet that simulates the
program:
I'll finish this section on parameters by noting that we now have three different sorts
of variables that can be used inside a subroutine: local variables defined in the
subroutine, formal parameter names, and static member variables that are defined
outside the subroutine but inside the same class as the subroutine.

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

A SUBROUTINE THAT RETURNS A VALUE is called a function. A given


function can only return a value of a specified type, called the return type of the
function. A function call generally occurs in a position where the computer is
expecting to find a value, such as the right side of an assignment statement, as an
actual parameter in a subroutine call, or in the middle of some larger expression. A
boolean-valued function can even be used as the test condition in an if, while, or
do..while statement.

(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.

For example, consider the function definition

static double pythagorus(double x, double y) {


// Computes the length of the hypotenuse of a right
// triangle, where the sides of the triangle are x and
y.
return Math.sqrt(x*x + y*y);
}

Suppose the computer executes the statement "totalLength = 17 +


pythagorus(12,5);". When it gets to the term pythagorus(12,5), it assigns the
actual parameters 12 and 5 to the formal parameters x and y in the function. In the
body of the function, it evaluates Math.sqrt(12.0*12.0 + 5.0*5.0), which works
out to 13.0. This value is returned, so it replaces the function call in the statement
"totalLength = 17 + pythagorus(12,5);". The return value is added to 17, and
the result, 30.0, is stored in the variable, totalLength. The effect is the same as if the
statement had been "totalLength = 17 + 13.0;".

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:

static int nextN(int currentN) {


if (currentN % 2 == 1) // test if current N is odd
return 3*currentN + 1; // if so, return this value
else
return currentN / 2; // if not, return this instead
}

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:

static int nextN(int currentN) {


int answer; // answer will be the value returned
if (currentN % 2 == 1) // test if current N is odd
answer = 3*currentN+1; // if so, this is the answer
else
answer = currentN / 2; // if not, this is the answer
return answer; // (Don't forget to return the answer!)
}

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:

static void Print3NSequence(int startingValue) {

// Prints a 3N+1 sequence to standard output, using


// startingValue as the initial value of N. It also
// prints the number of terms in the sequence.
// The value of startingValue must be a positive
integer.

int N; // One of the terms in the sequence.


int count; // The number of terms found.

N = startingValue; // Start the sequence with


startingValue;
count = 1;

TextIO.putln("The 3N+1 sequence starting from " + N);


TextIO.putln();
TextIO.putln(N); // print initial term of sequence

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:

static char letterGrade(int numGrade) {

// Returns the letter grade corresponding to


// the numerical grade, numGrade.

if (numGrade >= 90)


return 'A'; // 90 or above gets an A
else if (numGrade >= 80)
return 'B'; // 80 to 89 gets a B
else if (numGrade >= 65)
return 'C'; // 65 to 79 gets a C
else if (numGrade >= 50)
return 'D'; // 50 to 64 gets a D
else
return 'F'; // anything else gets an F

} // end of function letterGrade()

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:

static boolean isPrime(int N) {

// Returns true if N is a prime number. A prime number


// is an integer greater than 1 that is not divisible
// by any positive integer, except itself and 1. If N
has
// any divisor, D, in the range 1 < D < N, then it
// has a divisor in the range 2 to Math.sqrt(N), namely
// either D itself or N/D. So we only test possible
// divisors from 2 to Math.sqrt(N).

int divisor; // A number we will test to see whether it


// evenly divides N.

if (N <= 1)
return false; // No number <= 1 is a prime.

int maxToTry = (int)Math.sqrt(N);


// We will try to divide N by numbers between
// 2 and maxToTry; If N is not evenly divisible
// by any of these numbers, then N is prime.
// (Note that since Math.sqrt(N) is defined to
// return a value of type double, the value
// must be typecast to type int before it can
// be assigned to maxToTry.)

for (divisor = 2; divisor <= maxToTry; divisor++) {


if ( N % divisor == 0 ) // Test if divisor evenly
divides N.
return false; // If so, we know N is not
prime.
// No need to continue
testing.
}

// If we get to this point, N must be prime. Otherwise,


// the function would already have been terminated by
// a return statement in the previous for loop.

return true; // Yes, N is prime.

} // end of function isPrime()

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.

static String reverse(String str) {


// Returns a reversed copy of str.
String copy; // The reversed copy.
int i; // One of the positions in str,
// from str.length() - 1 down to 0.
copy = ""; // Start with an empty string.
for ( i = str.length() - 1; i >= 0; i-- ) {
// Append i-th char of str to copy.
copy = copy + str.charAt(i);
}
return copy;
}

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.

public class ThreeN2 {

/*
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.
*/

public static void main(String[] args) {

TextIO.putln("This program will print out 3N+1


sequences");
TextIO.putln("for starting values that you specify.");
TextIO.putln();

int K; // Starting point for sequence, specified by the


user.
do {
TextIO.putln("Enter a starting value;");
TextIO.put("To end the program, enter 0: ");
K = TextIO.getInt(); // get starting value from user
if (K > 0) // print sequence, but only if K
is > 0
Print3NSequence(K);
} while (K > 0); // continue only if K > 0

} // end main()

static void Print3NSequence(int startingValue) {

// Prints a 3N+1 sequence to standard output, using


// startingValue as the initial value of N. Terms are
// printed five to a line. The subroutine also
// prints the number of terms in the sequence.
// The value of startingValue must be a positive
integer.

int N; // One of the terms in the sequence.


int count; // The number of terms found.
int onLine; // The number of terms that have been output
// so far on the current line.

N = startingValue; // Start the sequence with


startingValue;
count = 1; // We have one term so far.

TextIO.putln("The 3N+1 sequence starting from " + N);


TextIO.putln();
TextIO.put(N, 8); // Print initial term, using 8
characters.
onLine = 1; // There's now 1 term on current
output line.

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.
}

TextIO.putln(); // end current line of output


TextIO.putln(); // and then add a blank line
TextIO.putln("There were " + count + " terms in the
sequence.");

} // end of Print3NSequence()

static int nextN(int currentN) {


// Computes and returns the next term in a 3N+1
sequence,
// given that the current term is currentN.
if (currentN % 2 == 1)
return 3 * currentN + 1;
else
return currentN / 2;
} // end of nextN()

} // end of class ThreeN2

You should read this program carefully and try to understand how it works. Here is an
applet version for you to try:

Toolboxes, API's, and Packages

AS COMPUTERS AND THEIR USER INTERFACES have become easier to use,


they have also become more complex for programmers to deal with. You can write
programs for a simple console-style user interface using just a few subroutines that
write output to the console and read the user's typed replies. A modern graphical user
interface, with windows, buttons, scroll bars, menus, text-input boxes, and so on,
might make things easier for the user. But it forces the programmer to cope with a
hugely expanded array of possibilities. The programmer sees this increased
complexity in the form of great numbers of subroutines that are provided for
managing the user interface, as well as for other purposes.

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.

The Java programming language is supplemented by a large, standard API. You've


seen part of this API already, in the form of mathematical subroutines such as
Math.sqrt(), the String data type and its associated routines, and the
System.out.print() routines. The standard Java API includes routines for working
with graphical user interfaces, for network communication, for reading and writing
files, and more. It's tempting to think of these routines as being built into the Java
language, but they are technically subroutines that have been written and made
available for use in Java programs.

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.

It might be helpful to look at a graphical representation of the levels of nesting in the


java package, its sub-packages, the classes in those sub-packages, and the
subroutines in those classes. This is not a complete picture, since it shows only a few
of the many items in each element:
Let's say that you want to use the class java.awt.Color in a program that you are
writing. One way to do this is to use the full name of the class. For example, you
could say

java.awt.Color rectColor;

to declare a variable named rectColor whose type is java.awt.Color. Of course,


this can get tiresome, so Java makes it possible to avoid using the full names of
classes. If you put

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.

Although we won't be creating packages explicitly, every class is actually part of a


package. If a class is not specifically placed in a package, then it is put in something
called the default package, which has no name. All the examples that you see in these
notes are in the default package.

More on Program Design


Preconditions and Postconditions

When working with subroutines as building blocks, it is important to be clear about


how a subroutine interacts with the rest of the program. This interaction is specified
by the contract of the subroutine, as discussed in Section 1. A convenient way to
express the contract of a subroutine is in terms of preconditions and postconditions.

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.

A postcondition of a subroutine represents the other side of the contract. It is


something that will be true after the subroutine has run (assuming that its
preconditions were met -- and that there are no bugs in the subroutine). The
postcondition of the function Math.sqrt() is that the square of the value that is
returned by this function is equal to the parameter that is provided when the
subroutine is called. Of course, this will only be true if the preconditiion -- that the
parameter is greater than or equal to zero -- is met. A postcondition of the built-in
subroutine System.out.print() is that the value of the parameter has been
displayed on the screen.

Preconditions most often give restrictions on the acceptable values of parameters, as


in the example of Math.sqrt(x). However, they can also refer to global variables that
are used in the subroutine. The postcondition of a subroutine specifies the task that it
performs. For a function, the postcondition should specify the value that the function
returns.

Subroutines are often described by comments that explicitly specify their


preconditions and postconditions. When you are given a pre-written subroutine, a
statement of its preconditions and postcondtions tells you how to use it and what it
does. When you are assigned to write a subroutine, the preconditions and
postconditions give you an exact specification of what the subroutine is expected to
do. I will use this approach in the example that constitutes the rest of this section. I
will also use it occasionally later in the book, although I will generally be less formal
in my commenting style.

Preconditions and postconditions will be discussed more thoroughly in Chapter 9,


which deals with techniques for writing correct and robust programs.
A Design Example

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:

void Mosaic.open(int rows, int cols, int w, int h);


Precondition: The parameters rows, cols, w, and h are
greater than zero.
Postcondition: A "mosaic" window is opened on the screen
that can
display rows and columns of colored
rectangles.
Each rectangle is w pixels wide and h pixels
high.
The number of rows is given by the first
parameter and the number of columns by the
second.
Initially, all the rectangles are black.
Note: The rows are numbered from 0 to rows - 1, and the
columns
are numbered from 0 to cols - 1.

void Mosaic.setColor(int row, int col, int r, int g, int b);


Precondition: row and col are in the valid ranges of row
numbers and
column numbers. r, g, and b are in the range
0 to 255.
Also, the mosaic window should be open.
Postcondition: The color of the rectangle in row number row
and column
number col has been set to the color
specified by
r, g, and b. r gives the amount of red in
the color
with 0 representing no red and 255
representing the
maximum possible amount of red. The larger
the value
of r, the more red in the color. g and b
work
similarly for the green and blue color
components.

int Mosaic.getRed(int row, int col);


int Mosaic.getBlue(int row, int col);
int Mosaic.getGreen(int row, int col);
Precondition: row and col are in the valid ranges of row
numbers
and column numbers. Also, the mosaic window
should
be open.
Postcondition: Returns an int value that represents one of
the
three color components of the rectangle in
row
number row and column number col. The return
value
is in the range 0 to 255. (Mosaic.getRed()
returns
the red component of the rectangle,
Mosaic.getGreen()
the green component, and Mosaic.getBlue() the
blue
component.)

void Mosaic.delay(int milliseconds);


Precondition: milliseconds is a positive integer.
Postcondition: The program has paused for at least the
number
of milliseconds given by the parameter, where
one second is equal to 1000 milliseconds.
Note: This can be used to insert a time delay in the
program (to
regulate the speed at which the colors are changed,
for
example).

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

Open a Mosaic window


Fill window with random colors;
Move around, changing squares at random.

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:

Open a Mosaic window


Fill window with random colors;
Set the current position to the middle square in the window;
As long as the mosaic window is open:
Randomly change color of current square;
Move current position up, down, left, or right, at random;

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:


For each column:
set the square in that row and column to a random color

"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:

static void fillWithRandomColors() {


for (int row = 0; row < 10; row++)
for (int column = 0; column < 20; column++)
changeToRandomColor(row,column);
}

Turning to the changeToRandomColor subroutine, we already have a method,


Mosaic.setColor(row,col,r,g,b), that can be used to change the color of a
square. If we want a random color, we just have to choose random values for r, g, and
b. According to the precondition of the Mosaic.setColor() subroutine, these random
values must be integers in the range from 0 to 255. A formula for randomly selecting
such an integer is "(int)(256*Math.random())". So the random color subroutine
becomes:

static void changeToRandomColor(int rowNum, int colNum) {


int red = (int)(256*Math.random());
int green = (int)(256*Math.random());
int blue = (int)(256*Math.random());
mosaic.setColor(rowNum,colNum,red,green,blue);
}

Finally, consider the randomMove subroutine, which is supposed to randomly move


the disturbance up, down, left, or right. To make a random choice among four
directions, we can choose a random integer in the range 0 to 3. If the integer is 0,
move in one direction; if it is 1, move in another direction; and so on. The position of
the disturbance is given by the variables currentRow and currentColumn. To "move
up" means to subtract 1 from currentRow. This leaves open the question of what to
do if currentRow becomes -1, which would put the disturbance above the window.
Rather than let this happen, I decide to move the disturbance to the opposite edge of
the applet by setting currentRow to 9. (Remember that the 10 rows are numbered
from 0 to 9.) Moving the disturbance down, left, or right is handled similarly. If we
use a switch statement to decide which direction to move, the code for randomMove
becomes:

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.

public class RandomMosaicWalk {

/*
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.
*/

static int currentRow; // row currently containing the


disturbance
static int currentColumn; // column currently containing
disturbance

public static void main(String[] args) {


// Main program creates the window, fills it with
// random colors, then moves the disturbance in
// a random walk around the window for as long as
// the window is open.
Mosaic.open(10,20,10,10);
fillWithRandomColors();
currentRow = 5; // start at center of window
currentColumn = 10;
while (Mosaic.isOpen()) {
changeToRandomColor(currentRow, currentColumn);
randomMove();
Mosaic.delay(20);
}
} // end of main()

static void fillWithRandomColors() {


// Precondition: The mosaic window is open.
// Postcondition: Each rectangle has been set to a
// random color
for (int row=0; row < 10; row++) {
for (int column=0; column < 20; column++) {
changeToRandomColor(row, column);
}
}
} // end of fillWithRandomColors()

static void changeToRandomColor(int rowNum, int colNum) {


// Precondition: rowNum and colNum are in the valid
range
// of row and column numbers.
// Postcondition: The rectangle in the specified row
and
// column has been changed to a random
color.
int red = (int)(256*Math.random()); // choose random
levels in range
int green = (int)(256*Math.random()); // 0 to 255
for red, green,
int blue = (int)(256*Math.random()); // and blue
color components
Mosaic.setColor(rowNum,colNum,red,green,blue);
} // end of changeToRandomColor()

static void randomMove() {


// Precondition: The global variables currentRow and
currentColumn
// specify a valid position in the
grid.
// Postcondition: currentRow or currentColumn is
changed to
// one of the neighboring positions in
the grid,
// up, down, left, or right from the
previous
// position. If this moves the
position outside
// the grid, then it is moved to the
opposite edge
// of the window.
int directionNum; // Randomly set to 0, 1, 2, or 3 to
choose direction.
directionNum = (int)(4*Math.random());
switch (directionNum) {
case 0: // move up
currentRow--;
if (currentRow < 0)
currentRow = 9;
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;
}
} // end of randomMove()

} // end of class RandomMosaicWalk


The Truth about Declarations

NAMES ARE FUNDAMENTAL TO PROGRAMMING, as I said a few chapters


ago. There are a lot of details involved in declaring and using names. I have been
avoiding some of those details. In this section, I'll reveal most of the truth (although
still not the full truth) about declaring and using variables in Java. The material under
the headings "Combining Initialization with Declaration" and "Named Constants and
the final Modifier" is particularly important, since I will be using it regularly in
future chapters.

Combining Initialization with Declaration

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,

int count; // Declare a variable named count.


count = 0; // Give count its initial value.

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

int count = 0; // Declare count and give it an initial


value.

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,

char firstInitial = 'D', secondInitial = 'E';

int x, y = 1; // OK, but only y has been initialized!

int N = 3, M = N+2; // OK, N is initialized


// before its value is used.

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:

for ( int i = 0; i < 10; i++ ) {


System.out.println(i);
}
Again, you should remember that this is simply an abbreviation for the following,
where I've added an extra pair of braces to show that i is considered to be local to the
for statement and no longer exists after the for loop ends:

{
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:

public class Bank {


static double interestRate = 0.05;
static int maxWithdrawal = 200;
.
. // More variables and subroutines.
.
}

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:

public class Bank {


static double interestRate;
interestRate = 0.05; // ILLEGAL:
. // Can't be outside a
subroutine!
.
.

Because of this, declarations of member variables often include initial values. As


mentioned in Section 2, if no initial value is provided for a member variable, then a
default initial value is used. For example, "static int count;" is equivalent to
"static int count = 0;".

Named Constants and the final Modifier

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

final static double interestRate = 0.05;

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

final static double INTEREST_RATE = 0.05;

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.

As an extended example, I will give a new version of the RandomMosaicWalk


program from the previous section. This version uses named constants to represent the
number of rows in the mosaic, the number of columns, and the size of each little
square. The three constants are declared as final static member variables with the
lines:

final static int ROWS = 30; // Number of rows in mosaic.


final static int COLUMNS = 30; // Number of columns in
mosaic.
final static int SQUARE_SIZE = 15; // Size of each square in
mosaic.

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

Mosaic.open(ROWS, COLUMNS, SQUARE_SIZE, SQUARE_SIZE);

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.

public class RandomMosaicWalk2 {

/*
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.
*/

final static int ROWS = 30; // Number of rows in


mosaic.
final static int COLUMNS = 30; // Number of columns in
mosaic.
final static int SQUARE_SIZE = 15; // Size of each square in
mosaic.

static int currentRow; // row currently containing the


disturbance
static int currentColumn; // column currently containing
disturbance

public static void main(String[] args) {


// Main program creates the window, fills it with
// random colors, then moves the disturbance in
// a random walk around the window.
Mosaic.open(ROWS, COLUMNS, SQUARE_SIZE, SQUARE_SIZE);
fillWithRandomColors();
currentRow = ROWS / 2; // start at center of window
currentColumn = COLUMNS / 2;
while (Mosaic.isOpen()) {
changeToRandomColor(currentRow, currentColumn);
randomMove();
Mosaic.delay(20);
}
} // end of main()

static void fillWithRandomColors() {


// Precondition: The mosaic window is open.
// Postcondition: Each rectangle has been set to a
// random color
for (int row=0; row < ROWS; row++) {
for (int column=0; column < COLUMNS; column++) {
changeToRandomColor(row, column);
}
}
} // end of fillWithRandomColors()

static void changeToRandomColor(int rowNum, int colNum) {


// Precondition: rowNum and colNum are in the valid
range
// of row and column numbers.
// Postcondition: The rectangle in the specified row
and
// column has been changed to a random
color.
int red = (int)(256*Math.random());
int green = (int)(256*Math.random());
int blue = (int)(256*Math.random());
Mosaic.setColor(rowNum,colNum,red,green,blue);
} // end of changeToRandomColor()

static void randomMove() {


// Precondition: The global variables currentRow and
currentColumn
// specify a valid position in the
grid.
// Postcondition: currentRow or currentColumn is
changed to
// one of the neighboring positions in
the grid,
// up, down, left, or right from the
previous
// position. (If this moves the
position outside
// the grid, then it is moved to the
opposite edge
// of the window.)
int directionNum; // Randomly set to 0, 1, 2, or 3
// to choose direction.
directionNum = (int)(4*Math.random());
switch (directionNum) {
case 0: // move up
currentRow--;
if (currentRow < 0)
currentRow = ROWS - 1;
break;
case 1: // move right
currentColumn++;
if (currentColumn >= COLUMNS)
currentColumn = 0;
break;
case 2: // move down
currentRow ++;
if (currentRow >= ROWS)
currentRow = 0;
break;
case 3: // move left
currentColumn--;
if (currentColumn < 0)
currentColumn = COLUMNS - 1;
break;
}
} // end of randomMove()

} // end of class RandomMosaicWalk2

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.

Naming and Scope Rules

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 static member subroutines, scope is straightforward. The scope of a static


subroutine is the entire source code of the class in which it is defined. That is, it is
possible to call the subroutine from any point in the class. It is even possible to call a
subroutine from within itself. This is an example of something called "recursion," a
fairly advanced topic that we will return to later.

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:

public class Game {


static int count; // member variable

static void playGame() {


int count; // local variable
.
. // Some statements to define playGame()
.
}

.
. // 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

static Insanity Insanity( Insanity Insanity ) { ... }

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

Blocks, Loops, and Branches

THE ABILITY OF A COMPUTER TO PERFORM complex tasks is built on just a


few ways of combining simple commands into control structures. In Java, there are
just six such structures -- and, in fact, just three of them would be enough to write
programs to perform any task. The six control structures are: the block, the while
loop, the do..while loop, the for loop, the if statement, and the switch statement. Each
of these structures is considered to be a single "statement," but each is in fact a
structured statement that can contain one or more other statements inside itself.

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.

Here are two examples of blocks:

{
System.out.print("The answer is ");
System.out.println(ans);
}

{ // This block exchanges the values of x and 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.
}

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:

int number; // The number to be printed.


number = 1; // Start with 1.
while ( number < 6 ) { // Keep going as long as number is <
6.
System.out.println(number);
number = number + 1; // Go on to the next number.
}
System.out.println("Done!");

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:

public class Interest3 {

/*
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.
*/

public static void main(String[] args) {

double principal; // The value of the investment.


double rate; // The annual interest rate.

/* Get the initial investment and interest rate from the


user. */

TextIO.put("Enter the initial investment: ");


principal = TextIO.getlnDouble();

TextIO.put("Enter the annual interest rate: ");


rate = TextIO.getlnDouble();

/* Simulate the investment for 5 years. */

int years; // Counts the number of years that have passed.


years = 0;
while (years < 5) {
double interest; // Interest for this year.
interest = principal * rate;
principal = principal + interest; // Add it to
principal.
years = years + 1; // Count the current year.
System.out.print("The value of the investment after ");
System.out.print(years);
System.out.print(" years is $");
System.out.println(principal);
} // end of while loop

} // end of main()

} // end of class Interest3

And here is the applet which simulates this program:

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

When the computer executes an if statement, it evaluates the boolean expression. If


the value is true, the computer executes the first statement and skips the statement
that follows the "else". If the value of the expression is false, then the computer
skips the first statement and executes the second one. Note that in any case, one and
only one of the two statements inside the if statement is executed. The two
statements represent alternative courses of action; the computer decides between these
courses of action based on the value of the boolean expression.

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
}

As an example, here is an if statement that exchanges the value of two variables, x


and y, but only if x is greater than y to begin with. After this if statement has been
executed, we can be sure that the value of x is definitely less than or equal to the value
of y:

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:

if ( years > 1 ) { // handle case for 2 or more years


System.out.print("The value of the investment after ");
System.out.print(years);
System.out.print(" years is $");
}
else { // handle case for 1 year
System.out.print("The value of the investment after 1
year is $");
} // end of if statement
System.out.println(principal); // this is done in any case

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:

Get the user's input


Compute the value of the investment after 1 year
Display the value
Compute the value after 2 years
Display the value
Compute the value after 3 years
Display the value
Compute the value after 4 years
Display the value
Compute the value after 5 years
Display the value

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:

Get the user's input


while there are more years to process:
Compute the value after the next year
Display the value

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

Ask the user for the initial investment


Read the user's response
Ask the user for the interest rate
Read the user's response
To fill in the details of the step "Compute the value after the next year," you have to
know how to do the computation yourself. (Maybe you need to ask your boss or
professor for clarification?) Let's say you know that the value is computed by adding
some interest to the previous value. Then we can refine the while loop to:

while there are more years to process:


Compute the interest
Add the interest to the value
Display the value

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:

Ask the user for the initial investment


Read the user's response
Ask the user for the interest rate
Read the user's response
years = 0
while years < 5:
years = years + 1
Compute interest = value * interest rate
Add the interest to the value
Display the value

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:

double principal, rate, interest; // declare the


variables
int years;
System.out.print("Type initial investment: ");
principal = TextIO.getlnDouble();
System.out.print("Type interest rate: ");
rate = TextIO.getlnDouble();
years = 0;
while (years < 5) {
years = years + 1;
interest = principal * rate;
principal = principal + interest;
System.out.println(principal);
}

This still needs to be wrapped inside a complete program, it still needs to be


commented, and it really needs to print out more information for the user. But it's
essentially the same program as the one in the previous section. (Note that the
pseudocode algorithm uses indentation to show which statements are inside the loop.
In Java, indentation is completely ignored by the computer, so you need a pair of
braces to tell the computer which statements are in the loop. If you leave out the
braces, the only statement inside the loop would be "years = years + 1;". The
other statements would only be executed once, after the loop ends. The nasty thing is
that the computer won't notice this error for you, like it would if you left out the
parentheses around "(years < 5)". The parentheses are required by the syntax of the
while statement. The braces are only required semantically. The computer can
recognize syntax errors but not semantic errors.)

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."

A general outline of the algorithm for the program we want is:


Get a positive integer N from the user;
Compute, print, and count each number in the
sequence;
Output the number of terms;

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:

Get a positive integer N from the user;


while N is not 1:
Compute N = next term;
Output N;
Count this term;
Output the number of terms;

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:

Get a positive integer N from the user;


while N is not 1:
if N is even:
Compute N = N/2;
else
Compute N = 3 * N + 1;
Output N;
Count this term;
Output the number of terms;

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:

Get a positive integer N from the user;


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;

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.

public class ThreeN {

/* This program prints out a 3N+1 sequence


starting from a positive integer specified
by the user. It also counts the number
of terms in the sequence, and prints out
that number. */

public static void main(String[] args) {

int N; // for computing terms in the sequence


int counter; // for counting the terms

TextIO.put("Starting point for sequence: ");


N = TextIO.getlnInt();
while (N <= 0) {
TextIO.put("The starting point must be positive. "
+ " Please try again: ");
N = TextIO.getlnInt();
}
// At this point, we know that N > 0

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()

} // end of class ThreeN

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:

TextIO.putln(N); // print out initial term


counter = 1; // and count it

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!)

Coding, Testing, Debugging

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 and do..while Statements


The while Statement

The while statement was already introduced in Section 1. A while loop has the form

while ( boolean-expression )
statement

The statement can, of course, be a block statement consisting of several statements


grouped together between a pair of braces. This statement is called the body of the
loop. The body of the loop is repeated as long as the boolean-expression is true. This
boolean expression is called the continuation condition, or more simply the test, of the
loop. There are a few points that might need some clarification. What happens if the
condition is false in the first place, before the body of the loop is executed even once?
In that case, the body of the loop is never executed at all. The body of a while loop
can be executed any number of times, including zero. What happens if the condition is
true, but it becomes false somewhere in the middle of the loop body? Does the loop
end as soon as this happens? It does not, because the computer continues executing
the body of the loop until it gets to the end. Only then does it jump back to the
beginning of the loop and test the condition, and only then can the loop end.

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.

Here is the program and an applet that simulates it:

public class ComputeAverage {

/* This program reads a sequence of positive integers input


by the user, and it will print out the average of those
integers. The user is prompted to enter one integer at
a
time. The user must enter a 0 to mark the end of the
data. (The zero is not counted as part of the data to
be averaged.) The program does not check whether the
user's input is positive, so it will actually work for
both positive and negative input values.
*/

public static void main(String[] args) {

int inputNumber; // One of the integers input by the


user.
int sum; // The sum of the positive integers.
int count; // The number of positive integers.
double average; // The average of the positive
integers.

/* Initialize the summation and counting variables. */

sum = 0;
count = 0;

/* Read and process the user's input. */

TextIO.put("Enter your first positive integer: ");


inputNumber = TextIO.getlnInt();

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();
}

/* Display the result. */

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()

} // end class ComputeAverage

The do..while Statement

Sometimes it is more convenient to test the continuation condition at the end of a


loop, instead of at the beginning, as is done in the while loop. The do..while
statement is very similar to the while statement, except that the word "while," along
with the condition that it tests, has been moved to the end. The word "do" is added to
mark the beginning of the loop. A do..while statement has the form

do
statement
while ( boolean-expression );

or, since, as usual, the statement can be a block,

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

boolean wantsToContinue; // True if user wants to play


again.
do {
Checkers.playGame();
TextIO.put("Do you want to play again? ");
wantsToContinue = TextIO.getlnBoolean();
} while (wantsToContinue == true);

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).

By the way, a more-than-usually-pedantic programmer would sneer at the test "while


(wantsToContinue == true)". This test is exactly equivalent to "while
(wantsToContinue)". Testing whether "wantsToContinue == true" is true
amounts to the same thing as testing whether "wantsToContinue" is true. A little less
offensive is an expression of the form "flag == false", where flag is a boolean
variable. The value of "flag == false" is exactly the same as the value of "!flag",
where ! is the boolean negation operator. So you can write "while (!flag)" instead
of "while (flag == false)", and you can write "if (!flag)" instead of "if
(flag == false)".

Although a do..while statement is sometimes more convenient than a while


statement, having two kinds of loops does not make the language more powerful. Any
problem that can be solved using do..while loops can also be solved using only
while statements, and vice versa. In fact, if doSomething represents any block of
program code, then

do {
doSomething
} while ( boolean-expression );

has exactly the same effect as

doSomething
while ( boolean-expression ) {
doSomething
}

Similarly,

while ( boolean-expression ) {
doSomething
}

can be replaced by

if ( boolean-expression ) {
do {
doSomething
} while ( boolean-expression );
}

without changing the meaning of the program in any way.

The break and continue Statements

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:

while (true) { // looks like it will run forever!


TextIO.put("Enter a positive number: ");
N = TextIO.getlnlnt();
if (N > 0) // input is OK; jump out of loop
break;
TextIO.putln("Your answer must be > 0.");
}
// continue here after break

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).

The for Statement

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
}

For example, consider this example, copied from an example in Section 2:

years = 0; // initialize the variable years


while ( years < 5 ) { // condition for continuing loop

interest = principal * rate; //


principal += interest; // do three
statements
System.out.println(principal); //

years++; // update the value of the variable, years


}

This loop can be written as the following equivalent for statement:

for ( years = 0; years < 5; years++ ) {


interest = principal * rate;
principal += interest;
System.out.println(principal);
}

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.

The formal syntax of the for statement is as follows:

for ( initialization; continuation-condition; update )


statement

or, using a block statement:

for ( initialization; continuation-condition; update ) {


statements
}

The continuation-condition must be a boolean-valued expression. The initialization


can be any expression, as can the update. Any of the three can be empty. If the
continuation condition is empty, it is treated as if it were "true," so the loop will be
repeated forever or until it ends for some other reason, such as a break statement.
(Some people like to begin an infinite loop with "for (;;)" instead of "while
(true)".)

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

for ( variable = min; variable <= max; variable++ ) {


statements
}

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:

for ( N = 1 ; N <= 10 ; N++ )


System.out.println( N );
For various reasons, Java programmers like to start counting at 0 instead of 1, and
they tend to use a "<" in the condition, rather than a "<=". The following variation of
the above loop prints out the ten numbers 0, 1, 2, ..., 9:

for ( N = 0 ; N < 10 ; N++ )


System.out.println( N );

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.

for ( N = 10 ; N >= 1 ; N-- )


System.out.println( N );

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!

for ( i=1, j=10; i <= 10; i++, j-- ) {


TextIO.put(i,5); // Output i in a 5-character wide
column.
TextIO.putln(j,5); // Output j in a 5-character column
// and end the line.
}

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):

(1) // There are 10 numbers to print.


// Use a for loop to count 1, 2,
// ..., 10. The numbers we want
// to print are 2*1, 2*2, ... 2*10.

for (N = 1; N <= 10; N++) {


System.out.println( 2*N );
}

(2) // Use a for loop that counts


// 2, 4, ..., 20 directly by
// adding 2 to N each time through
// the loop.

for (N = 2; N <= 20; N = N + 2) {


System.out.println( N );
}
(3) // Count off all the numbers
// 2, 3, 4, ..., 19, 20, but
// only print out the numbers
// that are even.

for (N = 2; N <= 20; N++) {


if ( N % 2 == 0 ) // is N even?
System.out.println( N );
}

(4) // Irritate the professor with


// a solution that follows the
// letter of this silly assignment
// while making fun of it.

for (N = 1; N <= 1; N++) {


System.out.print("2 4 6 8 10 12 ");
System.out.println("14 16 18 20");
}

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:

// Print out the alphabet on one line of output.


char ch; // The loop control variable;
// one of the letters to be printed.
for ( ch = 'A'; ch <= 'Z'; ch++ )
System.out.print(ch);
System.out.println();

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

Get a positive integer, N, from the user


Let divisorCount = 0
for each number, testDivisor, in the range from 1 to N:
if testDivisor is a divisor of N:
Count it by adding 1 to divisorCount
Output the count

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

for each item in the sequence:


if the item passes the test:
process it

The for loop in our divisor-counting algorithm can be translated into Java code as

for (testDivisor = 1; testDivisor <= N; testDivisor++) {


if ( N % testDivisor == 0 )
divisorCount++;
}

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

Get a positive integer, N, from the user


Let divisorCount = 0 // Number of divisors found.
Let numberTested = 0 // Number of possible divisors
tested
// since the last period was
output.
for each number, testDivisor, in the range from 1 to N:
if testDivisor is a divisor of N:
Count it by adding 1 to divisorCount
Add 1 to numberTested
if numberTested is 1000000:
print out a '.'
Let numberTested = 0
Output the count

Finally, we can translate the algorithm into a complete Java program. Here it is,
followed by an applet that simulates it:

public class CountDivisors {

/* This program reads a positive integer from the user.


It counts how many divisors that number has, and
then it prints the result.
*/

public static void main(String[] args) {

int N; // A positive integer entered by the user.


// Divisors of this number will be counted.

int testDivisor; // A number between 1 and N that is a


// possible divisor of N.

int divisorCount; // Number of divisors of N that have


been found.

int numberTested; // Used to count how many possible


divisors
// of N have been tested. When the
number
// reaches 1000000, a period is output
and
// the value of numberTested is reset
to zero.

/* Get a positive integer from the user. */

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.");
}

/* Count the divisors, printing a "." after every 1000000


tests. */

divisorCount = 0;
numberTested = 0;

for (testDivisor = 1; testDivisor <= N; testDivisor++) {


if ( N % testDivisor == 0 )
divisorCount++;
numberTested++;
if (numberTested == 1000000) {
TextIO.put('.');
numberTested = 0;
}
}

/* Display the result. */

TextIO.putln();
TextIO.putln("The number of divisors of " + N
+ " is " + divisorCount);

} // end main()

} // end class CountDivisors


Nested Loops

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

for each rowNumber = 1, 2, 3, ..., 12:


Print the first twelve multiples of rowNumber on one
line
Output a carriage return

The first step in the for loop can itself be expressed as a for loop:

for N = 1, 2, 3, ..., 12:


Print N * rowNumber

so a refined algorithm for printing the table has one for loop nested inside another:

for each rowNumber = 1, 2, 3, ..., 12:


for N = 1, 2, 3, ..., 12:
Print N * rowNumber
Output a carriage return

Assuming that rowNumber and N have been declared to be variables of type int, this
can be expressed in Java as

for ( rowNumber = 1; rowNumber <= 12; rowNumber++ ) {


for ( N = 1; N <= 12; N++ ) {
// print in 4-character columns
TextIO.put( N * rowNumber, 4 );
}
TextIO.putln();
}

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.

Ask the user to input a string


Read the response into a variable, str
Let count = 0 (for counting the number of different
letters)
for each letter of the alphabet:
if the letter occurs in str:
Print the letter
Add 1 to count
Output the count

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.

Ask the user to input a string


Read the response into a variable, str
Convert str to upper case
Let count = 0
for letter = 'A', 'B', ..., 'Z':
for i = 0, 1, ..., str.length()-1:
if letter == str.charAt(i):
Print letter
Add 1 to count
break // jump out of the loop
Output the count

Here is the complete program and an applet to simulate it:


public class ListLetters {

/* This program reads a line of text entered by the user.


It prints a list of the letters that occur in the text,
and it reports how many different letters were found.
*/

public static void main(String[] args) {

String str; // Line of text entered by the user.


int count; // Number of different letters found in
str.
char letter; // A letter of the alphabet.

TextIO.putln("Please type in a line of text.");


str = TextIO.getln();

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()

} // end class ListLetters

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

THE FIRST OF THE TWO BRANCHING STATEMENTS in Java is the if


statement, which you have already seen in Section 1. It takes the form

if (boolean-expression)
statement-1
else
statement-2

As usual, the statements inside an if statements can be blocks. The if statement


represents a two-way branch. The else part of an if statement -- consisting of the
word "else" and the statement that follows it -- can be omitted.

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 < 50)


System.out.println("It's cold.");
else if (temperature < 80)
System.out.println("It's nice.");
else
System.out.println("It's hot.");

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.)

As an example of using if statements, lets suppose that x, y, and z are variables of


type int, and that each variable has already been assigned a value. Consider the
problem of printing out the values of the three variables in increasing order. For
examples, if the values are 42, 17, and 20, then the output should be in the order 17,
20, 42.

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,

if (x < y && x < z) {


output x, followed by y and z in their correct order
}
else if (x > y && x > z) {
output y and z in their correct order, followed by x
}
else {
output x in between y and z in their correct order
}

Determining the relative order of y and z requires another if statement, so this


becomes

if (x < y && x < z) { // x comes first


if (y < z)
System.out.println( x + " " + y + " " + z );
else
System.out.println( x + " " + z + " " + y );
}
else if (x > y && x > z) { // x comes last
if (y < z)
System.out.println( y + " " + z + " " + x );
else
System.out.println( z + " " + y + " " + x );
}
else { // x in the middle
if (y < z)
System.out.println( y + " " + x + " " + z);
else
System.out.println( z + " " + x + " " + y);
}

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:

if ( x < y ) { // x comes before y


if ( z < x )
System.out.println( z + " " + x + " " + y);
else if ( z > y )
System.out.println( x + " " + y + " " + z);
else
System.out.println( x + " " + z + " " + y);
}
else { // y comes before x
if ( z < y )
System.out.println( z + " " + y + " " + x);
else if ( z > x )
System.out.println( y + " " + x + " " + z);
else
System.out.println( y + " " + z + " " + x);
}

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

Read the user's input measurement and units of measure


Express the measurement in inches, feet, yards, and miles
Display the four results

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:

Let measurement = TextIO.getDouble()


Let units = TextIO.getlnWord()
if the units are inches
Let inches = measurement
else if the units are feet
Let inches = measurement * 12 // 12 inches per
foot
else if the units are yards
Let inches = measurement * 36 // 36 inches per
yard
else if the units are miles
Let inches = measurement * 12 * 5280 // 5280 feet per
mile
else
The units are illegal!
Print an error message and stop processing
Let feet = inches / 12.0
Let yards = inches / 36.0
Let miles = inches / (12.0 * 5280.0)
Display the results

Since units is a String, we can use units.equals("inches") to check whether the


specified unit of measure is "inches". However, it would be nice to allow the units to
be specified as "inch" or abbreviated to "in". To allow these three possibilities, we can
check if (units.equals("inches") || units.equals("inch") ||
units.equals("in")). It would also be nice to allow upper case letters, as in
"Inches" or "IN". We can do this by converting units to lower case before testing it
or by substituting the function units.equalsIgnoreCase for units.equals.

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.

public class LengthConverter {

/* This program will convert measurements expressed in inches,


feet, yards, or miles into each of the possible units of
measure. The measurement is input by the user, followed by
the unit of measure. For example: "17 feet", "1 inch",
"2.73 mi". Abbreviations in, ft, yd, and mi are accepted.
The program will continue to read and convert measurements
until the user enters an input of 0.
*/

public static void main(String[] args) {

double measurement; // Numerical measurement, input by


user.
String units; // The unit of measure for the input,
also
// specified by the user.

double inches, feet, yards, miles; // Measurement expressed


in
// each possible unit
of
// measure.

TextIO.putln("Enter measurements in inches, feet, yards, or


miles.");
TextIO.putln("For example: 1 inch 17 feet 2.73
miles");
TextIO.putln("You can use abbreviations: in ft yd
mi");
TextIO.putln("I will convert your input into the other
units");
TextIO.putln("of measure.");
TextIO.putln();

while (true) {

/* Get the user's input, and convert units to lower case.


*/

TextIO.put("Enter your measurement, or 0 to end: ");


measurement = TextIO.getDouble();
if (measurement == 0)
break; // terminate the while loop
units = TextIO.getlnWord();
units = units.toLowerCase();

/* Convert the input measurement to inches. */

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
}

/* Convert measurement in inches to feet, yards, and


miles. */

feet = inches / 12;


yards = inches / 36;
miles = inches / (12*5280);

/* Output measurement in terms of each unit of measure.


*/

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()

} // end class LengthConverter

The switch Statement

THE SECOND BRANCHING STATEMENT in Java is the switch statement, which


is introduced in this section. The switch is used far less often than the if statement,
but it is sometimes useful for expressing a certain type of multi-way branch. Since
this section wraps up coverage of all of Java's control statements, I've included a
complete list of Java's statement types at the end of the section.

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.

A switch statement has the form:

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:

switch (N) { // assume N is an integer variable


case 1:
System.out.println("The number is 1.");
break;
case 2:
case 4:
case 8:
System.out.println("The number is 2, 4, or 8.");
System.out.println("(That's a power of 2!)");
break;
case 3:
case 6:
case 9:
System.out.println("The number is 3, 6, or 9.");
System.out.println("(That's a multiple of 3!)");
break;
case 5:
System.out.println("The number is 5.");
break;
default:
System.out.println("The number is 7,");
System.out.println(" or is outside the range 1 to
9.");
}

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.

One application of switch statements is in processing menus. A menu is a list of


options. The user selects one of the options. The computer has to respond to each
possible choice in a different way. If the options are numbered 1, 2, ..., then the
number of the chosen option can be used in a switch statement to select the proper
response.

In a TextIO-based program, the menu can be presented as a numbered list of options,


and the user can choose an option by typing in its number. Here is an example that
could be used in a variation of the LengthConverter example from the previous
section:

int optionNumber; // Option number from menu, selected by


user.
double measurement; // A numerical measurement, input by
the user.
// The unit of measurement depends
on which
// option the user has selected.
double inches; // The same measurement, converted into
inches.

/* Display menu and get user's selected option number. */

TextIO.putln("What unit of measurement does your input


use?");
TextIO.putln();
TextIO.putln(" 1. inches");
TextIO.putln(" 2. feet");
TextIO.putln(" 3. yards");
TextIO.putln(" 4. miles");
TextIO.putln();
TextIO.putln("Enter the number of your choice: ");
optionNumber = TextIO.getlnInt();

/* Read user's measurement and convert to inches. */

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

/* Now go on to convert inches to feet, yards, and miles...


*/

The Empty Statement

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.

Occasionally, stray empty statements can cause annoying, hard-to-find errors in a


program. For example, the following program segment prints out "Hello" just once,
not ten times:

for (int i = 0; i < 10; i++);


System.out.println("Hello");

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.

Java statement types:

 declaration statement (for declaring variables)


 assignment statement
 subroutine call statement (including input/output routines)
 other expression statement (such as "x++;")
 empty statement
 block statement
 while statement
 do..while statement
 if statement
 for statement
 switch statement
 break statement (found in loops and switch statements only)
 continue statement (found in loops only)
 return statement (found in subroutine definitions only)
 try..catch statement
 throw statement
 synchronized statement

Introduction to Applets and Graphics

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.*;

public class name-of-applet extends Applet {

public void paint(Graphics g) {


statements
}

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.

g.drawRect(x,y,w,h) draws the outline of a rectangle. The parameters x, y, w, and h


must be integers. This draws the outline of the rectangle whose top-left corner is x
pixels from the left edge of the applet and y pixels down from the top of the applet.
The width of the rectangle is w pixels, and the height is h pixels.

g.fillRect(x,y,w,h) is similar to drawRect except that it fills in the inside of the


rectangle instead of just drawing an outline.

This is enough information to write the applet shown here:

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

Set the drawing color to red (using the g.setColor subroutine)


Fill in the entire applet (using the g.fillRect subroutine)
Set the drawing color to black
Set the top-left corner inset to be 0
Set the rectangle width and height to be as big as the applet
while the width and height are greater than zero:
draw a rectangle (using the g.drawRect subroutine)
increase the inset
decrease the width and the height

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;

public class StaticRects extends Applet {

public void paint(Graphics g) {


// Draw a set of nested black rectangles on a red
background.
// Each nested rectangle is separated by 15 pixels on
// all sides from the rectangle that encloses it.

int inset; // Gap between borders of applet


// and one of the rectangles.

int rectWidth, rectHeight; // The size of one of the


rectangles.

g.setColor(Color.red);
g.fillRect(0,0,300,160); // Fill the entire applet with
red.

g.setColor(Color.black); // Draw the rectangles in black.

inset = 0;

rectWidth = 299; // Set size of first rect to size of


applet.
rectHeight = 159;

while (rectWidth >= 0 && rectHeight >= 0) {


g.drawRect(inset, inset, rectWidth, rectHeight);
inset += 15; // Rects are 15 pixels apart.
rectWidth -= 30; // Width decreases by 15 pixels
// on left and 15 on
right.
rectHeight -= 30; // Height decreases by 15 pixels
// on top and 15 on
bottom.
}

} // end paint()

} // end class StaticRects

(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 {

public void program() {


statements
}

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:

public class PrintProduct extends ConsoleApplet {

public void program() {

double x,y; // Numbers input by the user.


double prod; // The product, x*y.

console.put("What is your first number? ");


x = console.getlnDouble();
console.put("What is your second number? ");
y = console.getlnDouble();

prod = x * y;
console.putln();
console.put("The product is ");
console.putln(prod);

} // end program()

} // end class PrintProduct

And here's what this applet looks like on a Web page:

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.*;

public class name-of-class extends SimpleAnimationApplet2 {

public void drawFrame(Graphics g) {


statements // to draw one frame of the animation
}

The "import java.awt.*;" is required to get access to graphics-related classes such


as Graphics and Color. You get to fill in any name you want for the class, and you
get to fill in the statements inside the subroutine. The drawFrame() subroutine will be
called by the system each time a frame needs to be drawn. All you have to do is say
what happens when this subroutine is called. Of course, you have to draw a different
picture for each frame, and to do that you need to know which frame you are drawing.
The class SimpleAnimationApplet2 provides a function named getFrameNumber()
that you can call to find out which frame to draw. This function returns an integer
value that represents the frame number. If the value returned is 0, you are supposed to
draw the first frame; if the value is 1, you are supposed to draw the second frame, and
so on.

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.*;

public class MovingRects extends SimpleAnimationApplet2 {

public void drawFrame(Graphics g) {

// Draw one frame in the animation by filling in the


background
// with a solid red and then drawing a set of nested
black
// rectangles. The frame number tells how much the first
// rectangle is to be inset from the borders of the
applet.

int width; // Width of the applet, in pixels.


int height; // Height of the applet, in pixels.

int inset; // Gap between borders of applet and a


rectangle.
// The inset for the outermost rectangle
goes
// from 0 to 14 then back to 0, and so on,
// as the frameNumber varies.

int rectWidth, rectHeight; // The size of one of the


rectangles.

width = getWidth(); // Find out the size of the drawing


area.
height = getHeight();

g.setColor(Color.red); // Fill the frame with red.


g.fillRect(0,0,width,height);

g.setColor(Color.black); // Switch color to black.

inset = getFrameNumber() % 15; // Get the inset for the


// outermost
rect.
rectWidth = width - 2*inset - 1; // Set size of outermost
rect.
rectHeight = height - 2*inset - 1;

while (rectWidth >= 0 && rectHeight >= 0) {


g.drawRect(inset,inset,rectWidth,rectHeight);
inset += 15; // Rects are 15 pixels apart.
rectWidth -= 30; // Width decreases by 15 pixels
// on left and 15 on
right.
rectHeight -= 30; // Height decreases by 15 pixels
// on top and 15 on
bottom.
}

} // end drawFrame()

} // end class MovingRects

(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 ]

for referring to an element of an array.

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,

list = new int[5];

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:

for (int i = 0; i < list.length; i++) {


System.out.println( list[i] );
}

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,

int[] list = new int[5];

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,

int[] list = { 1, 4, 9, 16, 25, 36, 49 };

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:

list = new int[] { 1, 8, 27, 64, 125, 216, 343 };

The general syntax for this form of the new operator is

new base-type [ ] { list-of-values }

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:

makeButtons( new String[] { "Stop", "Go", "Next", "Previous" } );

One final note: For historical reasons, the declaration

int[] list;

can also be written as

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.

Programming with Arrays


ARRAYS ARE THE MOST BASIC AND THE MOST IMPORTANT type of data
structure, and techniques for processing arrays are among the most important
programming techniques you can learn. Two fundamental array processing techniques
-- searching and sorting -- will be covered in Section 4. This section introduces some
of the basic ideas of array processing in general.

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:

// do any necessary initialization


for (int i = 0; i < A.length; i++) {
. . . // process A[i]
}

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:

double sum; // The sum of the numbers in A.


sum = 0; // Start with 0.
for (int i = 0; i < A.length; i++)
sum += A[i]; // add A[i] to the sum, for
// i = 0, 1, ..., A.length - 1

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; // For counting the items.


count = 0; // Start with 0 items counted.
for (int i = 0; i < A.length; i++) {
if (A[i] < 0.0) // if this item is less than zero...
count++; // ...then count it
}
// At this point, the value of count is the number
// of items that have passed the test of being < 0
Replace the test "A[i] < 0.0", if you want to count the number of items in an array that
satisfy some other property. Here is a variation on the same theme. Suppose you want
to count the number of times that an item in the array A is equal to the item that
follows it. The item that follows A[i] in the array is A[i+1], so the test in this case is "if
(A[i] == A[i+1])". But there is a catch: This test cannot be applied when A[i] is the last
item in the array, since then there is no such item as A[i+1]. The result of trying to
apply the test in this case would be an array index out of bounds error. This just means
that we have to stop one item short of the final item:

int count = 0;
for (int i = 0; i < A.length - 1; i++) {
if (A[i] == A[i+1])
count++;
}

Another typical problem is to find the largest number in A. The strategy is to go


through the array, keeping track of the largest number found so far. We'll store the
largest number found so far in a variable called max. As we look through the array,
whenever we find a number larger than the current value of max, we change the value
of max to that larger value. After the whole array has been processed, max is the largest
item in the array overall. The only question is, what should the original value of max
be? One possibility is to start with max equal to A[0], and then to look through the rest
of the array, starting from A[1], for larger items:

double max = A[0];


for (int i = 1; i < A.length; i++) {
if (A[i] > max)
max = A[i];
}
// at this point, max is the largest item in A

(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?)

As a final example of basic array operations, consider the problem of copying an


array. To make a copy of our sample array A, it is not sufficient to say

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:

double[] B = new double[A.length]; // Make a new array object,


// the same size as A.
for (int i = 0; i < A.length; i++)
B[i] = A[i]; // Copy each item from A to B.
Copying values from one array to another is such a common operation that Java has a
predefined subroutine to do it. The subroutine, System.arraycopy(), is a static member
subroutine in the standard System class. Its declaration has the form

public static void arraycopy(Object sourceArray, int sourceStartIndex,


Object destArray, int destStartIndex, int count)

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:

double B = new double[A.length];


System.arraycopy( A, 0, B, 0, A.length );

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:

double[] copy( double[] source ) {


// Create and return a copy of the array, source.
// If source is null, return null.
if ( source == null )
return null;
double[] cpy; // A copy of the source array.
cpy = new double[source.length];
System.arraycopy( source, 0, cpy, 0, source.length );
return cpy;
}

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:

public class CLDemo {

public static void main(String[] args) {


System.out.println("You entered " + args.length
+ " command-line parameters.");
if (args.length > 0) {
System.out.println("They were:");
for (int i = 0; i < args.length; i++)
System.out.println(" " + args[i]);
}
} // end main()

} // end class CLDemo

Note that the parameter, args, is never null when main() is called by the system, but it
might be an array of length zero.

In practice, command-line parameters are often the names of files to be processed by


the program

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.

As an example, let's look at a well-known problem called the birthday problem:


Suppose that there are N people in a room. What's the chance that there are two people
in the room who have the same birthday? (That is, they were born on the same day in
the same month, but not necessarily in the same year.) Most people severely
underestimate the probability. We actually look at a different version of the problem:
Suppose you choose people at random and check their birthdays. How many people
will you check before you find one who has the same birthday as someone you've
already checked? Of course, the answer in a particular case depends on random
factors, but we can simulate the experiment with a computer program and run the
program several times to get an idea of how many people need to be checked on
average.

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):

static void birthdayProblem() {


// Simulate choosing people at random and checking the
// day of the year they were born on. If the birthday
// is the same as one that was seen previously, stop,
// and output the number of people who were checked.

boolean[] used; // For recording the possible birthdays


// that have been seen so far. A value
// of true in used[i] means that a person
// whose birthday is the i-th day of the
// year has been found.

int count; // The number of people who have been checked.

used = new boolean[365]; // Initially, all entries are false.

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;
}

TextIO.putln("A duplicate birthday was found after "


+ count + " tries.");

} // 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

for (int i = 0; i < 365; i++)


used[i] = false;

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:

int[] x = new int[MESSAGE_COUNT];


int[] y = new int[MESSAGE_COUNT];
Color[] color = new Color[MESSAGE_COUNT];
Font[] font = new Font[MESSAGE_COUNT];

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

public void paintComponent(Graphics g) {


super.paintComponent(); // (Fill with background color.)
for (int i = 0; i < MESSAGE_COUNT; i++) {
g.setColor( color[i] );
g.setFont( font[i] );
g.drawString( message, x[i], y[i] );
}
}

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

data = new StringData[MESSAGE_COUNT];

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

for (int i = 0; i < MESSAGE_COUNT; i++)


data[i] = new StringData();

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

public void paintComponent(Graphics g) {


super.paintComponent(g); // (Fill with background color.)
for (int i = 0; i < MESSAGE_COUNT; i++) {
g.setColor( data[i].color );
g.setFont( data[i].font );
g.drawString( message, data[i].x, data[i].y );
}
}

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:

Font randomFont; // One of the 5 fonts, chosen at random.


int rand; // A random integer in the range 0 to 4.

rand = (int)(Math.random() * 5);


switch (rand) {
case 0:
randomFont = font1;
break;
case 1:
randomFont = font2;
break;
case 2:
randomFont = font3;
break;
case 3:
randomFont = font4;
break;
case 4:
randomFont = font5;
break;
}

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:

fonts = new Font[5]; // Array to store five fonts.


fonts[0] = new Font("Serif", Font.BOLD, 14);
fonts[1] = new Font("SansSerif", Font.BOLD + Font.ITALIC, 24);
fonts[2] = new Font("Monospaced", Font.PLAIN, 20);
fonts[3] = new Font("Dialog", Font.PLAIN, 30);
fonts[4] = new Font("Serif", Font.ITALIC, 36);

This makes it much easier to select one of the fonts at random. It can be done with the
statements

Font randomFont; // One of the 5 fonts, chosen at random.


int fontIndex; // A random number in the range 0 to 4.
fontIndex = (int)(Math.random() * 5);
randomFont = fonts[ fontIndex ];

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

static String[] monthName = { "January", "February", "March",


"April", "May", "June",
"July", "August", "September",
"October", "November", "December" };

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.

Partially Full Arrays

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.)

public class ReverseInputNumbers {

public static void main(String[] args) {

int[] numbers; // An array for storing the input values.


int numCt; // The number of numbers saved in the array.
int num; // One of the numbers input by the user.

numbers = new int[100]; // Space for 100 ints.


numCt = 0; // No numbers have been saved yet.

TextIO.putln("Enter up to 100 positive integers; enter 0 to end.");

while (true) { // Get the numbers and put them in the array.
TextIO.put("? ");
num = TextIO.getlnInt();
if (num <= 0)
break;
numbers[numCt] = num;
numCt++;
}

TextIO.putln("\nYour numbers in reverse order are:\n");

for (int i = numCt - 1; i >= 0; i--) {


TextIO.putln( numbers[i] );
}

} // end main();

} // end class ReverseInputNumbers

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:

Player[] playerList = new Player[10]; // Up to 10 players.


int playerCt = 0; // At the start, there are no players.

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:

playerList[playerCt] = newPlayer; // Put new player in next


// available spot.
playerCt++; // And increment playerCt to count the new player.

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:

playerList[k] = playerList[playerCt - 1];


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

for (int i = k+1; i < playerCt; i++) {


playerList[i-1] = playerList[i];
}
playerCt--;

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

Shape[] shapes = new Shape[100]; // Array to hold up to 100 shapes.


shapes[0] = new Rect(); // Put some objects in the array.
shapes[1] = new Line(); // (A real program would
shapes[2] = new FilledOval(); // use some parameters here.)
int shapeCt = 3; // Keep track of number of objects in array.

could be illustrated as:


Such an array would be useful in a drawing program. The array could be used to hold
a list of shapes to be displayed. If the Shape class includes a method, "void
redraw(Graphics g)" for drawing the shape in a graphics context g, then all the shapes in
the array could be redrawn with a simple for loop:

for (int i = 0; i < shapeCt; i++)


shapes[i].redraw(g);

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:

// Add a new player, even if the current array is full.

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.
}

// At this point, we KNOW there is room in the array.

playerList[playerCt] = newPlayer; // Add the new player...


playerCt++; // ...and count it.

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 class DynamicArrayOfInt {

private int[] data; // An array to hold the data.

public DynamicArrayOfInt() {
// Constructor.
data = new int[1]; // Array will grow as necessary.
}

public int get(int position) {


// Get the value from the specified position in the array.
// Since all array positions are initially zero, when the
// specified position lies outside the actual physical size
// of the data array, a value of 0 is returned.
if (position >= data.length)
return 0;
else
return data[position];
}

public void put(int position, int value) {


// Store the value in the specified position in the array.
// The data array will increase in size to include this
// position, if necessary.
if (position >= data.length) {
// The specified position is outside the actual size of
// the data array. Double the size, or if that still does
// not include the specified position, set the new size
// to 2*position.
int newSize = 2 * data.length;
if (position >= newSize)
newSize = 2 * position;
int[] newData = new int[newSize];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
// The following line is for demonstration purposes only.
System.out.println("Size of dynamic array increased to "
+ newSize);
}
data[position] = value;
}

} // end class DynamicArrayOfInt

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:

public class ReverseWithDynamicArray {

public static void main(String[] args) {

DynamicArrayOfInt numbers; // To hold the input numbers.


int numCt; // The number of numbers stored in the array.
int num; // One of the numbers input by the user.

numbers = new DynamicArrayOfInt();


numCt = 0;

TextIO.putln("Enter some positive integers; Enter 0 to end");


while (true) { // Get numbers and put them in the dynamic array.
TextIO.put("? ");
num = TextIO.getlnInt();
if (num <= 0)
break;
numbers.put(numCt, num); // Store num in the dynamic array.
numCt++;
}

TextIO.putln("\nYour numbers in reverse order are:\n");

for (int i = numCt - 1; i >= 0; i--) {


TextIO.putln( numbers.get(i) ); // Print the i-th number.
}

} // end main();

} // end class ReverseWithDynamicArray

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.

list.remove(obj)-- If the specified object occurs somewhere in the ArrayList, it is removed


from the list. Any items in the list that come after the removed item are moved down
one position. The size of the ArrayList decreases by 1. If obj occurs more than once in
the list, only the first copy is removed.

-- 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;

and initialized to refer to a new, empty ArrayList object with

players = new ArrayList();

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);

and if player number i leaves the game, it is only necessary to say

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:

Player plr = (Player)players.get(i);


For example, if the Player class includes an instance method makeMove() that is called
to allow a player to make a move in the game, then the code for letting all the players
move is

for (int i = 0; i < players.size(); i++) {


Player plr = (Player)players.get(i);
plr.makeMove();
}

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):

for (int i = 0; i < rects.size(); i++) {


ColoredRect rect = (ColoredRect)rects.get(i);
g.setColor( rect.color );
g.fillRect( rect.x, rect.y, rect.width, rect.height);
g.setColor( Color.black );
g.drawRect( rect.x, rect.y, rect.width - 1, rect.height - 1);
}

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

ColoredRect findRect(int x, int y) {


// Find the topmost rect that contains the point (x,y).
// Return null if no rect contains that point. The
// rects in the ArrayList are considered in reverse order
// so that if one lies on top of another, the one on top
// is seen first and is the one that is returned.

for (int i = rects.size() - 1; i >= 0; i--) {


ColoredRect rect = (ColoredRect)rects.get(i);
if ( x >= rect.x && x < rect.x + rect.width
&& y >= rect.y && y < rect.y + rect.height )
return rect; // (x,y) is inside this rect.
}

return null; // No rect containing (x,y) was found.

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:

void bringToFront(ColoredRect rect) {


// If rect != null, move it out in front of the other
// rects by moving it to the last position in the ArrayList.
if (rect != null) {
rects.remove(rect);
rects.add(rect);
repaint();
}
}

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.

Suppose that vec is a Vector. Then:


 vec.size() is a function that returns the number of elements currently in
the vector.
 vec.addElement(obj) will add the Object, obj to the end of the vector. This is
the same as the add() method of an ArrayList.
 vec.removeElement(obj) removes obj from the vector, if it occurs. Only the
first occurrence is removed. This is the same as remove(obj) for an
ArrayList.
 vec.removeElementAt(N) removes the N-th element, for an integer N. N
must be in the range 0 to vec.size()-1. This is the same as remove(N) for an
ArrayList.
 vec.setSize(N) sets the size of the vector to N. If there were more than N
elements in vec, the extra elements are removed. If there were fewer
than N elements, extra spaces are filled with null. The ArrayList class
does not have a setSize() method.

The Vector class includes many more methods, but these are probably the most
commonly used.

Searching and Sorting

TWO ARRAY PROCESSING TECHNIQUES that are particularly common are


searching and sorting. Searching here refers to finding an item in the array that meets
some specified criterion. Sorting refers to rearranging all the items in the array into
increasing or decreasing order (where the meaning of increasing and decreasing can
depend on the context).

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:

static int find(int[] A, int N) {


// Searches the array A for the integer N.
// Postcondition: If N is not in the array, -1 is
// returned. If N is in the array, then the
// return value, i, is the first integer that
// satisfies A[i] == N.

for (int index = 0; index < A.length; index++) {


if ( A[index] == N )
return index; // N has been found at this index!
}

// If we get this far, then N has not been found


// anywhere in the array. Return a value of -1.

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:

static int binarySearch(int[] A, int N) {


// Searches the array A for the integer N.
// Precondition: A must be sorted into increasing order.
// Postcondition: If N is in the array, then the return
// value, i, satisfies A[i] == N. If not, then the
// return value is -1.

int lowestPossibleLoc = 0;
int highestPossibleLoc = A.length - 1;

while (highestPossibleLoc >= lowestPossibleLoc) {


int middle = (lowestPossibleLoc + highestPossibleLoc) / 2;
if (A[middle] == N) {
// N has been found at this index!
return middle;
}
else if (A[middle] > N) {
// eliminate locations >= middle
highestPossibleLoc = middle - 1;
}
else {
// eliminate locations <= middle
lowestPossibleLoc = middle + 1;
}
}

// At this point, highestPossibleLoc < LowestPossibleLoc,


// which means that N is known to be not in the array. Return
// a -1 to indicate that N could not be found in the array.

return -1;

Association Lists

One particularly common application of searching is with association lists. The


standard example of an association list is a dictionary. A dictionary associates
definitions with words. Given a word, you can use the dictionary to look up its
definition. We can think of the dictionary as being a list of pairs of the form (w,d),
where w is a word and d is its definition. A general association list is a list of pairs
(k,v), where k is some "key" value, and v is a value associated to that key. In general,
we want to assume that no two pairs in the list have the same key. The basic operation
on association lists is this: Given a key, k, find the value v associated with k, if any.

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 {

PhoneEntry[] info = new PhoneEntry[100]; // Space for 100 entries.


int entries = 0; // Actual number of entries in the array.
void addEntry(String name, String phoneNum) {
// Add a new item at the end of the array.
info[entries] = new PhoneEntry();
info[entries].name = name;
info[entries].phoneNum = phoneNum;
entries++;
}

String getNumber(String name) {


// Return phone number associated with name,
// or return null if the name does not occur
// in the array.
for (int index = 0; index < entries; index++) {
if (name.equals( info[index].name )) // Found it!
return info[index].phoneNum;
}
return null; // Name wasn't found.
}

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.

static void insert(int[] A, int itemsInArray, int newItem) {


// Precondition: itemsInArray is the number of items that are
// stored in A. These items must be in increasing order
// (A[0] <= A[1] <= ... <= A[itemsInArray-1]).
// The array size is at least one greater than itemsInArray.
// Postcondition: The number of items has increased by one,
// newItem has been added to the array, and all the items
// in the array are still in increasing order.
// Note: To complete the process of inserting an item in the
// array, the variable that counts the number of items
// in the array must be incremented, after calling this
// subroutine.

int loc = itemsInArray - 1; // Start at the end of the array.

/* Move items bigger than newItem up one space;


Stop when a smaller item is encountered or when the
beginning of the array (loc == 0) is reached. */

while (loc >= 0 && A[loc] > newItem) {


A[loc + 1] = A[loc]; // Bump item from A[loc] up to loc+1.
loc = loc - 1; // Go on to next location.
}

A[loc + 1] = newItem; // Put newItem in last vacated space.

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:

static void insertionSort(int[] A) {


// Sort the array A into increasing order.

int itemsSorted; // Number of items that have been sorted so far.

for (itemsSorted = 1; itemsSorted < A.length; itemsSorted++) {


// Assume that items A[0], A[1], ... A[itemsSorted-1]
// have already been sorted. Insert A[itemsSorted]
// into the sorted list.

int temp = A[itemsSorted]; // The item to be inserted.


int loc = itemsSorted - 1; // Start at end of list.

while (loc >= 0 && A[loc] > temp) {


A[loc + 1] = A[loc]; // Bump item from A[loc] up to loc+1.
loc = loc - 1; // Go on to next location.
}

A[loc + 1] = temp; // Put temp in last vacated space.


}
}

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:

static void selectionSort(int[] A) {

// Sort A into increasing order, using selection sort

for (int lastPlace = A.length-1; lastPlace > 0; lastPlace--) {


// Find the largest item among A[0], A[1], ...,
// A[lastPlace], and move it into position lastPlace
// by swapping it with the number that is currently
// in position lastPlace.

int maxLoc = 0; // Location of largest item seen so far.

for (int j = 1; j <= lastPlace; j++) {


if (A[j] > A[maxLoc]) {
// Since A[j] is bigger than the maximum we've seen
// so far, j is the new location of the maximum value
// we've seen so far.
maxLoc = j;
}
}

int temp = A[maxLoc]; // Swap largest item with A[lastPlace].


A[maxLoc] = A[lastPlace];
A[lastPlace] = temp;

} // end of for loop

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:

public void sortBySuit() {


// Sorts the cards in the hand so that cards of the same
// suit are grouped together, and within a suit the cards
// are sorted by value. Note that aces are considered to have
// the lowest value, 1.
Vector newHand = new Vector();
while (hand.size() > 0) {
int pos = 0; // Position of minimal card.
Card c = (Card)hand.elementAt(0); // Minimal card seen so far.
for (int i = 1; i < hand.size(); i++) {
Card c1 = (Card)hand.elementAt(i);
if ( c1.getSuit() < c.getSuit() ||
(c1.getSuit() == c.getSuit()
&& c1.getValue() < c.getValue()) ) {
pos = i;
c = c1;
}
}
hand.removeElementAt(pos);
newHand.addElement(c);
}
hand = newHand;
}
Unsorting

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:

static void shuffle(int[] A) {


// Postcondition: The items in A have been rearranged into
// a random order.
for (int lastPlace = A.length-1; lastPlace > 0; lastPlace--) {
// Choose a random location from among 0,1,...,lastPlace.
int randLoc = (int)(Math.random()*(lastPlace+1));
// Swap items in locations randLoc and lastPlace.
int temp = A[randLoc];
A[randLoc] = A[lastPlace];
A[lastPlace] = temp;
}
}

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:

A[0][0] A[0][1] A[0][2] A[0][3]


A[1][0] A[1][1] A[1][2] A[1][3]
A[2][0] A[2][1] A[2][2] A[2][3]

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.)

Three-dimensional arrays are treated similarly. For example, a three-dimensional


array of ints could be created with the declaration statement "int[][][] B = new int[7][5]
[11];". It's possible to visualize the value of B as a solid 7-by-5-by-11 block of cells.
Each cell holds an int and represents one position in the three-dimensional array.
Individual positions in the array can be referred with variable names of the form B[i][j]
[k].
Higher-dimensional arrays follow the same pattern, although for dimensions
greater than three, there is no easy way to visualize the structure of the array.

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 }
};

If no initializer is provided for an array, then when the array is created it is


automatically filled with the appropriate value: zero for numbers, false for boolean,
and null for objects.

Just as in the case of one-dimensional arrays, two-dimensional arrays are often


processed using for statements. To process all the items in a two-dimensional array,
you have to use one for statement nested inside another. If the array A is declared as

int[][] A = new int[3][4];

then you could store a zero into each location in A with:

for (int row = 0; row < 3; row++) {


for (int column = 0; column < 4; column++) {
A[row][column] = 0;
}
}

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.

Similarly, you could add up all the items in A with:

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:

ChessPiece[][] board = new ChessPiece[8][8];

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:

grid = new Color[ROWS][COLUMNS];

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:

int rowHeight = getSize().height / ROWS;


int colWidth = getSize().width / COLUMNS;
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLUMNS; col++) {
g.setColor( grid[row][col] ); // Get color from array.
g.fillRect( col*colWidth, row*rowHeight,
colWidth, rowHeight );
}
}

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:

double[][] profit = new double[25][12];

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:

double totalProfit; // Company's total profit in 2000.

totalProfit = 0;
for (int store = 0; store < 25; store++) {
for (int month = 0; month < 12; month++)
totalProfit += profit[store][month];
}

Sometimes it is necessary to process a single row or a single column of an array, not


the entire array. For example, to compute the total profit earned by the company in
December, that is, in month number 11, you could use the loop:

double decemberProfit = 0.0;


for (storeNum = 0; storeNum < 25; storeNum++)
decemberProfit += profit[storeNum][11];

Let's extend this idea to create a one-dimensional array that contains the total profit
for each month of the year:

double[] monthlyProfit; // Holds profit for each month.


monthlyProfit = new double[12];

for (int month = 0; month < 12; month++) {


// compute the total profit from all stores in this month.
monthlyProfit[month] = 0.0;
for (int store = 0; store < 25; store++) {
// Add the profit from this store in this month
// into the total profit figure for the month.
monthlyProfit[month] += profit[store][month];
}
}

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.

double maxProfit; // Maximum profit earned by a store.


int bestStore; // The number of the store with the
// maximum profit.

double total = 0.0; // Total profit for one store.

// First compute the profit from store number 0.

for (int month = 0; month < 12; month++)


total += profit[0][month];

bestStore = 0; // Start by assuming that the best


maxProfit = total; // store is store number 0.
// Now, go through the other stores, and whenever we
// find one with a bigger profit than maxProfit, revise
// the assumptions about bestStore and maxProfit.

for (store = 1; store < 25; store++) {

// Compute this store's profit for the year.

total = 0.0;
for (month = 0; month < 12; month++)
total += profit[store][month];

// Compare this store's profits with the highest


// profit we have seen among the preceding stores.

if (total > maxProfit) {


maxProfit = total; // Best profit seen so far!
bestStore = store; // It came from this store.
}

} // end for

// At this point, maxProfit is the best profit of any


// of the 25 stores, and bestStore is a store that
// generated that profit. (Note that there could also be
// other stores that generated exactly the same profit.)

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:

public static final int


EMPTY = 0, // Value representing an empty square.
RED = 1, // A regular red piece.
RED_KING = 2, // A red king.
BLACK = 3, // A regular black piece.
BLACK_KING = 4; // A black king.

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

0 BLACK EMPTY BLACK EMPTY BLACK EMPTY BLACK EMPTY

1 EMPTY BLACK EMPTY BLACK EMPTY BLACK EMPTY BLACK

2 BLACK EMPTY BLACK EMPTY BLACK EMPTY BLACK EMPTY

3 EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY

4 EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY

5 EMPTY RED EMPTY RED EMPTY RED EMPTY RED

6 RED EMPTY RED EMPTY RED EMPTY RED EMPTY

7 EMPTY RED EMPTY RED EMPTY RED EMPTY RED

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.

board[toRow][toCol] = board[fromRow][fromCol]; // Move the piece.


board[fromRow][fromCol] = EMPTY;

if (fromRow - toRow == 2 || fromRow - toRow == -2) {


// The move is a jump. Remove the jumped piece from the board.
int jumpRow = (fromRow + toRow) / 2; // Row of the jumped piece.
int jumpCol = (fromCol + toCol) / 2; // Column of the jumped piece.
board[jumpRow][jumpCol] = EMPTY;
}

if (toRow == 0 && board[toRow][toCol] == RED)


board[toRow][toCol] = RED_KING; // Red piece becomes a king.
if (toRow == 7 && board[toRow][toCol] == BLACK)
board[toRow][toCol] = BLACK_KING; // Black 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.)

int fromRow, fromCol; // Position of piece to be moved.


int toRow, toCol; // Square it is to move to.

CheckersMove(int r1, int c1, int r2, int c2) {


// Constructor. Set the values of the instance variables.
fromRow = r1;
fromCol = c1;
toRow = r2;
toCol = c2;
}

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);
}

} // end class CheckersMove.

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

public CheckersMove[] getLegalMoves(int player)


// Return an array containing all the legal CheckersMoves
// for the specified player on the current board. If the player
// has no legal moves, null is returned. The value of player
// should be one of the constants RED or BLACK; if not, null
// is returned. If the returned value is non-null, it consists
// entirely of jump moves or entirely of regular moves, since
// if the player can jump, only jumps are legal moves.

A brief pseudocode algorithm for the method is

Start with an empty list of moves


Find any legal jumps and add them to the list
if there are no jumps:
Find any other legal moves and add them to the list
if the list is empty:
return null
else:
return the list

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:

Let "moves" be an empty ArrayList


Find any legal jumps and add them to moves
if moves.size() is 0:
Find any other legal moves and add them to moves
if moves.size() is 0:
return null
else:
Let moveArray be an array of CheckersMoves of length moves.size()
Copy the contents of moves into moveArray
return moveArray

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:

For each row of the board:


For each column of the board:
if one of the player's pieces is at this location:
if it is legal to jump to row + 2, column + 2
add this move to moves
if it is legal to jump to row - 2, column + 2
add this move to moves
if it is legal to jump to row + 2, column - 2
add this move to moves
if it is legal to jump to row - 2, column - 2
add this move to moves

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 (r2 < 0 || r2 >= 8 || c2 < 0 || c2 >= 8)


return false; // (r2,c2) is off the board.

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()

This method is called by my getLegalMoves() method to check whether one of the


possible moves that it has found is actually legal. I have a similar method that is
called to check whether a jump is legal. In this case, I pass to the method the square
containing the player's piece, the square that the player might move to, and the square
between those two, which the player would be jumping over. The square that is being
jumped must contain one of the opponent's pieces. This method has the specification:

private boolean canJump(int player, int r1, int c1,


int r2, int c2, int r3, int c3) {
// This is called by other methods to check whether
// the player can legally jump from (r1,c1) to (r3,c3).
// It is assumed that the player has a piece at (r1,c1), that
// (r3,c3) is a position that is 2 rows and 2 columns distant
// from (r1,c1) and that (r2,c2) is the square between (r1,c1)
// and (r3,c3).
Given all this, you should be in a position to understand the complete getLegalMoves()
method. It's a nice way to finish off this chapter, since it combines several topics that
we've looked at: one-dimensional arrays, ArrayLists, and two-dimensional arrays:

public CheckersMove[] getLegalMoves(int player) {

if (player != RED && player != BLACK)


return null;

int playerKing; // The constant for a King belonging to the player.


if (player == RED)
playerKing = RED_KING;
else
playerKing = BLACK_KING;

ArrayList moves = new ArrayList();


// Moves will be stored in this list.

/* First, check for any possible jumps. Look at each square on


the board. If that square contains one of the player's pieces,
look at a possible jump in each of the four directions from that
square. If there is a legal jump in that direction, put it in
the moves ArrayList.
*/

for (int row = 0; row < 8; row++) {


for (int col = 0; col < 8; col++) {
if (board[row][col] == player || board[row][col] == playerKing) {
if (canJump(player, row, col, row+1, col+1, row+2, col+2))
moves.add(new CheckersMove(row, col, row+2, col+2));
if (canJump(player, row, col, row-1, col+1, row-2, col+2))
moves.add(new CheckersMove(row, col, row-2, col+2));
if (canJump(player, row, col, row+1, col-1, row+2, col-2))
moves.add(new CheckersMove(row, col, row+2, col-2));
if (canJump(player, row, col, row-1, col-1, row-2, col-2))
moves.add(new CheckersMove(row, col, row-2, col-2));
}
}
}

/* 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 no legal moves have been found, return null. Otherwise, create


an array just big enough to hold all the legal moves, copy the
legal moves from the ArrayList into the array, and return the array.
*/

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

Applets, HTML, and GUI's

JAVA IS A PROGRAMMING LANGUAGE DESIGNED for networked computers


and the World Wide Web. Java applets are downloaded over a network to appear on a
Web page. Part of learning Java is learning to program applets and other Graphical
User Interface programs. GUI programs are event-driven. That is, user actions such as
clicking on a button or pressing a key on the keyboard generate events, and the
program must respond to these events as they occur.
Event-driven programming builds on all the skills you have learned in the first five
chapters of this text. You need to be able to write the subroutines that respond to
events. Inside these subroutines, you are doing the kind of programming-in-the-small
that was covered in nextchapters.And of course, objects are everywhere. Events are
objects. Applets and other GUI components are objects. Events are handled by
instance methods contained in objects. In Java, event-oriented programming is object-
oriented programming.
This chapter covers the basics of applets, graphics, components, and events. There is
also a section that covers HyperText Markup Language (HTML), the language used
for writing Web pages. The discussion of applets and GUI's will continue in the next
chapter with more details and with more advanced techniques.
The Basic Java Applet and JApplet

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.*;

public class HelloWorldApplet extends Applet {

// An applet that simply displays the string Hello World!

public void paint(Graphics g) {


g.drawString("Hello World!", 10, 30);
}

} // end of class HelloWorldApplet


The drawString() method, defined in the Graphics class, actually does the drawing.
The parameters of this method specify the string to be drawn and the point in the
applet where the string is to be placed. More about this later.
Now, an applet is an object, not a class. So far we have only defined a class. Where
does an actual applet object come from? It is possible, of course, to create such
objects:
Applet hw = new HelloWorldApplet();
This might even be useful if you are writing a program and would like to add an
applet to a window you've created. Most often, however, applet objects are created by
"the system." For example, when an applet appears on a page in a Web browser, "the
system" means the Web browser. It is up to the browser program to create the applet
object and to add it to a Web page. The Web browser, in turn, gets instructions about
what is to appear on a given Web page from the source document for that page. For an
applet to appear on a Web page, the source document for that page must specify the
name of the applet and its size. This specification, like the rest of the document, is
written in a language called HTML. I will discuss HTML in more detail in next part.
Here is some HTML code that instructs a Web browser to display a
HelloWorldApplet:
<center>
<applet code="HelloWorldApplet.class" width=200 height=50>
</applet>
</center>
and here is the applet that this code displays:

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.*;

public class HelloWorldApplet2 extends Applet {


public void init() {
// Initialize the applet by setting it to use blue
// and yellow as background and foreground colors.
setBackground(Color.blue);
setForeground(Color.yellow);
}

public void paint(Graphics g) {


g.drawString("Hello World!", 10, 30);
}

} // end of class HelloWorldApplet2

JApplets and Swing


The AWT (Abstract Windowing Toolkit) has been part of Java from the beginning,
but, almost from the beginning, it has been clear that the AWT was not powerful or
flexible enough for writing complex, sophisticated applications. This does not prevent
it from being useful -- especially for applets, which are generally not as complex as
full-scale, independent applications. The Swing graphical user interface library was
created to address the problems with the AWT. With the release of Java version 1.2,
Swing became an official part of Java. (Versions of Java starting with 1.2 are also
called, rather confusingly, "Java 2.") There are still good reasons to write applets
based on the AWT, such as the lack of support in many Web browsers for Java 2.
However, at this point, anyone writing a stand-alone graphical application in Java
should almost certainly be using Swing, and it is Swing that I will concentrate on in
this book. If you want to write applets using the AWT, you might want to look at the
previous version of this book, which can be found on the web at .The classes that
make up the Swing library can be found in the package javax.swing. Swing includes
the class javax.swing.JApplet to be used as a basis for writing applets. JApplet is
actually a subclass of Applet, so JApplets are in fact Applets in the usual sense.
However, JApplets have a lot of extra structure that plain Applets don't have. Because
of this structure, the painting of a JApplet is a more complex affair and is handled by
the system. So, when you make a subclass of JApplet you should not write a paint()
method for it. As we will see, if you want to draw on a JApplet, you should add a
component to the applet to be used for that purpose. On the other hand, you can and
generally should write an init() method for a subclass of JApplet.
In this book, I will use a plain Applet in only a few examples. In almost all cases, I
will use a JApplet even where a plain applet might make more sense (that is, when the
applet is just being used as a simple drawing surface).

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.

import javax.swing.*; // Swing GUI classes are defined here.


import java.awt.event.*; // Event handling class are defined here.

public class HelloSwing extends JApplet implements ActionListener {

public void init() {


// This method is called by the system before the applet
// appears. It is used here to create the button and add
// it to the "content pane" of the JApplet. The applet
// is also registered as an ActionListener for the button.

JButton bttn = new JButton("Click Me!");


bttn.addActionListener(this);
getContentPane().add(bttn);
} // end init()

public void actionPerformed(ActionEvent evt) {


// This method is called when an action event occurs.
// In this case, the only possible source of the event
// is the button. So, when this method is called, we know
// that the button has been clicked. Respond by showing
// an informational dialog box. The dialog box will
// contain an "OK" button which the user must click to
// dismiss the dialog box.

String title = "Greetings"; // Shown in title bar of dialog box.


String message = "Hello from the Swing User Interface Library.";
JOptionPane.showMessageDialog(null, message, title,
JOptionPane.INFORMATION_MESSAGE);
} // end actionPerformed()

} // end class HelloSwing

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.

public class HelloSwing2 extends JApplet {

public void init() {


// This method is called by the system before the applet
// appears. It is used here to create the button and add
// it to the "content pane" of the JApplet. An anonymous
// class is used to create an ActionListener for the button.

JButton bttn = new JButton("Click Me!");

bttn.addActionListener( new ActionListener() {


// The "action listener" for the button is defined
// by this nested anonymous class.
public void actionPerformed(ActionEvent evt) {
// This method is called to respond when the user
// presses the button. It displays a message in
// a dialog box, along with an "OK" button which
// the user can click to dismiss the dialog box.
String title = "Greetings"; // Shown in box's title bar.
String message = "Another hello from Swing.";
JOptionPane.showMessageDialog(null, message, title,
JOptionPane.INFORMATION_MESSAGE);
} // end actionPerformed()
});

getContentPane().add(bttn);

} // end init()

} // end class HelloSwing2

HTML Basics

APPLETS GENERALLY APPEAR ON PAGES in a Web browser program. Such


pages are themselves written in a language called HTML (HyperText Markup
Language). An HTML document describes the contents of a page. A Web browser
interprets the HTML code to determine what to display on the page. The HTML code
doesn't look much like the resulting page that appears in the browser. The HTML
document does contain all the text that appears on the page, but that text is "marked
up" with commands that determine the structure and appearance of the text and
determine what will appear on the page in addition to the text.
HTML has developed rapidly in the last few years, and it has become a rather
complicated language. In this section, I will cover just the basics of the language.
While that leaves out all the fancy stuff, it does include just about everything I've used
to make the Web pages in this on-line text.
It is possible to write an HTML page using an ordinary text editor, typing in all the
mark-up commands by hand. However, there are many Web-authoring programs that
make it possible to create Web pages without ever looking at the underlying code.
Using these tools, you can compose a Web page in much the same way that you
would write a paper with a word processor. For example, Netscape Composer, which
is part of Netscape Communicator, works in this way. However, my opinion is that
making high-quality Web pages still requires some work with raw HTML, and serious
Web authors still need to learn the HTML language.
The mark-up commands used by HTML are called tags. An HTML tag takes the form
<tag-name optional-modifiers>
Where the tag-name is a word that specifies the command, and the optional-modifiers,
if present, are used to provide additional information for the command (much like
parameters in subroutines). A modifier takes the form
modifier-name = value
Usually, the value is enclosed in quotes, and it must be if it is more than one word
long or if it contains certain special characters. There are a few modifiers which have
no value, in which case only the name of the modifier is present. HTML is case
insensitive, which means that you can use uppercase and lowercase letters
interchangeably in tags and modifiers.
A simple example of a tag is <HR>, which draws a line -- also called a "horizontal
rule" -- across the page. The HR tag can take several possible modifiers such as
WIDTH and ALIGN. For example, the short line just after the heading of this page
was produced by the HTML command:
<HR align=center width="33%">
The WIDTH here is specified as 33% of the available space. It could also be given as
a fixed number of pixels. The value for ALIGN could be CENTER, LEFT, or RIGHT.
A LEFT alignment would shove the line to the left side of the page, and a RIGHT
alignment, to the right side. WIDTH and ALIGN are optional modifiers. If you leave
them out, then their default values will be used. The default for WIDTH is 100%, and
the default for ALIGN is LEFT.
Many tags require matching closing tags, which take the form
</tag-name>
For example, the tag <PRE> must always have a matching closing tag </PRE> later
in the document. The tag applies to everything that comes between the opening tag
and the closing tag. The <PRE> tag tells a Web browser to display everything
between the <PRE> and the </PRE> just as it is formatted in the original HTML
source code, including all the spaces and carriage returns. (But tags between <PRE>
and </PRE> are still interpreted by the browser.) "PRE" stands for preformatted text.
All of the sample programs in these notes are formatted using the <PRE> command.
It is important for you to understand that when you don't use PRE, the computer will
completely ignore the formatting of the text in the HTML source code. The only thing
it pays attention to is the tags. Five blank lines in the source code have no more effect
than one blank line or even a single blank space. Outside of <PRE>, if you want to
force a new line on the Web page, you can use the tag <BR>, which stands for
"break". For example, I might give my address as:
David Eck<BR>
Department of Mathematics and Computer Science<BR>
Hobart and William Smith Colleges<BR>
Geneva, NY 14456<BR>
If you want extra vertical space in your web page, you can use several <BR>'s in a
row.
Similarly, you need a tag to indicate how the text should be broken up into
paragraphs. This is done with the <P> tag, which should be placed at the beginning of
every paragraph. The <P> tag has a matching </P>, which should be placed at the end
of each paragraph. The closing </P> is technically optional, but it is considered good
form to use it. If you want all the lines of the paragraph to be shoved over to the right,
you can use <P ALIGN=RIGHT> instead of <P>. (This is mostly useful when used
with one short line, or when used with <BR> to make several short lines.) You can
also use <P ALIGN=CENTER> for centered lines.
By the way, if tags like <P> and <HR> have special meanings in HTML, you might
wonder how I can get them to appear here on this page. To get certain special
characters to appear on the page, you have to use an entity name in the HTML source
code. The entity name for < is &lt;, and the entity name for > is &gt;. Entity names
begin with & and end with a semicolon. The character & is itself a special character
whose entity name is &amp;. There are also entity names for nonstandard characters
such as the accented e, é, which has the entity name &eacute;.
The rest of this page discusses several other basic HTML tags. This is not meant to be
a complete discussion. But it is enough to produce interesting pages.

Overall Document Structure


HTML documents have a standard structure. They begin with <HTML> and end with
</HTML>. Between these tags, there are two sections, the head, which is marked off
by <HEAD> and </HEAD>, and the body, which -- as I'm sure you have guessed -- is
surrounded by <BODY> and </BODY>. Often, the head contains only one item: a
title for the document. This title might be shown, for example, in the title bar of a Web
browser window. The title should not contain any HTML tags. The body contains the
actual page contents that are displayed by the browser. So, an HTML document takes
this form:
<HTML>

<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.

Headings and Font Styles


HTML has a number of tags that affect the size and style of displayed text. For a
heading, which is meant to stand out on a line by itself, HTML offers the tags <H1>,
<H2>, ..., <H6>. These tags are always used with matching closing tags such as
</H1>. The <H1> tag is meant for the most important headings and produces the
largest size text. I've found <H4> through <H6> to be too small to be useful. You can
use <BR> tags in headings, if you want multi-line headings. You can also use links
and images, which are described below. The heading tags can take ALIGN as a
modifier, with the value LEFT, RIGHT, or CENTER. For example, the heading
A Sample Heading
was written as "<H1 align=center>A Sample Heading</H1>" in the HTML source
code.
There are a number of different style tags that you can apply to text. For example,
bold text can be obtained by surrounding the text with <B> and </B>. You can use
<i> for italic, <U> for underlined, and <TT> for typewriter style text. Most browsers
support <SUB> for subscripted text and <SUP> for superscripted text. For example,
"x<SUP>2</SUP>" will give: x2.
Because HTML is meant to describe the logical structure of a document, rather than
its exact appearance, it has a number of tags for displaying the logical style of the text.
For example, the <EM> tag is meant to emphasize the text surrounded by <EM> and
</EM>, while <STRONG> is for strong emphasis. And the <CITE> style tag is
meant for titles of books.
You can get even more control over the style of the text by using the
<FONT>...</FONT> tag. The <FONT> tag uses modifiers such as COLOR and SIZE
to control the appearance of the font. For big blue text, you would say:
<FONT color=blue size="+1">big blue text</FONT>
The value "+1" for the SIZE modifier means "a little bigger than usual." You could
use "+2" for an even bigger font, "-1" for a smaller font, and so on. However, only a
limited number of different sizes are available.

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.

The Applet tag and Applet Parameters


The <APPLET> tag is used to add a Java applet to a Web page. This tag must have a
matching </APPLET>. A required modifier named CODE gives the name of the
compiled class file that contains the applet. HEIGHT and WIDTH modifiers are
required to specify the size of the applet. If you want the applet to be centered on the
page, you can put the applet in a paragraph with CENTER alignment So, an applet tag
to display an applet named HelloWorldApplet centered on a Web page would look
like this:
<P ALIGN=CENTER>
<APPLET CODE="HelloWorldApplet.class" HEIGHT=50 WIDTH=150>
</APPLET>
</P>
This assumes that the file HelloWorldApplet.class is located in the same directory
with the HTML document. If this is not the case, you can use another modifier,
CODEBASE, to give the URL of the directory that contains the class file. The value
of CODE itself is always just a file name, not a URL.
If an applet uses a lot of .class files, it's a good idea to collect all the .class files into a
single .zip or .jar file. Zip and jar files are archive files which hold a number of
smaller files. Your Java development system is probably capable of creating them in
some way. If your class files are in an archive, then you have to specify the name of
the archive file in an ARCHIVE modifier in the <APPLET> tag. Archive files won't
work on older browsers, but they should work for any browser that understands Java
version 1.1 or later.
Applets can use applet parameters to customize their behavior. Applet parameters are
specified by using <PARAM> tags, which can only occur between an <APPLET> tag
and the closing </APPLET>. The PARAM tag has required modifiers named NAME
and VALUE, and it takes the form
<PARAM NAME="param-name" VALUE="param-value">
The parameters are available to the applet when it runs. An applet can use the
predefined method getParameter() to check for parameters specified in PARAM tags.
The getParameter() method has the following interface:
String getParameter(String paramName)
The parameter paramName corresponds to the param-name in a PARAM tag. If the
specified paramName actually occurs in one of the PARAM tags, then getParameter
returns the associated param-value. If the specified paramName does not occur in any
PARAM tag, then getParameter returns the value null. Parameter names are case-
sensitive, so you can't use "size" in the PARAM tag and ask for "Size" in
getParameter.
By the way, if you put anything besides PARAM tags between <APPLET> and
</APPLET>, it will be ignored by any browser that supports Java. On the other hand,
a browser that does not support Java will ignore the APPLET and PARAM tags. This
means that if you put a message such as "Your browser doesn't support Java" between
<APPLET> and </APPLET>, then that message will only appear in browsers that
don't support Java.
Here is an example of an APPLET tag with PARAMs and some extra text for display
in browsers that don't support Java:
<APPLET code="ShowMessage.class" WIDTH=200 HEIGHT=50>
<PARAM NAME="message" VALUE="Goodbye World!">
<PARAM NAME="font" VALUE="Serif">
<PARAM NAME="size" VALUE="36">
<p align=center>Sorry, but your browser doesn't support Java!</p>
</APPLET>
The applet ShowMessage would presumably read these parameters in its init()
method, which might go something like this:
String display; // Instance variable: message to be displayed.
String fontName; // Instance variable: font to use for display.

public void init() {


String value;
value = getParameter("message"); // Get message PARAM, if any.
if (value == null)
display = "Hello World!"; // default value
else
display = value; // Value from PARAM tag.
value = getParameter("font");
if (value == null)
fontName = "SansSerif"
else
fontName = value;
.
.
.
Dealing with the size parameter would be just a little harder, since a parameter value
is always a String, and the size is supposed to be an int. This means that the String
value must somehow be converted to an int. We'll worry about how to do that later.

Graphics and Painting

EVERYTHING YOU SEE ON A COMPUTER SCREEN has to be drawn there, even


the text. The Java API includes a range of classes and methods that are devoted to
drawing. In this section, I'll look at some of the most basic of these.
An applet is an example of a GUI component. The term component refers to a visual
element in a GUI, including buttons, menus, text-input boxes, scroll bars, check
boxes, and so on. In Java, GUI components are represented by objects belonging to
subclasses of the class java.awt.Component. Most components in the Swing GUI --
although not top-level components like JApplet -- belong to subclasses of the class
javax.swing.JComponent. Every component is responsible for drawing itself. For
example, if you want to use a standard component, you only have to add it to your
applet. You don't have to worry about painting it on the screen. That will happen
automatically.
Sometimes, however, you do want to draw on a component. You will have to do this
whenever you want to display something that is not included among the standard, pre-
defined component classes. When you want to do this, you have to define your own
component class and provide a method in that class for drawing the component.when
painting on a plain, non-Swing Applet, the drawing is done in a paint() method. To do
custom drawing, you have to define a subclass of Applet and include a paint() method
to do the drawing. However, when it comes to Swing and JApplets, things are a little
more complicated. You should not draw directly on JApplets or on other top-level
Swing components. Instead, you should make a separate component to use as a
drawing surface, and you should add that component to the JApplet. You will have to
write a class to represent the drawing surface, so programming a JApplet that does
custom drawing will always involve writing at least two classes: a class for the applet
itself and a class for the drawing surface. Typically, the class for the drawing surface
will be defined as a subclass of javax.swing.JPanel, which by default is nothing but a
blank area on the screen. A JPanel, like any JComponent, draws its content in the
method
public void paintComponent(Graphics g)
To create a drawing surface, you should define a subclass of JPanel and provide a
custom paintComponent() method. Create an object belonging to your new class, and
add it to your JApplet. When the time comes for your component to be drawn on the
screen, the system will call its paintComponent() to do the drawing. All this is not
really as complicated as it might sound. We will go over this in more detail when the
time comes.
Note that the paintComponent() method has a parameter of type Graphics. The
Graphics object will be provided by the system when it calls your method. You need
this object to do the actual drawing. To do any drawing at all in Java, you need a
graphics context. A graphics context is an object belonging to the class,
java.awt.Graphics. Instance methods are provided in this class for drawing shapes,
text, and images. Any given Graphics object can draw to only one location. In this
chapter, that location will always be a GUI component belonging to some subclass of
JComponent. The Graphics class is an abstract class, which means that it is impossible
to create a graphics context directly, with a constructor. There are actually two ways
to get a graphics context for drawing on a component: First of all, of course, when the
paintComponent() method of a component is called by the system, the parameter to
that method is a graphics context for drawing on the component. Second, each
component has an instance method called getGraphics(). This method is a function
that returns a graphics context that can be used for drawing on the component outside
its paintComponent() method. The official line is that you should not do this, and I
will avoid it for the most part. But I have found it convenient to use getGraphics() in
some cases, since it can mean better performance for certain types of drawing.
(Anyway, if the people who designed Java really didn't want us to use it, they
shouldn't have made the getGraphics() method public!)

Most components do, in fact, do all drawing operations in their paintComponent()


methods. What happens if, in the middle of some other method, you realize that the
content of the component needs to be changed? You should not call
paintComponent() directly to make the change; this method is meant to be called only
by the system. Instead, you have to inform the system that the component needs to be
redrawn, and let the system do its job by calling paintComponent(). You do this by
calling the repaint() method. The method
public void repaint();
is defined in the Component class, and so can be used with
any component. You should call repaint() to inform the
system that the component needs to be redrawn. The
repaint() method returns immediately, without doing any painting itself. The system
will call the component's paintComponent() method later, as soon as it gets a chance
to do so, after processing other pending events if there are any.
Note that the system can also call paintComponent() for other reasons. It is called
when the component first appears on the screen. It will also be called if the
component is covered up by another window and then uncovered. The system does
not save a copy of the component's contents when it is covered. When it is uncovered,
the component is responsible for redrawing itself. (As you will see, some of our early
examples will not be able to do this correctly.)
This means that, to work properly, the paintComponent() method must be smart
enough to correctly redraw the component at any time. To make this possible, a
program should store data about the state of the component in its instance variables.
These variables should contain all the information necessary to redraw the component
completely. The paintComponent() method should use the data in these variables to
decide what to draw. When the program wants to change the content of the
component, it should not simply draw the new content. It should change the values of
the relevant variables and call repaint(). When the system calls paintComponent(), this
method will use the new values of the variables and will draw the component with the
desired modifications. This might seem a roundabout way of doing things. Why not
just draw the modifications directly? There are at least two reasons. First of all, it
really does turn out to be easier to get things right if all drawing is done in one
method. Second, even if you did make modifications directly, you would still have to
make the paintComponent() method aware of them in some way so that it will be able
to redraw the component correctly when it is covered and uncovered.
You will see how all this works in practice as we work through examples in the rest of
this chapter. For now, we will spend the rest of this section looking at how to get some
actual drawing done.

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.

Note: This applet uses bad style, because every time


the paintComponent() method is called, new random values are
used. This means that a different picture will be drawn each
time. This is particularly bad if only part of the applet
needs to be redrawn, since then the applet will contain
cut-off pieces of messages.

When this file is compiled, it produces two classes,


RandomStrings.class and RandomStrings$Display.class. Both
classes are required to use the applet.
*/

import java.awt.*;
import javax.swing.*;

public class RandomStrings extends JApplet {

String message; // The message to be displayed. This can be set in


// an applet param with name "message". If no
// value is provided in the applet tag, then
// the string "Java!" is used as the default.

Font font1, font2, font3, font4, font5; // The five fonts.

Display drawingSurface; // This is the component on which the


// drawing will actually be done. It
// is defined by a nested class that
// can be found below.

public void init() {


// Called by the system to initialize the applet.

message = getParameter("message");
if (message == null)
message = "Java!";

font1 = new Font("Serif", Font.BOLD, 14);


font2 = new Font("SansSerif", Font.BOLD + Font.ITALIC, 24);
font3 = new Font("Monospaced", Font.PLAIN, 20);
font4 = new Font("Dialog", Font.PLAIN, 30);
font5 = new Font("Serif", Font.ITALIC, 36);
drawingSurface = new Display(); // Create the drawing surface.
drawingSurface.setBackground(Color.black);

setContentPane(drawingSurface); // Since drawingSurface will fill


// the entire applet, we simply
// replace the applet's content
// pane with drawingSurface.
} // end init()

class Display extends JPanel {


// This nested class defines a JPanel that is used
// for displaying the content of the applet. An
// object of this class is used as the content pane
// of the applet. Note that since this is a nested
// non-static class, it has access to the instance
// variables of the main class such as message and font1.

public void paintComponent(Graphics g) {

super.paintComponent(g); // Call the paintComponent method from


// the superclass, JPanel. This simply
// fills the entire component with the
// component's background color.

int width = getSize().width; // Get this component's width.


int height = getSize().height; // Get this component's height.

for (int i = 0; i < 25; i++) {

// Draw one string. First, set the font to be one of the five
// available fonts, at random.

int fontNum = (int)(5*Math.random()) + 1;


switch (fontNum) {
case 1:
g.setFont(font1);
break;
case 2:
g.setFont(font2);
break;
case 3:
g.setFont(font3);
break;
case 4:
g.setFont(font4);
break;
case 5:
g.setFont(font5);
break;
} // end switch

// Set the color to a bright, saturated color, with random hue.

float hue = (float)Math.random();


g.setColor( Color.getHSBColor(hue, 1.0F, 1.0F) );

// Select the position of the string, at random.

int x,y;
x = -50 + (int)(Math.random()*(width+40));
y = (int)(Math.random()*(height+20));

// Draw the message.

g.drawString(message,x,y);

} // end for

} // end paintComponent()

} // end nested class Display

} // end class RandomStrings

Mouse Events

EVENTS ARE CENTRAL to programming for a graphical user interface. A GUI


program doesn't have a main() routine that outlines what will happen when the
program is run, in a step-by-step process from beginning to end. Instead, the program
must be prepared to respond to various kinds of events that can happen at
unpredictable times and in an order that the program doesn't control. The most basic
kinds of events are generated by the mouse and keyboard. The user can press any key
on the keyboard, move the mouse, or press a button on the mouse. The user can do
any of these things at any time, and the computer has to respond appropriately.
In Java, events are represented by objects. When an event occurs, the system collects
all the information relevant to the event and constructs an object to contain that
information. Different types of events are represented by objects belonging to
different classes. For example, when the user presses one of the buttons on a mouse,
an object belonging to a class called MouseEvent is constructed. The object contains
information such as the GUI component on which the user clicked, the (x,y)
coordinates of the point in the component where the click occurred, and which button
on the mouse was pressed. When the user presses a key on the keyboard, a KeyEvent
is created. After the event object is constructed, it is passed as a parameter to a
designated subroutine. By writing that subroutine, the programmer says what should
happen when the event occurs.
As a Java programmer, you get a fairly high-level view of events. There is lot of
processing that goes on between the time that the user presses a key or moves the
mouse and the time that a subroutine in your program is called to respond to the
event. Fortunately, you don't need to know much about that processing. But you
should understand this much: Even though your GUI program doesn't have a main()
routine, there is a sort of main routine running somewhere that executes a loop of the
form
while the program is still running:
Wait for the next event to occur
Call a subroutine to handle the event
This loop is called an event loop. Every GUI program has an event loop. In Java, you
don't have to write the loop. It's part of "the system." If you write a GUI program in
some other language, you might have to provide a main routine that runs an event
loop.
In this section, we'll look at handling mouse events in Java, and we'll cover the
framework for handling events in general. The next section will cover keyboard
events. Java also has other types of events, which are produced by GUI components.
These will be introduced in Section 6 and covered in detail in Section 7.3.

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.

MouseEvent and MouseListener


The MouseListener interface specifies five different instance methods:
public void mousePressed(MouseEvent evt);
public void mouseReleased(MouseEvent evt);
public void mouseClicked(MouseEvent evt);
public void mouseEntered(MouseEvent evt);
public void mouseExited(MouseEvent evt);
The mousePressed method is called as soon as the user presses down on one of the
mouse buttons, and mouseReleased is called when the user releases a button. These
are the two methods that are most commonly used, but any mouse listener object must
define all five methods. You can leave the body of a method empty if you don't want
to define a response. The mouseClicked method is called if the user presses a mouse
button and then releases it quickly, without moving the mouse. (When the user does
this, all three routines -- mousePressed, mouseReleased, and mouseClicked -- will be
called in that order.) In most cases, you should define mousePressed instead of
mouseClicked. The mouseEntered and mouseExited methods are called when the
mouse cursor enters or leaves the component. For example, if you want the
component to change appearance whenever the user moves the mouse over the
component, you could define these two methods.
As an example, let's look at an applet that does something when the user clicks on it.
Here's an improved version of the RandomStrings applet from the end of the previous
section. In this version, the applet will redraw itself when you click on it:

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();
}

// The following empty routines are required by the


// MouseListener interface:

public void mouseEntered(MouseEvent evt) { }


public void mouseExited(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseReleased(MouseEvent evt) { }
Fourth and finally, the applet must be registered to listen for mouse events. Since the
drawing surface fills the entire applet, it is actually the drawing surface on which the
user clicks. We want the applet to listen for mouse events on the drawing surface. This
can be arranged by adding this line to the applet's init() method:
drawingSurface.addMouseListener(this);
This calls the addMouseListener() method in the drawing surface object. It tells that
object where to send the mouse events that it generates. The parameter to this method
is the object that will be listening for the events. In this case, the listening object is the
applet itself. The special variable "this" is used here to refer to the applet. (See Section
5.5. When used in the definition of an instance method, "this" refers to the object that
contains the method.)
We could make all these changes in the source code of the original RandomStrings
applet. However, since we are supposed to be doing object-oriented programming, it
might be instructive to write a subclass that contains the changes. This will let us
build on previous work and concentrate just on the modifications. Here's the actual
source code for the above applet. It uses "super", another special variable from
Section 5.5.
import java.awt.event.*;

public class ClickableRandomStrings extends RandomStrings


implements MouseListener {

public void init() {


// When the applet is created, do the initialization
// of the superclass, RandomStrings. Then set this
// applet to listen for mouse events on the
// "drawingSurface". (The drawingSurface variable
// is defined in the RandomStrings class and
// represents a component that fills the entire applet.)
super.init();
drawingSurface.addMouseListener(this);
}

public void mousePressed(MouseEvent evt) {


// When user presses the mouse, tell the system to
// call the drawingSurface's paintComponent() method.
drawingSurface.repaint();
}

// The next four empty routines are required by the


// MouseListener interface.

public void mouseEntered(MouseEvent evt) { }


public void mouseExited(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseReleased(MouseEvent evt) { }

} // end class ClickableRandomStrings

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.*;

public class SimpleStamper extends JApplet {

public void init() {


// This method is called by the system to initialize
// the applet. An object belonging to the nested class
// Display is created and installed as the content
// pane of the applet. This Display object does
// all the real work.
Display display = new Display();
setContentPane(display);
}

class Display extends JPanel implements MouseListener {


// A nested class to represent the drawing surface that
// fills the applet.
Display() {
// This constructor simply sets the background color
// of the panel to be black and sets the panel to
// listen for mouse events on itself.
setBackground(Color.black);
addMouseListener(this);
}

public void mousePressed(MouseEvent evt) {


// Since this panel has been set to listen for mouse
// events on itself, this method will be called when the
// user clicks the mouse on the panel. (Since the panel
// fills the whole applet, that means clicking anywhere
// on the applet.)

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;
}

int x = evt.getX(); // x-coordinate where user clicked.


int y = evt.getY(); // y-coordinate where user clicked.

Graphics g = getGraphics(); // Graphics context for drawing


// directly on this JPanel.

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 );
}

g.dispose(); // We are finished with the graphics context,


// so dispose of it.

} // end mousePressed();

// The next four empty routines are required by the


// MouseListener interface.

public void mouseEntered(MouseEvent evt) { }


public void mouseExited(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseReleased(MouseEvent evt) { }

} // end nested class Display

} // end class SimpleStamper

MouseMotionListeners and Dragging


Whenever the mouse is moved, it generates events. The operating system of the
computer detects these events and uses them to move the mouse cursor on the screen.
It is also possible for a program to listen for these "mouse motion" events and respond
to them. The most common reason to do so is to implement dragging. Dragging
occurs when the user moves the mouse while holding down a mouse button.
The methods for responding to mouse motion events are defined in an interface
named MouseMotionListener. This interface specifies two event-handling methods:
public void mouseDragged(MouseEvent evt);
public void mouseMoved(MouseEvent evt);
The mouseDragged method is called if the mouse is moved while a button on the
mouse is pressed. If the mouse is moved while no mouse button is down, then
mouseMoved is called instead. The parameter, evt, is an object of type MouseEvent. It
contains the x and y coordinates of the mouse's location. As long as the user continues
to move the mouse, one of these methods will be called over and over. (So many
events are generated that it would be inefficient for a program to hear them all, if it
doesn't want to do anything in response. This is why the mouse motion event-handlers
are defined in a separate interface from the other mouse events: You can listen for the
mouse events defined in MouseListener without automatically hearing all mouse
motion events as well.)
If you want your program to respond to mouse motion events, you must create an
object that implements the MouseMotionListener interface, and you must register that
object to listen for events. The registration is done by calling a component's
addMouseMotionListener method. The object will then listen for mouseDragged and
mouseMoved events associated with that component. In most cases, the listener object
will also implement the MouseListener interface so that it can respond to the other
mouse events as well. For example, if we want an applet to listen for all mouse events
associated with a drawingSurface object, then the definition of the applet class might
have the form:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Mouser extends JApplet


implements MouseListener, MouseMotionListener {

public void init() { // set up the applet


drawingSurface.addMouseListener(this);
drawingSurface.addMouseMotionListener(this);
. . . // other initializations
}
.
. // Define the seven MouseListener and
. // MouseMotionListener methods. Also, there
. // can be other variables and methods.
Here is a small sample applet that displays information about mouse events. It is
programmed to respond to any of the seven different kinds of mouse events by
displaying the coordinates of the mouse, the type of event, and a list of the modifier
keys that are down (Shift, Control, Meta, and Alt). Experiment to see what happens
when you use the mouse on the applet. The source code for this applet can be found in
SimpleTrackMouse.java. I encourage you to read the source code. You should now be
familiar with all the techniques that it uses.

It is interesting to look at what a program needs to do in order to respond to dragging


operations. In general, the response involves three methods: mousePressed(),
mouseDragged(), and mouseReleased(). The dragging gesture starts when the user
presses a mouse button, it continues while the mouse is dragged, and it ends when the
user releases the button. This means that the programming for the response to one
dragging gesture must be spread out over the three methods! Furthermore, the
mouseDragged() method can be called many times as the mouse moves. To keep track
of what is going on between one method call and the next, you need to set up some
instance variables. In many applications, for example, in order to process a
mouseDragged event, you need to remember the previous coordinates of the mouse.
You can store this information in two instance variables prevX and prevY of type int.
I also suggest having a boolean variable, dragging, which is set to true while a
dragging gesture is being processed. This is necessary because not every
mousePressed event is the beginning of a dragging gesture. The mouseDragged and
mouseReleased methods can use the value of dragging to check whether a drag
operation is actually in progress. You might need other instance variables as well, but
in general outline, the code for handling dragging looks like this:
private int prevX, prevY; // Most recently processed mouse coords.
private boolean dragging; // Set to true when dragging is in process.
. . . // other instance variables for use in dragging

public void mousePressed(MouseEvent evt) {


if ( we-want-to-start-dragging ) {
dragging = true;
prevX = evt.getX(); // Remember starting position.
prevY = evt.getY();
}
.
. // Other processing.
.
}

public void mouseDragged(MouseEvent evt) {


if ( dragging == false ) // First, check if we are
return; // processing a dragging gesture.
int x = evt.getX(); // Current position of Mouse.
int y = evt.getY();
.
. // Process a mouse movement from (prevX, prevY) to (x,y).
.
prevX = x; // Remember the current position for the next call.
prevY = y;
}

public void mouseReleased(MouseEvent evt) {


if ( dragging == false ) // First, check if we are
return; // processing a dragging gesture.
dragging = false; // We are done dragging.
.
. // Other processing and clean-up.
.
}
As an example, let's look at a typical use of dragging: allowing the user to sketch a
curve by dragging the mouse. This example also shows many other features of
graphics and mouse processing. In the following applet, you can draw a curve by
dragging the mouse on the large white area. Select a color for drawing by clicking on
one of the colored rectangles on the right. Note that the selected color is framed with a
white border. Clear your drawing by clicking in the square labeled "CLEAR". (This
applet still has the old problem that the drawing will disappear if you cover the applet
and uncover it.)

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.

Anonymous Event Handlers and Adapter Classes


As I mentioned above, it is a fairly common practice to use anonymous nested classes
to define listener objects. As discussed in Section 5.6, a special form of the new
operator is used to create an object that belongs to an anonymous class. For example,
a mouse listener object can be created with an expression of the form:
new MouseListener() {
public void mousePressed(MouseEvent evt) { . . . }
public void mouseReleased(MouseEvent evt) { . . . }
public void mouseClicked(MouseEvent evt) { . . . }
public void mouseEntered(MouseEvent evt) { . . . }
public void mouseExited(MouseEvent evt) { . . . }
}
This is all just one long expression that both defines an un-named class and creates an
object that belongs to that class. To use the object as a mouse listener, it should be
passed as the parameter to some component's addMouseListener() method in a
command of the form:
component.addMouseListener( new MouseListener() {
public void mousePressed(MouseEvent evt) { . . . }
public void mouseReleased(MouseEvent evt) { . . . }
public void mouseClicked(MouseEvent evt) { . . . }
public void mouseEntered(MouseEvent evt) { . . . }
public void mouseExited(MouseEvent evt) { . . . }
} );
Now, in a typical application, most of the method definitions in this class will be
empty. A class that implements an interface must provide definitions for all the
methods in that interface, even if the definitions are empty. To avoid the tedium of
writing empty method definitions in cases like this, Java provides adapter classes. An
adapter class implements a listener interface by providing empty definitions for all the
methods in the interface. An adapter class is only useful as a basis for making
subclasses. In the subclass, you can define just those methods that you actually want
to use. For the remaining methods, the empty definitions that are provided by the
adapter class will be used. The adapter class for the MouseListener interface is named
MouseAdapter. For example, if you want a mouse listener that only responds to
mouse-pressed events, you can use a command of the form:
component.addMouseListener( new MouseAdapter() {
public void mousePressed(MouseEvent evt) { . . . }
} );
To see how this works in a real example, let's write another version of the
ClickableRandomStrings applet that uses an anonymous class based on
MouseAdapter to handle mouse events:
import java.awt.event.*;

public class ClickableRandomStrings2 extends RandomStrings {

public void init() {


// When the applet is created, do the initialization
// of the superclass, RandomStrings. Then add a
// mouse listener to listen for mouse events on the
// "drawingSurface". (drawingSurface is defined
// in the superclass, RandomStrings.)

super.init();

drawingSurface.addMouseListener( new MouseAdapter() {


public void mousePressed(MouseEvent evt) {
// When user presses the mouse, tell the system to
// call the drawingSurface's paintComponent() method.
drawingSurface.repaint();
}
} );
} // end init()

} // end class ClickableRandomStrings2

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.

int key = evt.getKeyCode(); // Keyboard code for the pressed key.

if (key == KeyEvent.VK_LEFT) { // left-arrow key; move square up


squareLeft -= 8;
if (squareLeft < 3)
squareLeft = 3;
canvas.repaint();
}
else if (key == KeyEvent.VK_RIGHT) { // right-arrow key; move right
squareLeft += 8;
if (squareLeft > getSize().width - 3 - SQUARE_SIZE)
squareLeft = getSize().width - 3 - SQUARE_SIZE;
canvas.repaint();
}
else if (key == KeyEvent.VK_UP) { // up-arrow key; move up
squareTop -= 8;
if (squareTop < 3)
squareTop = 3;
canvas.repaint();
}
else if (key == KeyEvent.VK_DOWN) { // down-arrow key; move down
squareTop += 8;
if (squareTop > getSize().height - 3 - SQUARE_SIZE)
squareTop = getSize().height - 3 - SQUARE_SIZE;
canvas.repaint();
}

} // 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) {

int code = evt.getKeyCode(); // which key was pressed

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.

Introduction to Layouts and Components

IN PRECEDING SECTIONS, YOU'VE SEEN how to use a graphics context to draw


on the screen and how to handle mouse events and keyboard events. In one sense,
that's all there is to GUI programming. If you're willing to program all the drawing
and handle all the mouse and keyboard events, you have nothing more to learn.
However, you would either be doing a lot more work than you need to do, or you
would be limiting yourself to very simple user interfaces. A typical user interface uses
standard GUI components such as buttons, scroll bars, text-input boxes, and menus.
These components have already been written for you, so you don't have to duplicate
the work involved in developing them. They know how to draw themselves, and they
can handle the details of processing the mouse and keyboard events that concern
them.
Consider one of the simplest user interface components, a push button. The button has
a border, and it displays some text. This text can be changed. Sometimes the button is
disabled, so that clicking on it doesn't have any effect. When it is disabled, its
appearance changes. When the user clicks on the push button, the button changes
appearance while the mouse button is pressed and changes back when the mouse
button is released. In fact, it's more complicated than that. If the user moves the
mouse outside the push button before releasing the mouse button, the button changes
to its regular appearance. To implement this, it is necessary to respond to mouse exit
or mouse drag events. Furthermore, on many platforms, a button can receive the input
focus. The button changes appearance when it has the focus. If the button has the
focus and the user presses the space bar, the button is triggered. This means that the
button must respond to keyboard and focus events as well.
Fortunately, you don't have to program any of this, provided you use an object
belonging to the standard class javax.swing.JButton. A JButton object draws itself and
processes mouse, keyboard, and focus events on its own. You only hear from the
Button when the user triggers it by clicking on it or pressing the space bar while the
button has the input focus. When this happens, the JButton object creates an event
object belonging to the class java.awt.event.ActionEvent. The event object is sent to
any registered listeners to tell them that the button has been pushed. Your program
gets only the information it needs -- the fact that a button was pushed.

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() {

display = new Display();


// The component that displays "Hello World".

getContentPane().add(display, BorderLayout.CENTER);
// Adds the display panel to the CENTER position of the
// JApplet's content pane.

JPanel buttonBar = new JPanel();


// This panel will hold three buttons and will appear
// at the bottom of the applet.

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.

JButton greenButton = new JButton("Green"); // the second button


greenButton.addActionListener(this);
buttonBar.add(greenButton);

JButton blueButton = new JButton("Blue"); // the third button


blueButton.addActionListener(this);
buttonBar.add(blueButton);

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.

int colorNum; // Keeps track of which color is displayed;


// 1 for red, 2 for green, 3 for blue.

Font textFont; // The font in which the message is displayed.


// A font object represents a certain size and
// style of text drawn on the screen.

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.
}

void setColor(int code) {


// This method is provided to be called by the
// main class when it wants to set the color of the
// message. The parameter value should be 1, 2, or 3
// to indicate the desired color.
colorNum = code;
repaint(); // Tell the system to repaint this component.
}

public void paintComponent(Graphics g){


// This routine is called by the system whenever this
// panel needs to be drawn or redrawn. It first calls
// super.paintComponent() to fill the panel with the
// background color. It then displays the message
// "Hello World" in the proper color and font.
super.paintComponent(g);
switch (colorNum) { // Set the color.
case 1:
g.setColor(Color.red);
break;
case 2:
g.setColor(Color.green);
break;
case 3:
g.setColor(Color.blue);
break;
}
g.setFont(textFont); // Set the font.
g.drawString("Hello World!", 25,50); // Draw the message.
} // end paintComponent
} // end nested class Display

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.

String command = evt.getActionCommand();


// The "action command" associated with the event
// is the text on the button that was clicked.

if (command.equals("Red")) // Set the color.


display.setColor(1);
else if (command.equals("Green"))
display.setColor(2);
else if (command.equals("Blue"))
display.setColor(3);

} // 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.

setBackground( new Color(130,50,40) );

HighLowCanvas board = new HighLowCanvas();


getContentPane().add(board, BorderLayout.CENTER);

JPanel buttonPanel = new JPanel();


buttonPanel.setBackground( new Color(220,200,180) );
getContentPane().add(buttonPanel, BorderLayout.SOUTH);

JButton higher = new JButton( "Higher" );


higher.addActionListener(board);
buttonPanel.add(higher);

JButton lower = new JButton( "Lower" );


lower.addActionListener(board);
buttonPanel.add(lower);

JButton newGame = new JButton( "New Game" );


newGame.addActionListener(board);
buttonPanel.add(newGame);

} // end init()

In programming the drawing surface class, HighLowCanvas, it is important to think in


terms of the states that the game can be in, how the state can change, and how the
response to events can depend on the state. The approach that produced the original,
text-oriented game in Section 5.3 is not appropriate here. Trying to think about the
game in terms of a process that goes step-by-step from beginning to end is more likely
to confuse you than to help you.
The state of the game includes the cards and the message. The cards are stored in an
object of type Hand. The message is a String. These values are stored in instance
variables. There is also another, less obvious aspect of the state: Sometimes a game is
in progress, and the user is supposed to make a prediction about the next card.
Sometimes we are between games, and the user is supposed to click the "New Game"
button. It's a good idea to keep track of this basic difference in state. The canvas class
uses a boolean variable named gameInProgress for this purpose.
The state of the applet can change whenever the user clicks on a button. The
HighLowCanvas class implements the ActionListener interface and defines an
actionPerformed() method to respond to the user's clicks. This method simply calls
one of three other methods, doHigher(), doLower(), or newGame(), depending on
which button was pressed. It's in these three event-handling methods that the action of
the game takes place.
We don't want to let the user start a new game if a game is currently in progress. That
would be cheating. So, the response in the newGame() method is different depending
on whether the state variable gameInProgress is true or false. If a game is in progress,
the message instance variable should be set to show an error message. If a game is not
in progress, then all the state variables should be set to appropriate values for the
beginning of a new game. In any case, the board must be repainted so that the user
can see that the state has changed. The complete newGame() method is as follows:
void doNewGame() {
// Called by the constructor, and called by actionPerformed()
// when the user clicks the "New Game" button. Start a new game.
if (gameInProgress) {
// If the current game is not over, it is an error to try
// to start a new game.
message = "You still have to finish this game!";
repaint();
return;
}
deck = new Deck(); // Create a deck and hand to use for this game.
hand = new Hand();
deck.shuffle();
hand.addCard( deck.dealCard() ); // Deal the first card.
message = "Is the next card higher or lower?";
gameInProgress = true; // State changes! A game has started.
repaint();
}
The doHigher() and doLower() methods are almost identical to each other (and could
probably have been combined into one method with a parameter, if I were more
clever). Let's look at the doHigher() routine. This is called when the user clicks the
"Higher" button. This only makes sense if a game is in progress, so the first thing
doHigher() should do is check the value of the state variable gameInProgress. If the
value is false, then doHigher() should just set up an error message. If a game is in
progress, a new card should be added to the hand and the user's prediction should be
tested. The user might win or lose at this time. If so, the value of the state variable
gameInProgress must be set to false because the game is over. In any case, the board
is repainted to show the new state. Here is the doHigher() method:
void doHigher() {
// Called by actionPerformed() when user clicks "Higher".
// Check the user's prediction. Game ends if user guessed
// wrong or if the user has made three correct predictions.
if (gameInProgress == false) {
// If the game has ended, it was an error to click "Higher",
// so set up an error message and abort processing.
message = "Click \"New Game\" to start a new game!";
repaint();
return;
}
hand.addCard( deck.dealCard() ); // Deal a card to the hand.
int cardCt = hand.getCardCount(); // How many cards in the hand?
Card thisCard = hand.getCard( cardCt - 1 ); // Card just dealt.
Card prevCard = hand.getCard( cardCt - 2 ); // The previous card.
if ( thisCard.getValue() < prevCard.getValue() ) {
gameInProgress = false;
message = "Too bad! You lose.";
}
else if ( thisCard.getValue() == prevCard.getValue() ) {
gameInProgress = false;
message = "Too bad! You lose on ties.";
}
else if ( cardCt == 4) {
gameInProgress = false;
message = "You win! You made three correct guesses.";
}
else {
message = "Got it right! Try for " + cardCt + ".";
}
repaint();
}
The paintComponent() method of the HighLowCanvas class uses the values in the
state variables to decide what to show. It displays the string stored in the message
variable. It draws each of the cards in the hand. There is one little tricky bit: If a game
is in progress, it draws an extra face-down card, which is not in the hand, to represent
the next card in the deck. Drawing the cards requires some care and computation. I
wrote a method, "void drawCard(Graphics g, Card card, int x, int y)", which draws a
card with its upper left corner at the point (x,y). The paintComponent() routine
decides where to draw each card and calls this routine to do the drawing. You can
check out all the details in the source code, HighLowGUI.java.

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

Advanced GUI Programming

IT'S POSSIBLE TO PROGRAM A WIDE VARIETY of GUI applications using only


the techniques covered in the previous chapter. In many cases, the basic events,
components, layouts, and graphics routines covered in that chapter suffice. But the
Swing graphical user interface library is far richer than what we have seen so far, and
it can be used to build highly sophisticated applications. This chapter is a further
introduction to Swing. Although the title of the chapter is "Advanced GUI
Programming," it is still just an introduction. Full coverage of Swing would require at
least another complete book.
In this chapter, we'll take a more detailed look at Swing, starting with a few more
features of the Graphics class. We'll cover a number of new layout managers,
component classes, and event types, and we'll see how to open independent windows
and dialog boxes on the screen. We'll also look at two other programming techniques,
timers and threads.
The material in this chapter will be used in a number of examples and programming
exercises in future chapters. Aside from that, this chapter is not a prerequisite the rest
of this textbook. If you skip it, you will not miss out on any fundamental
programming concepts -- just a lot of the fun of GUI programming.

More About Graphics

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.

Off-screen Images and Double Buffering


In addition to images in image files, objects of type Image can be used to represent
images stored in the computer's memory. What makes such images particularly useful
is that it is possible to draw to an Image in the computer's memory. This drawing is
not visible to the user. Later, however, the image can be copied very quickly to the
screen. In fact, this technique is used automatically in Swing to draw the components
that you see on the screen. When the on-screen picture needs to be redrawn, the new
picture is drawn step-by-step to an off-screen image. This can take some time. If all
this drawing were done on screen, the user would see the image flicker as it is drawn.
Instead, a complete new image replaces the old one on the screen almost
instantaneously. The user doesn't see all the steps involved in redrawing. This
technique makes smooth, flicker-free animation and dragging easy in Swing. (It is not
at all easy or automatic when using the older AWT GUI components. This is one big
advantage of Swing.)
The technique of drawing an off-screen image and then quickly copying the image to
the screen is called double buffering. The name comes from the term "frame buffer,"
which refers to the region in memory that holds the image on the screen. (In fact, true
double buffering uses two frame buffers. The video card can display either frame
buffer on the screen and can switch instantaneously from one frame buffer to the
other. One frame buffer is used to draw a new image for the screen. Then the video
card is told to switch from one frame buffer to the other. No copying of memory is
involved. Double-buffering as it is implemented in Java does require copying, which
takes some time and is not perfectly flicker-free.)
It's possible to turn off double buffering in Swing (although there is little reason to do
so). To help you understand the effect of double buffering, here are two applets that
are identical, except that one uses double buffering and one does not. You can drag the
red squares around the applets. I've added a lot of lines in the background to increase
the time it takes to redraw the applet. You should notice an annoying flicker in the
non-double-buffered applet on the left:

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.

/* Some variables used for double-buffering. */

Image OSI; // The off-screen image (created in paintComponent()).

int widthOfOSI, heightOfOSI; // Current width and height of OSI.


// These are checked against the size
// of the component, to detect any change
// in the component's size. If the size
// has changed, a new OSI is created.
// The picture in the off-screen image
// is lost when that happens.

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.
}
}

public void paintComponent(Graphics g) {


// Paint the component by copying the off-screen image onto
// the screen. First, call checkOffScreenImage() to make
// sure that the off-screen image is ready.
// (Note that since the image fills the entire component,
// it is not necessary to call super.paintComponent(g).)

checkOffScreenImage();
g.drawImage(OSI, 0, 0, null); // Copy OSI onto the screen.

// Note: At this point, we could draw hiliting or other extra


// stuff on top of the picture in the off-screen image.
}

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.
}

Rectangles, Clipping, and Repainting


The example we've just looked at has one glaring inefficiency: Every time the user
drags the mouse, the entire applet is repainted, even though only a small part of the
picture might need to be changed. It's possible to improve on this by repainting only a
part of the applet. There is a second version of the repaint() command that makes this
possible. If comp is a variable that refers to some component, then
comp.repaint( x, y, width, height );
tells the system that a rectangular area in the component needs to be repainted. The
first two parameters, x and y, specify the upper left corner of the rectangle and the
next two parameters give the width and height of the rectangle. In response to this, the
system will call paintComponent() as usual, but the graphics context will be set up for
drawing only in the specified region. This is done by setting the clip region of the
graphics context. The clip region of a graphics context specifies the area where
drawing can occur. Any attempt to use the graphics context to draw outside the clip
region is ignored. (If part of a shape lies outside the clip region, that part is "clipped
off" before the shape is drawn on the screen.) Only the pixels inside the clip region
need to have their color set, and this can be much more efficient than setting the color
of every pixel in the component. When an off-screen image is copied onto the
component, only the part that lies within the clip region is actually copied.
The techniques covered in this section can be used to improve the simple painting
program from Section 6.6. The new version uses an off-screen image to save a copy
of the user's work, and it uses the version of repaint() discussed above. As before, the
user can draw a free-hand sketch. However, in this version, the user can also choose
to draw several shapes by selecting from the pop-up menu in the upper right. Try it
out! Check that when you cover up the applet with another window, your drawing is
still there when you uncover it.

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);

More about Layouts and Components

SWING INCLUDES A VARIETY of GUI components. We have already encountered


a few of these, such as JApplet, JButton, and JPanel. In then next few sections, we
will be studying Swing components in more detail.
Most Swing components are defined by subclasses of the class
javax.swing.JComponent. A JComponent cannot stand on its own. It must
be contained in some other component. We have seen, for example, that
JPanels can act as containers for other JComponents. At the top level of
this containment hierarchy are classes such as JApplet. A JApplet is not a
JComponent, but it can serve as a container for JComponents. A JApplet
is a top-level container that is meant to appear on a Web page. In
Section 7, we'll see two more top-level container classes, JFrame and JDialog, which
can be used to create independent windows on the computer screen.
The basic properties of components and containers are actually defined by the AWT
classes java.awt.Component and java.awt.Container. Occasionally, you will see these
classes used in Swing. For example, the getContentPane() method in a JApplet has a
return type of Container rather than JPanel or JComponent as you might expect.
A JPanel is a container that is itself a JComponent. A JPanel can contain other
components, and it can in turn be contained in another component. The fact that
panels can contain other panels means that you can have many levels of components
containing other components, as shown in the illustration on the right. Several other
classes, such as Box and TabbedPane, also define components that can be used as
containers. This leads to two questions: How are components added to a container?
How are their sizes and positions controlled?
The sizes and positions of the components in a container are usually controlled by a
layout manager. Different layout managers implement different ways of arranging
components. There are several predefined layout manager classes, including
FlowLayout, GridLayout, BorderLayout, BoxLayout, CardLayout and
GridBagLayout. All these classes are defined in the package java.awt. It is also
possible to define new layout managers, if none of these suit your purpose. Every
container is assigned a default layout manager when it is first created. For JPanels, the
default layout manager belongs to the class FlowLayout. The content pane of a
JApplet uses a BorderLayout by default. You can change the layout manager of a
container using its setLayout() method.
It is even possible to set the LayoutManager of a container to be null. This allows you
to take complete charge of laying out the components in the container. I will discuss
this possibility and give an example in the last part of Section 4.
As for adding components to a container, that's easy. You just use one of the
container's add() methods. There are several add() methods. Which one you should
use depends on what type of LayoutManager is being used by the container, so I will
discuss the appropriate add() methods as I go along.
I have often found it to be fairly difficult to get the exact layout that I want in my
applets and windows. I will briefly discuss several layout manager classes here, but
using them well will require practice and experimentation.

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.

BoxLayout and the Box Class


A BoxLayout simply lines up components in a single horizontal row or in a single
vertical column. BoxLayouts are generally used with objects belonging to the class
javax.swing.Box. A Box is just a container that uses a BoxLayout. The Box class
contains two static methods for creating boxes:
Box.createHorizontalBox();
and
Box.createVerticalBox();
These methods are used instead of a constructor to create box objects. For example, if
you want a Box to contain a horizontal row of components, you can create it with the
command:
Box hbox = Box.createHorizontalBox();
Components are added to a box using an add() method with one parameter, which
specifies the component that is to be added. The Box class has several static methods
that can be used to create specialized components for adding space to a box layout.
For example, if width is an integer, then Box.createHorizontalStrut(width) creates a
component that is invisible except that it has the specified width and so takes up that
amount of horizontal space. You can add a horizontal strut between two components
in a horizontal box layout to leave space between the components. Similarly,
Box.createVerticalStrut(height) creates an invisible component that has the specified
height. For example, the following commands create a Box that contains four
(useless) buttons in a horizontal row, with ten pixels of space between the second and
third button:
Box hbox = Box.createHorizontalBox();
hbox.add( new JButton("First") );
hbox.add( new JButton("Second") );
hbox.add( Box.createHorizontalStrut(10) );
hbox.add( new JButton("Third") );
hbox.add( new JButton("Fourth") );
Horizontal Boxes can be used for the "toolbars" that you see in many
graphical user interfaces.

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));

Basic Components and Their Events

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 JButton Class


An object of class JButton is a push button. You've already seen buttons used in the
previous chapter, but we can use a review of JButtons as a reminder of what's
involved in using components, events, and listeners. (Some of the methods described
here are new.)
Constructors: The JButton class has a constructor that takes a string as a parameter.
This string becomes the text displayed on the button. For example: stopGoButton =
new JButton("Go")
Events: When the user clicks on a button, the button generates an event of type
ActionEvent. This event is sent to any listener that has been registered with the
button.
Listeners: An object that wants to handle events generated by buttons must implement
the ActionListener interface. This interface defines just one method, "pubic void
actionPerformed(ActionEvent evt)", which is called to notify the object of an action
event.
Registration of Listeners: In order to actually receive notification of an event from a
button, an ActionListener must be registered with the button. This is done with the
button's addActionListener() method. For example:
stopGoButton.addActionListener(buttonHandler);
Event methods: When actionPerformed(evt) is called by the button, the parameter,
evt, contains information about the event. This information can be retrieved by calling
methods in the ActionEvent class. In particular, evt.getActionCommand() returns a
String giving the command associated with the button. By default, this command is
the text that is displayed on the button. The method evt.getSource() returns a
reference to the Object that produced the event, that is, to the JButton that was
pressed. The return value is of type Object, not JButton, because other types of
components can also produce ActionEvents.
Component methods: There are several useful methods in the JButton class. For
example, stopGoButton.setText("Stop") changes the text displayed on the button to
"Stop". And stopGoButton.setActionCommand("sgb") changes the action command
associated to this button for action events.
Of course, JButtons also have all the general Component methods, such as
setEnabled() and setFont(). The setEnabled() and setText() methods of a button are
particularly useful for giving the user information about what is going on in the
program. A disabled button is better than a button that gives an obnoxious error
message such as "Sorry, you can't click on me now!"
By the way, it's possible for a JButton to display an icon instead of or in addition to
the text that it displays. An icon is simply a small image. Several other components
can also display icons. However, I will not cover this aspect of Swing in this book.
Consult a Java reference if you are interested.

The JLabel Class


JLabels are certainly the simplest type of component. An object of type JLabel is just
a single line of text. The text cannot be edited by the user, although it can be changed
by your program. The constructor for a JLabel specifies the text to be displayed:
JLabel message = new JLabel("Hello World!");
There is another constructor that specifies where in the label the text is located, if
there is extra space. The possible alignments are given by the constants JLabel.LEFT,
JLabel.CENTER, and JLabel.RIGHT. For example,
JLabel message = new JLabel("Hello World!", JLabel.CENTER);
creates a label whose text is centered in the available space. You can change the text
displayed in a label by calling the label's setText() method:
message.setText("Goodby World!");
Since the JLabel class is a subclass of Component, you can use methods such as
setForeground() with labels. If you want the background color to have any effect, you
should call setOpaque(true) on the label, since otherwise the JLabel might not fill in
its background (depending on the look-and-feel). For example:
JLabel message = new JLabel("Hello World!");
message.setForeground(Color.red); // Display red text...
message.setBackground(Color.black); // on a black background...
message.setFont(new Font("Serif",Font.BOLD,18)); // in a bold font.
message.setOpaque(true); // Make sure background is filled in.

The JCheckBox Class


A JCheckBox is a component that has two states: selected or unselected. The user can
change the state of a check box by clicking on it. The state of a checkbox is
represented by a boolean value that is true if the box is selected and false if the box is
unselected. A checkbox has a label, which is specified when the box is constructed:
JCheckBox showTime = new JCheckBox("Show Current Time");
Usually, it's the user who sets the state of a JCheckBox, but you can also set the state
in your program. The current state of a checkbox is set using its setSelected(boolean)
method. For example, if you want the checkbox showTime to be checked, you would
say "showTime.setSelected(true);". To uncheck the box, say
"showTime.setSelected(false);". You can determine the current state of a checkbox by
calling its isSelected() method, which returns a boolean value.
In many cases, you don't need to worry about events from checkboxes. Your program
can just check the state whenever it needs to know it by calling the isSelected()
method. However, a checkbox does generate an event when its state changes, and you
can detect this event and respond to it if you want something to happen at the moment
the state changes. When the state of a checkbox is changed by the user, it generates an
event of type ActionEvent. If you want something to happen when the user changes
the state of a checkbox, you must register an ActionListener with the checkbox. (Note
that if you change the state by calling the setSelected() method, no ActionEvent is
generated. However, there is another method in the JCheckBox class, doClick(),
which simulates a user click on the checkbox and does generate an ActionEvent.)
When handling an ActionEvent, you can call evt.getSource() in the actionPerformed()
method to find out which object generated the event. (Of course, if you are only
listening for events from one component, you don't even have to do this.) The
returned value is of type Object, but you can type-cast it to another type if you want.
Once you know the object that generated the event, you can ask the object to tell you
its current state. For example, if you know that the event had to come from one of two
checkboxes, cb1 or cb2, then your actionPerformed() method might look like this:
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if (source == cb1) {
boolean newState = ((JCheckBox)cb1).isSelected();
... // respond to the change of state
}
else if (source == cb2) {
boolean newState = ((JCheckBox)cb2).isSelected();
... // respond to the change of state
}
}
Alternatively, you can use evt.getActionCommand() to retrieve the action command
associated with the source. For a JCheckBox, the action command is, by default, the
label of the checkbox.

The JRadioButton and ButtonGroup Classes


Closely related to checkboxes are radio buttons. Radio buttons occur in groups. At
most one radio button in a group can be selected at any given time. In Java, a radio
button is represented by an object of type JRadioButton. When used in isolation, a
JRadioButton acts just like a JCheckBox, and it has the same methods and events.
Ordinarily, however, a JRadioButton is used in a group. A group of radio buttons is
represented by an object belonging to the class ButtonGroup. A ButtonGroup is not a
component and does not itself have a visible representation on the screen. A
ButtonGroup works behind the scenes to organize a group of radio buttons, so that at
most one button in the group can be selected at any given time.
To use a group of radio buttons, you must create a JRadioButton object for each
button in the group, and you must create one object of type ButtonGroup to organize
the individual buttons into a group. Each JRadioButton must be added individually to
some container, so that it will appear on the screen. (A ButtonGroup plays no role in
the placement of the buttons on the screen.) Each JRadioButton must also be added to
the ButtonGroup, which has an add() method for this purpose. If you want one of the
buttons to be selected at start-up, you can call setSelected(true) for that button. If you
don't do this, then none of the buttons will be selected until the user clicks on one of
them.
As an example, here is how you could set up a set of radio buttons that can be used to
select a color:
JRadioButton redRadio, blueRadio, greenRadio, blackRadio;
// Variables to represent the radio buttons.
// These should probably be instance variables, so
// that they can be used throughout the program.

ButtonGroup colorGroup = new ButtonGroup();


redRadio = new JRadioButton("Red"); // Create a button.
colorGroup.add(redRadio); // Add it to the group.

blueRadio = new JRadioButton("Blue");


colorGroup.add(blueRadio);

greenRadio = new JRadioButton("Green");


colorGroup.add(greenRadio);

blackRadio = new JRadioButton("Black");


colorGroup.add(blackRadio);

redRadio.setSelected(true); // Make an initial selection.


The individual buttons must still be added to a container if they are to appear on the
screen. If you want to respond immediately when the user clicks on one of the radio
buttons, you should register an ActionListener for each button. Here is an applet that
demonstrates this. When you click one of the radio buttons, the background color of
the label is changed:

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.

The JComboBox Class


The JComboBox class represents another way of letting the user select one option
from a list of options. But in this case, the options are presented as a kind of pop-up
menu, and only the currently selected option is visible on the screen. The painting
applet at the end of Section 6.6 used a JComboBox for selecting a color.
When a JComboBox object is first constructed, it initially contains no items. An item
is added to the bottom of the menu by calling its instance method, addItem(str), where
str is a string that will be displayed. (In fact, you can add any type of object to a
JComboBox. The toString() method of the object is called to determine what string to
display.)
For example, the following code will create an object of type JComboBox that
contains the options Red, Blue, Green, and Black:
JComboBox colorChoice = new JComboBox();
colorChoice.addItem("Red");
colorChoice.addItem("Blue");
colorChoice.addItem("Green");
colorChoice.addItem("Black");
You can call the getSelectedIndex() method of a JComboBox to find out which item is
currently selected. This method returns an integer that gives the position of the
selected item in the list, where the items are numbered starting from zero.
Alternatively, you can call getSelectedItem() to get the selected item itself. (This
method returns a value of type Object.) You can change the selection by calling the
method setSelectedIndex(n), where n is an integer giving the position of the item that
you want to select.
The most common way to use a JComboBox menu is to call its getSelectedIndex()
method when you have a need to know which item is currently selected. However,
like other components that we have seen, JComboBox components generate
ActionEvents. You can register an ActionListener with the JComboBox if you want to
respond to such events as they occur.
JComboBoxes have a nifty feature, which is probably not all that useful in practice.
You can make a JComboBox "editable" by calling its method setEditable(true). If you
do this, the user can edit the selection by clicking on the JComboBox and typing. This
allows the user to make a selection that is not in the pre-configured list that you
provide. (The "Combo" in the name "JComboBox" refers to the fact that it's a kind of
combination of menu and text-input box.) If the user has edited the selection in this
way, then the getSelectedIndex() method will return the value -1, and
getSelectedItem() will return the string that the user typed. An ActionEvent is
triggered if the user presses return in the JComboBox.

The JSlider Class


A JSlider provides a way for the user to select an integer value from a range of
possible values. The user does this by dragging a "knob" along a bar. A slider can,
optionally, be decorated with tick marks and with labels. This demonstration applet
shows three sliders with different decorations and with different ranges of values:

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);

JScrollBar and JScrollPane


A JScrollBar, like a JSlider, allows the user to select an integer value from a range of
values. A scroll bar, however, is generally used to control the scrolling of another
component such as the text in a text editor. A scroll bar can be either horizontal or
vertical. It has five parts:

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 JTextField and JTextArea Classes


JTextFields and JTextAreas are boxes where the user can type in and edit text. The
difference between them is that a JTextField contains a single line of editable text,
while a JTextArea can display multiple lines. It is also possible to set a JTextField or
JTextArea to be read-only so that the user can read the text that it contains but cannot
edit the text.
Both JTextField and JTextArea are subclasses of javax.swing.text.JTextComponent,
which defines their common behavior. The JTextComponent class supports the idea of
a selection. A selection is a subset of the characters in the JTextComponent, including
all the characters from some starting position to some ending position. The selection
is hilited on the screen. The user selects text by dragging the mouse over it. Some
useful methods in class JTextComponent include the following. They can, of course,
be used for both JTextFields and JTextAreas.
void setText(String newText); // substitute newText
// for current contents
String getText(); // return a copy of the current contents
String getSelectedText(); // return the selected text
void select(int start, int end); // change the selection;
// characters in the range start <= pos < end are
// selected; characters are numbered starting from zero
void selectAll(); // select the entire text
int getSelectionStart(); // get starting point of selection
int getSelectionEnd(); // get end point of selection
void setEditable(boolean canBeEdited);
// specify whether or not the text in the component
// can be edited by the user
The requestFocus() method, inherited from JComponent, is also useful for text
components. The constructor for a JTextField takes the form
JTextField(int columns);
where columns specifies the number of characters that should be visible in the text
field. This is used to determine the preferred width of the text field. (Because
characters can be of different sizes, the number of characters visible in the text field
might not be exactly equal to columns.) You don't have to specify the number of
columns; for example, you might use the text field in a context where it will expand to
the maximum size available. In that case, you can use the constructor JTextField(),
with no parameters. You can also use the following constructors, which specify the
initial contents of the text field:
JTextField(String contents);
JTextField(String contents, int columns);
JTextField has a subclass, JPasswordField, which is identical except that it does not
reveal the text that it contains. The characters in a JPasswordField are all displayed as
asterisks (or some other fixed character). A password field is, obviously, designed to
let the user enter a password without showing that password on the screen.
The constructors for a JTextArea are
JTextArea();
JTextArea(int lines, int columns);
JTextArea(String contents);
JTextArea(String contents, int lines, int columns);
The parameter lines specifies how many lines of text should be visible in the text area.
This determines the preferred height of the text area. (The text area can actually
contain any number of lines; the text area can be scrolled to reveal lines that are not
currently visible.) It is common to use a JTextArea as the Center component of a
BorderLayout. In that case, it isn't useful to specify the number of lines and columns,
since the TextArea will expand to fill all the space available in the center area of the
container.
The JTextArea class adds a few useful procedures to those inherited from
JTextComponent:
void append(String text);
// add the specified text at the end of the current
// contents; line breaks can be inserted by using the
// special character \n
void insert(String text, int pos);
// insert the text, starting at specified position
void replaceRange(String text, int start, int end);
// delete the text from position start to position end
// and then insert the specified text in its place
void setLineWrap(boolean wrap);
// If wrap is true, then a line that is too long to be
// displayed in the text area will be "wrapped" onto
// the next line. The default value is false.
A JTextField generates an ActionEvent when the user presses return while typing in
the JTextField. The JTextField class includes an addActionListener() method that can
be used to register a listener with a JTextField. In the actionPerformed() method, the
evt.getActionCommand() method will return a copy of the text from the JTextField. It
is also common to use a JTextField by checking its contents, when needed, with the
getText() method. JTextAreas do not generate action events.
A JTextArea does not have scroll bars, but scroll bars can be added easily by putting
the text area in a scroll pane:
JTextArea inputArea = new JTextArea();
JScrollPane scroller = new JScrollPane( inputArea );
The scroll bars will appear only when needed. Remember to add the scroll pane, not
the text area, to a container.
Other Components

Menus and Menu Bars


This section has introduced many, but not all, Swing components. We will look at
menus and menu bars in Section 5. Some Swing components will not be covered at
all. These include:
JList -- displays a list of items to the user, and allows the user to select one or several
items from the list.
JTable -- displays a two-dimensional table of items, and possibly allows the user to
edit them.
JTree -- displays hierarchical data in a tree-like structure.
JToolBar -- holds a row of tools, such as icons and buttons. The user can drag the tool
bar away from the window that contains it, and it becomes a separate, floating tool
window.
JSplitPane -- a container that displays two components. The user can drag the dividing
line between the components to adjust their relative sizes.
JTabbedPane -- a container that displays one of a set of panels. The user selects which
panel is visible by clicking on a "tab" at the top of the pane.

Programming with Components

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.

An Example with Text Input Boxes


As a first example, let's look at a simple calculator applet. This example demonstrates
typical uses of JTextFields, JButtons, and JLabels, and it uses several layout
managers. In the applet, you can enter two real numbers in the text-input boxes and
click on one of the buttons labeled "+", "-", "*", and "/". The corresponding operation
is performed on the numbers, and the result is displayed in a JLabel at the bottom of
the applet. If one of the input boxes contains an illegal entry -- a word instead of a
number, for example -- an error message is displayed in the JLabel.

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() {

/* Since I will be using the content pane several times,


declare a variable to represent it. Note that the
return type of getContentPane() is Container. */

Container content = getContentPane();

/* Assign a background color to the applet and its


content panel. This color will show through between
components and around the edges of the applet. */

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.) */

xInput = new JTextField("0");


xInput.setBackground(Color.white);
yInput = new JTextField("0");
yInput.setBackground(Color.white);

/* 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);

JPanel yPanel = new JPanel();


yPanel.setLayout(new BorderLayout());
yPanel.add( new Label(" y = "), BorderLayout.WEST );
yPanel.add(yInput, BorderLayout.CENTER);

/* Create a panel to hold the four buttons for the four


operations. A GridLayout is used so that the buttons
will all have the same size and will fill the panel.
The applet serves as ActionListener for the buttons. */

JPanel buttonPanel = new JPanel();


buttonPanel.setLayout(new GridLayout(1,4));

JButton plus = new JButton("+");


plus.addActionListener(this);
buttonPanel.add(plus);

JButton minus = new JButton("-");


minus.addActionListener(this);
buttonPanel.add(minus);

JButton times = new JButton("*");


times.addActionListener(this);
buttonPanel.add(times);

JButton divide = new JButton("/");


divide.addActionListener(this);
buttonPanel.add(divide);

/* Create the label for displaying the answer in red


on a white background. The label is set to be
"opaque" to make sure that the white background
is painted. */

answer = new JLabel("x + y = 0", JLabel.CENTER);


answer.setForeground(Color.red);
answer.setBackground(Color.white);
answer.setOpaque(true);

/* Set up the layout for the applet, using a GridLayout,


and add all the components that have been created. */

content.setLayout(new GridLayout(4,1,2,2));
content.add(xPanel);
content.add(yPanel);
content.add(buttonPanel);
content.add(answer);

/* Try to give the input focus to xInput, which is the natural


place for the user to start. */

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.

double x, y; // The numbers from the input boxes.


/* Get a number from the xInput JTextField. Use
xInput.getText() to get its contents as a String.
Convert this String to a double. The try...catch
statement will check for errors in the String. If
the string is not a legal number, the error message
"Illegal data for x." is put into the answer and
the actionPerformed() method ends. */

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;
}

/* Get a number from yInput in the same way. */

try {
String yStr = yInput.getText();
y = Double.parseDouble(yStr);
}
catch (NumberFormatException e) {
answer.setText("Illegal data for y.");
return;
}

/* Perform the operation based on the action command


from the button. Note that division by zero produces
an error message. */

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.)

An Example with Sliders


As a second example, let's look more briefly at another applet. In this example, the
user manipulates three JSliders to set the red, green, and blue levels of a color. The
value of each color level is displayed in a JLabel, and the color itself is displayed in a
large rectangle:

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.

Custom Component Examples


Java's standard component classes are often all you need to construct a user interface.
Sometimes, however, you need a component that Java doesn't provide. In that case,
you can write your own component class, building on one of the components that Java
does provide. We've already done this, actually, every time we've written a subclass of
the JPanel class to use as a drawing surface. A JPanel is a blank slate. By defining a
subclass, you can make it show any picture you like, and you can program it to
respond in any way to mouse and keyboard events. Sometimes, if you are lucky, you
don't need such freedom, and you can build on one of Java's more sophisticated
component classes.
For example, suppose I have a need for a "stopwatch" component. When the user
clicks on the stopwatch, I want it to start timing. When the user clicks again, I want it
to display the elapsed time since the first click. The textual display can be done with a
JLabel, but we want a JLabel that can respond to mouse clicks. We can get this
behavior by defining a StopWatch component as a subclass of the JLabel class. A
StopWatch object will listen for mouse clicks on itself. The first time the user clicks, it
will change its display to "Timing..." and remember the time when the click occurred.
When the user clicks again, it will check the time again, and it will compute and
display the elapsed time. (Of course, I don't necessarily have to define a subclass. I
could use a regular label in my applet, set the applet to listen for mouse events on the
label, and let the applet do the work of keeping track of the time and changing the text
displayed on the label. However, by writing a new class, I have something that is
reusable in other projects. I also have all the code involved in the stopwatch function
collected together neatly in one place. For more complicated components, both of
these considerations are very important.)
The StopWatch class is not very hard to write. I need an instance variable to record
the time when the user started the stopwatch. Times in Java are measured in
milliseconds and are stored in variables of type long (to allow for very large values).
In the mousePressed() method, I need to know whether the timer is being started or
stopped, so I need another instance variable to keep track of this aspect of the
component's state. There is one more item of interest: How do I know what time the
mouse was clicked? The method System.currentTimeMillis() returns the current time.
But there can be some delay between the time the user clicks the mouse and the time
when the mousePressed() routine is called. I don't want to know the current time. I
want to know the exact time when the mouse was pressed. When I wrote the
StopWatch class, this need sent me on a search in the Java documentation. I found that
if evt is an object of type MouseEvent(), then the function evt.getWhen() returns the
time when the event occurred. I call this function in the mousePressed() routine.
The complete StopWatch class is rather short:
import java.awt.event.*;
import javax.swing.*;

public class StopWatch extends JLabel implements MouseListener {


private long startTime; // Start time of timer.
// (Time is measured in milliseconds.)

private boolean running; // True when the timer is running.

public StopWatch() {
// Constructor.
super(" Click to start timer. ", JLabel.CENTER);
addMouseListener(this);
}

public void mousePressed(MouseEvent evt) {


// React when user presses the mouse by
// starting or stopping the timer.
if (running == false) {
// Record the time and start the timer.
running = true;
startTime = evt.getWhen(); // Time when mouse was clicked.
setText("Timing....");
}
else {
// Stop the timer. Compute the elapsed time since the
// timer was started and display it.
running = false;
long endTime = evt.getWhen();
double seconds = (endTime - startTime) / 1000.0;
setText("Time: " + seconds + " sec.");
}
}

public void mouseReleased(MouseEvent evt) { }


public void mouseClicked(MouseEvent evt) { }
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }

} // 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.*;

public class MirrorLabel extends JPanel {

// Constructor and methods meant for use public use.

public MirrorLabel(String text) {


// Construct a MirrorLable to display the specified text.
this.text = text;
}

public void setText(String text) {


// Change the displayed text. Call revalidate
// so that the layout of its container can be
// recomputed.
this.text = text;
revalidate(); // Tells container that size might have changed.
repaint();
}

public String getText() {


// Return the string that is displayed by this component.
return text;
}

// Implementation. Not meant for public use.

private String text; // The text displayed by this component.

private Image OSC;


// An off-screen image holding the non-reversed text.

private int widthOfOSC, heightOfOSC;


// Current size of the off-screen image, if one exists.

public void paintComponent(Graphics g) {


// The paint method makes a new OSC, if necessary. It writes
// a non-reversed copy of the string to the the OSC, then
// reverses the OSC as it copies it to the screen.
// (Note: color or font might have changed since the
// last time paintComponent() was called, so I can't just
// reuse the old image in the OSC.)
if (OSC == null || getSize().width != widthOfOSC
|| getSize().height != heightOfOSC) {
OSC = createImage(getSize().width, getSize().height);
widthOfOSC = getSize().width;
heightOfOSC = getSize().height;
}
Graphics OSG = OSC.getGraphics();
OSG.setColor(getBackground());
OSG.fillRect(0, 0, widthOfOSC, heightOfOSC);
OSG.setColor(getForeground());
OSG.setFont(getFont());
FontMetrics fm = OSG.getFontMetrics(getFont());
int x = (widthOfOSC - fm.stringWidth(text)) / 2;
int y = (heightOfOSC + fm.getAscent() - fm.getDescent()) / 2;
OSG.drawString(text, x, y);
OSG.dispose();
g.drawImage(OSC, widthOfOSC, 0, 0, heightOfOSC,
0, 0, widthOfOSC, heightOfOSC, null);
} // end paintComponent()

public Dimension getPreferredSize() {


// Compute a preferred size that will hold the string plus
// a border of 5 pixels.
FontMetrics fm = getFontMetrics(getFont());
return new Dimension(fm.stringWidth(text) + 10,
fm.getAscent() + fm.getDescent() + 10);
}

} // end class MirrorLabel

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.

A Null Layout Example


As a final example, we'll look at an applet that does not use a layout manager. If you
set the layout manager of a container to be null, then you assume complete
responsibility for positioning and sizing the components in that container. For an
applet, you can remove the layout manager with the command:
getContentPane().setLayout(null);
If comp is any component, then the statement
comp.setBounds(x, y, width, height);
puts the top left corner of the component at the point (x,y), measured in the
coordinated system of the container that contains the component, and it sets the width
and height of the component to the specified values. You should only set the bounds
of a component if the container that contains it has a null layout manager. In a
container that has a non-null layout manager, the layout manager is responsible for
setting the bounds, and you should not interfere with its job.
Assuming that you have set the layout manager to null, you can call the setBounds()
method any time you like. (You can even make a component that moves or changes
size while the user is watching.) If you are writing an applet that has a known, fixed
size, then you can set the bounds of each component in the applet's init() method.
That's what done in the following applet, which contains four components: two
buttons, a label, and a panel that displays a checkerboard pattern. This applet doesn't
do anything useful. The buttons just change the text in the label.

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().setLayout(null); // I will do the layout myself!

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 = new Checkerboard();


// (Checkerboard is defined later in this class.)
getContentPane().add(board);

newGameButton = new JButton("New Game");


newGameButton.addActionListener(this);
getContentPane().add(newGameButton);

resignButton = new JButton("Resign");


resignButton.addActionListener(this);
getContentPane().add(resignButton);

message = new JLabel("Click \"New Game\" to begin a game.",


JLabel.CENTER);
message.setForeground( new Color(100,255,100) );
message.setFont(new Font("Serif", Font.BOLD, 14));
getContentPane().add(message);

/* Set the position and size of each component by calling


its setBounds() method. */

board.setBounds(20,20,164,164);
newGameButton.setBounds(210, 60, 120, 30);
resignButton.setBounds(210, 120, 120, 30);
message.setBounds(0, 200, 330, 30);

/* Add a border to the content pane. Since the return


type of getContentPane() is Container, not JComponent,
getContentPane() must be type-cast to a JComponent
in order to call the setBorder() method. Although I
think the content pane is always, in fact, a JPanel,
to be safe I test that the return value really is
a JComponent. */

if (getContentPane() instanceof JComponent) {


((JComponent)getContentPane()).setBorder(
BorderFactory.createEtchedBorder());
}
} // end init();

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.

Menus and Menubars

ANY USER OF A GRAPHICAL USER INTERFACE is accustomed to selecting


commands from menus, which can be found in a menu bar at the top of a window (or
sometimes at the top of a screen). In Java, menu bars, menus, and the items in menus
are JComponents, just like all the other Swing components. Java makes it easy to add
a menu bar to a JApplet or, as we will see in Section 7, to a JFrame. Here is a sample
applet that uses menus:

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.

Menu Bars and Menus


A menu bar is just an object that belongs to the class JMenuBar. Since JMenuBar is a
subclass of JComponent, a menu bar could actually be used anywhere in any
container. In practice though, a JMenuBar is generally added to a top-level container
such as a JApplet. This can be done in the init() method of a JApplet using commands
of the form
JMenuBar menubar = new JMenuBar();
setMenuBar(menubar);
The applet's setMenuBar() method does not add the menu bar to the applet's content
pane. The menu bar appears in a separate area, above the content pane.
A menu bar is a container for menus. The type of menu that can appear in a menu bar
is an object belonging to the class JMenu. The constructor for a JMenu specifies a title
for the menu, which appears in the menu bar. A menu is added to a menu bar using the
menu bar's add() method. For example, the following commands will create a menu
with title "Options" and add it to the JMenuBar, menubar:
JMenu optionsMenu = new JMenu("Options");
menubar.add(optionsMenu);
A mnemonic can be added to a JMenu using the menu's addMnemonic() method,
which takes a parameter of type char. For example:
optionsMenu.setMnemonic('O');
A mnemonic provides a keyboard shortcut for the menu. If a mnemonic has been set
for a menu, then the menu can be opened by pressing the specified character key
while holding down the ALT key. If the mnemonic character appears in the title of the
menu, it will be underlined. The mnemonic does not have to be the first character in
the title. In fact, it doesn't have to appear in the title at all. Uppercase and lowercase
letters are equivalent for mnemonics.
Note, by the way, that you can add a menu to a menu bar either before or after you
have added menu items to the menu. You can add a menu to a menu bar even after it
has appeared on the screen, but I found that I had to call menubar.validate() after
adding the menu to get the menu to appear. You can remove a menu from a menubar
by calling menubar.remove(menu), but again, I found it necessary to call
menubar.validate() after doing this if the menubar is already on the screen.

Menu Items, Sub-menus, and Separators


Each of the items in a menu is an object belonging to the class JMenuItem. A
JMenuItem can be created with a constructor that specifies the text that appears in the
menu, and it can be added to the menu using the menu's add() method. For example:
JMenuItem clear = new JMenuItem("Clear");
optionsMenu.add(clear); // where optionsMenu is of type JMenu
You can specify a mnemonic for the menu item as the second parameter to the
constructor: new JMenuItem("Clear",'C'). The JMenu class also has an add() method
that takes a String as parameter. This version of add() creates a new menu item with
the given string as its text, and it adds that menu item to the menu. Furthermore, the
menu item that was created is returned as the value of the method. This means that the
two commands shown above can be abbreviated to the single command:
JMenuItem clear = optionsMenu.add("Clear");
A JMenuItem generates an ActionEvent when it is invoked by the user. If you want
the menu item to have some effect when it is invoked, you have to add an
ActionListener to the menu item. For example, if listener is the object of type
ActionListener that is to respond to the "Clear" command, you can say:
clear.addActionListener(listener);
Action events from JMenuItems can be processed in the same way as action events
from JButtons: When the actionPerformed() method of the listener is called, the
action command will be the text of the menu item, and the source of the event will be
the menu item object itself.
In many cases, the only things you want to do with a menu item are add it to a menu
and add an action listener to it. It's possible to do both of these with one command.
For example:
optionsMenu.add("Clear").addActionListener(listener);
This funny looking line does the following: optionsMenu.add("Clear") creates creates
a menu item and adds it to the menu, optionsMenu, and it returns the menu item as the
value of the method call. Then the addActionListener() method is applied to the return
value, that is, to the menu item that was just created.
The items in a menu are often separated into logical groups by horizontal lines drawn
across the menu. The "Options" menu in the sample applet contains two such lines.
You can add a separating line to the end of a JMenu by calling the menu's
addSeparator() method. For example:
optionsMenu.addSeparator();
The JMenu class is actually defined as a subclass of JMenuItem, which means that
you can add one menu to another. The menu that is added appears as a sub-menu in
the menu to which it is added. The title of the sub-menu appears as an item in the
main menu. When the user selects this item, the sub-menu appears. For example, in
the applet at the top of this page, the "Background Color" sub-menu of the "Options"
menu is created with the commands:
JMenu background = new JMenu("Background Color");
optionsMenu.add(background); // Add as sub-menu.
background.add("Red").addActionListener(canvas);
background.add("Green").addActionListener(canvas);
background.add("Blue").addActionListener(canvas);
background.add("Cyan").addActionListener(canvas);
background.add("Magenta").addActionListener(canvas);
background.add("Yellow").addActionListener(canvas);
background.add("Black").addActionListener(canvas);
background.add("Gray").addActionListener(canvas);
background.add("White").addActionListener(canvas);

Checkbox and Radio Button Menu Items


The JMenuItem class has two subclasses, JCheckBoxMenuItem and
JRadioButtonMenuItem, that can be used to create menu items that serve as check
boxes and radio buttons. Check boxes and radio buttons were covered in Section 3
and just about everything that was said there applies here as well.
A JCheckBoxMenuItem can be in one of two states, either selected or unselected. The
user changes the state by selecting the menu item. Just as with a JCheckBox, you can
determine the state of a JCheckBoxMenuItem by calling its isSelected() method. You
can set the state by calling the item's setSelected(boolean) method. You can register an
ActionListener with a JCheckBoxMenuItem, if you want to respond immediately
when the user changes the state. In many cases, however, you can just check the state
at the point in your program where you need to know it. For example, one of the
JCheckBoxMenuItems in the sample applet determines the size of the shapes that are
added to the drawing area. If the "Add Large Shapes" box is checked when a shape is
added, then the shape will be large; if not, the shape will be small. There is no action
listener in this case because nothing happens when the user selects the item (except
that it changes state). When the user adds a new shape, the program calls
addLargeShapes.isSelected() to determine which size to use. (addLargeShapes is the
instance variable that refers to the JCheckBoxMenuItem.)
JRadioButtonMenuItems are almost always used in groups, where at most one of the
radio buttons in the group can be selected at any given time. As with JRadioButtons,
all the JRadioButtonMenuItems in a group are added to a ButtonGroup, which
ensures that at most one of the items is selected. In the sample applet, for example,
there are nine JRadioButtonMenuItems in the "Color" menu. These are represented by
instance variables named red, green, blue, and so on. The code that creates the menu
items and adds them both to the menu and to a button group look like this:
ButtonGroup colorGroup = new ButtonGroup();

red = new JRadioButtonMenuItem("Red");


shapeColorMenu.add(red); // Add to menu.
colorGroup.add(red); // Add to button group.

green = new JRadioButtonMenuItem("Green");


shapeColorMenu.add(green);
colorGroup.add(green);

blue = new JRadioButtonMenuItem("Blue");


shapeColorMenu.add(blue);
colorGroup.add(blue);
.
.
.
Initially, the "Red" item is selected. This is accomplished with the command
red.setSelected(true). There are no ActionListeners for the JRadioButtonMenuItems.
When a new shape is added to the drawing area, the program checks the items in the
"Color" menu to see what color is selected, and that color is used as the color of the
new shape. This is done in an addShape() method using code that look like:
if (red.isSelected())
shape.setColor(Color.red);
else if (green.isSelected())
shape.setColor(Color.green);
else if (blue.isSelected())
shape.setColor(Color.blue);
.
.
.
Note that red, green, and the other variables that represent the menu items in the
"Color" menu must be defined as instance variables since they are initialized in the
init() method of the applet and are also used in another method. The variable that
represents the ButtonGroup, on the other hand, is just a local variable in the init()
method, since it is not used in any other 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.

menuitem.setAccelerator( KeyStroke.getKeyStroke("alt F4") );


// Pressing the F4 key while holding down the ALT key
// is equivalent to selecting the menu item. On a
// Macintosh, ALT refers to the Command key. Under
// Windows and Linux, this accelerator will probably
// be non-functional, since the operating system will
// intercept ALT-F4 and interpret it as a request to
// close the window.

Enabling and Disabling Menu Items


Since a JMenuItem is a JComponent, you can call menuitem.setEnabled(false) to
disable a menu item and menuitem.setEnabled(true) to enable a menu item. A menu
item that is disabled will appear "grayed out," and the user will not be able to select it,
either with the mouse or with an accelerator. It's always a good idea to give the user
visual feedback about the state of a program. Disabling a menu item when it doesn't
make any sense to select it is one good way of doing this.

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 );
}
}

public void mouseReleased(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 );
}
}
In a program that uses dragging in addition to popup menus, the mouse event
handling routines can become quite complicated. This is true for the sample applet at
the top of this page. You can check the source code to see how it's done.
Timers, Animation, and Threads

JAVA IS A MULTI-THREADED LANGUAGE, which means that several different


things can be going on, in parallel. A thread is the basic unit of program execution. A
thread executes a sequence of instructions, one after the other. When the system
executes a stand-alone program, it creates a thread. (Threads are usually called
processes in this context, but the differences are not important here.) The commands
of the program are executed sequentially, from beginning to end, by this thread. The
thread "dies" when the program ends. In a typical computer system, many threads can
exist at the same time. At a given time, only one thread can actually be running, since
the computer's Central Processing Unit (CPU) can only do one thing at a time. (An
exception to this is a multi-processing computer, which has several CPUs. At a given
time, every CPU can be executing a different thread.) However, the computer uses
time sharing to give the illusion that several threads are being executed at the same
time, "in parallel." Time sharing means that the CPU executes one thread for a while,
then switches to another thread, then to another..., and then back to the first thread --
typically about 100 times per second. As far as users are concerned, the threads might
as well be running at the same time.
To say that Java is a multi-threaded language means that a Java program can create
one or more threads which will then run in parallel with the program. This is a
fundamental, built-in part of the language, not an option or add-on like it is in some
languages. Still, programming with threads can be tricky, and should be avoided
unless it is really necessary. Ideally, even then, you can avoid using threads directly by
using well-tested classes and libraries that someone has written for you.
Animation In Swing
One of the places where threads are used in GUI programming is to do animation. An
animation is just a sequence of still images displayed on the screen one after the other.
If the images are displayed quickly enough and if the changes from one image to the
next are small enough, then the viewer will perceive continuous motion. To program
an animation, you need some way of displaying a sequence of images.
A GUI program already has at least one thread, an event-handling thread, which
detects actions taken by the user and calls appropriate subroutines in the program to
handle each event. An animation, however, is not driven by user actions. It is
something that happens by itself, as an independent process. In Java, the most natural
way to accomplish this is to create a separate thread to run the animation. Before the
introduction of the Swing GUI, a Java programmer would have to deal with this
thread directly. This made animation much more complicated than it should have
been. The good news in Swing is that it is no longer necessary to program directly
with threads in order to do simple animations. The neat idea in Swing is to integrate
animation with event-handling, so that you can program animations using the same
techniques that are used for the rest of the program.
In Swing, an animation can be programmed using an object belonging to the class
javax.swing.Timer. A Timer object can generate a sequence of events on its own,
without any action on the part of the user. To program an animation, all your program
has to do is create a Timer and respond to each event from the timer by displaying
another frame in the animation. Behind the scenes, the Timer runs a separate thread
which is responsible for generating the events, but you never need to deal with the
thread directly.
The events generated by a Timer are of type ActionEvent. The constructor for a Timer
specifies two things: The amount of time between events and an ActionListener that
will be notified of each event:
Timer(int delayTime, ActionListener listener)
The listener should be programmed to respond to events from the Timer in its
actionPerformed() method. The delay time between events is specified in milliseconds
(where one second equals 1000 milliseconds). The actual delay time between two
events can be longer than the requested delay time, depending on how long it takes to
process the events and how busy the computer is with other things. In a typical
animation, somewhere between ten and thirty frames should be displayed every
second. These rates correspond to delay times between 100 and 33.
A Timer does not start running automatically when it is created. To make it run, you
must call its start() method. A timer also has a stop() method, which you can call to
make it stop generating events. If you have stopped a timer and want to start it up
again, you can call its restart() method. (The start() method should be called only
once.) None of these methods have parameters.
Let's look at an example. In the following applet, you can start an animation running
by clicking the "Start" button. When you do this, the text on the button changes to
"Stop", and you can stop the animation by clicking the button again. This is yet
another applet that says "Hello World." The animation simply cycles the color of the
message through all possible hues:

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 {

Display display; // A JPanel belonging to a nested "Display"


// class; used for displaying "Hello World."
// It defines a method "setColor(Color)" for
// setting the color of the displayed message.

JButton startStopButton; // The button that will be used to


// start and stop the animation.

Timer timer; // The timer that drives the animation. A timer


// is started when the user starts the animation.
// Each time an ActionEvent is received from the
// timer, the color of the message will change.
// The value of this variable is null when the
// animation is not in progress.

int colorIndex; // This is be a number between 0 and 100 that


// will be used to determine the color. It will
// increase by 1 each time a timer event is
// processed.

public void init() {


// This is called by the system to initialize the applet.
// It adds a button to the "south" position in the applet's
// content pane, and it adds a display panel to the "center"
// position so that it will fill the rest of the content pane.

display = new Display();


// The component that displays "Hello World".

getContentPane().add(display, BorderLayout.CENTER);
// Adds the display panel to the CENTER position of the
// JApplet's content pane.

JPanel buttonBar = new JPanel();


// This panel will hold the button and appears
// at the bottom of the applet.
buttonBar.setBackground(Color.gray);
getContentPane().add(buttonBar, BorderLayout.SOUTH);

startStopButton = new JButton("Start");


buttonBar.add(startStopButton);

startStopButton.addActionListener( new ActionListener() {


// The action listener that responds to the
// button starts or stops the animation. It
// checks the value of timer to find out which
// to do. Timer is non-null when the animation
// is running, so if timer is null, the
// animation needs to be started.
public void actionPerformed(ActionEvent evt) {
if (timer == null)
startAnimation();
else
stopAnimation();
}
});

} // end init()

ActionListener timerListener = new ActionListener() {


// Define an action listener to respond to events
// from the timer. When an event is received, the
// color of the display is changed.
public void actionPerformed(ActionEvent evt) {
colorIndex++; // A number between 0 and 100.
if (colorIndex > 100)
colorIndex = 0;
float hue = colorIndex / 100.0F; // Between 0.0F and 1.0F.
display.setColor( Color.getHSBColor(hue,1,1) );
}
};

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");
}
}

public void stop() {


// The stop() method of an applet is called by the system
// when the applet is about to be stopped, either temporarily
// or permanently. We don't want a timer running while
// the applet is stopped, so stop the animation. (It's
// harmless to call stopAnimation() if the animation is not
// running.)
stopAnimation();
}
.
.
.
This applet responds to ActionEvents from two sources: the button and the timer that
drives the animation. I decided to use a different ActionListener object for each
source. Each listener object is defined by an anonymous nested class. (It would, of
course, be possible to use a single object, such as the applet itself, as a listener, and to
determine the source of an event by calling evt.getSource(). However, Java
programmers tend to be fond of anonymous classes.)
The applet defines methods startAnimation() and stopAnimation(), which are called
when the user clicks the button. Each time the user clicks "Start", a new timer is
created and started:
timer = new Timer(50,timerListener);
timer.start();
Remember that without timer.start(), the timer won't do anything at all. The
constructor specifies a delay time of 50 milliseconds, so there should be about 20
action events from the timer every second. The second parameter is an ActionListener
object. The timer events will be processed by calling the actionPerformed() method of
this object. The stopAnimation() method calls timer.stop(), which ends the flow of
events from the timer. The startAnimation() and stopAnimation() methods also
change the text on the button, so that it reads "Stop" when the animation is running
and "Start" when it is not running.
The actionPerformed() method in timerListener responds to a timer event by setting
the color of the display. The color is computed from a number, colorIndex that is
changed for each frame. (The color is specified as an "HSB" color. See Section 6.3 for
information on the HSB color system.)

JApplet's start() and stop() Methods


There is one other method in the HelloWorldSpectrum class that needs some
explanation: the stop() method. Every applet has several methods that are meant to be
called by the system at various times in the applet's life cycle. We have already seen
that init() is called when the applet is first created, before it appears on the screen.
Another method, destroy() is called just before the applet is destroyed, to give it a
chance to clean things up. Two other applet methods, start() and stop(), are called by
the system between init() and destroy() The start() method is always called by the
system just after init(), and stop() is always called just before destroy(). However,
start() and stop() can also be called at other times. The reason is that an applet is not
necessarily active for the whole time that it exists.
Suppose that you are viewing a Web page that contains an applet, and suppose you
follow a link to another page. The applet still exists. It will be there if you hit your
browser's Back button to return to the page that contains the applet. However, the
page containing the applet is not visible, so the user can't see the applet or interact
with it. The applet will not receive any events from the user, and since it is not visible,
it will not be asked to paint itself. The system calls the applet's stop() method when
user leaves the page that contains the applet. The system will call the applet's start()
method if the user returns to that page. This lets the applet keep track of when it is
active and when it is inactive. It might want to do this so that it can avoid using
system resources when it is inactive.
In particular, an applet should probably not leave a timer running when it is inactive.
The HelloWorldSpectrum applet defines the stop() method to call stopAnimation(),
which, in turn, will stop the timer if it is running. When the applet is about to become
inactive, the system will call stop(), and the animation -- if it was running -- will be
stopped. You can try it, if you are reading this page in a Web browser: Start the
animation running in the above applet, go to a different page, and then come back to
this page. You should see that the animation has been stopped.
The animation in the HelloWorldSpectrum applet is started and stopped under the
control of the user. In many cases, we want an animation to run for the entire time that
an applet is active. In that case, the animation can be started in the applet's start()
method and stopped in the applet's stop() method. It would also be possible to start the
animation in the init() method and stop it in the destroy() method, but that would
leave the animation running, uselessly, while the applet is inactive. In the following
example, a message is scrolled across the page. It uses a timer which churns out
events for the whole time the applet is active:

You can find the source code in the file ScrollingHelloWorld.java, but the relevant
part here is the start() and stop() methods:

public void start() {


// Called when the applet is being started or restarted.
// Create a new timer, or restart the existing timer.
if (timer == null) {
// This method is being called for the first time,
// since the timer does not yet exist.
timer = new Timer(300, this); // (Applet listens for events.)
timer.start();
}
else {
timer.restart();
}
}

public void stop() {


// Called when the applet is about to be stopped.
// Stop the timer.
timer.stop();
}
These methods can be called several times during the lifetime of an applet. The first
time start() is called, it creates and starts a timer. If start() is called again, the timer
already exists, and the existing timer is simply restarted.

Other Useful Timer Methods


Although timers are most often used to generate a sequence of events, a timer can also
be configured to generate a single event, after a specified amount of time. In this case,
the timer is being used as an alarm which will signal the program after a specified
amount of time has passed. To use a Timer object in this way, call setRepeats(false)
after constructing it. For example:
Timer alarm = new Timer(5000, listener);
alarm.setRepeats(false);
alarm.start();
The timer will send one action event to the listener five seconds (5000 milliseconds)
after it is started. You can cancel the alarm before it goes off by calling its stop()
method.
Here's one final way to control the timing of events: When you start a repeating timer,
the time until the first event is the same as the time between events. Sometimes, it
would be convenient to have a longer or shorter delay before the first event. If you
start a timer in the init() method of an applet, for example, you might want to give the
applet some time to appear on the screen before receiving any events from the timer.
You can set a separate delay for the first event by calling timer.setInitialDelay(delay),
where timer is the Timer and delay is specified in milliseconds as usual.

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:

The algorithm for computing the colors in this applet is:


For square sizes 64, 32, 16, 8, 4, 2, and 1:
For each square in the applet:
Let (a,b) be the pixel coords of the center of the square.
Let (x,y) be the real numbers corresponding to (a,b).
Let (zx,zy) = (x,y).
Let count = 0.
Repeat until count is 80 or (zx,zy) is "big":
Let new_zx = zx*zx - zy*zy + x.
Let zy = 2*zx*zy + y.
Let zx = new_zx.
Let count = count + 1.
Let color = Color.getHSBColor( count/100.0F, 0.0F, 0.0F )
Fill the square with that color.
The point is that this is a long computation. When you click the "Start" button of the
applet, the applet creates a separate thread to do this computation.
In Java, a thread is an object belonging to the class java.lang.Thread. The purpose of a
thread is to execute a single subroutine from beginning to end. In the Mandelbrot
applet, that subroutine implements the above algorithm. The subroutine for a thread is
usually an instance method
public void run()
that is defined in an object that implements the interface named Runnable. The
Runnable interface defines run() as its only method. The Runnable object is provided
as a parameter to the constructor of the thread object. (It is also possible to define a
thread by declaring a subclass of class Thread, and defining a run() method in the
subclass, but it is more common to use a Runnable object to provide the run() method
for a thread.) If runnableObject is an object that implements the Runnable interface,
then a thread can be constructed with the command:
Thread runner = new Thread(runnableObject);
The job of this thread is to execute the run() method in runnableObject. Just as with a
Timer, it is not enough to construct a thread. You must also start it running by calling
its start method: runner.start(). When this method is called, the thread will begin
executing the run() method in the runnableObject, and it will do this in parallel with
the rest of the program. When the subroutine ends, the thread will die, and it cannot be
restarted or reused. There is no stop method for stopping a thread. (Actually, there is
one, but it is deprecated, meaning that you are not supposed to call it.) If you want to
be able to stop the thread, you need to provide some way of telling the thread to stop
itself. I often do this with an instance variable named running that is visible both in
the run() method and elsewhere in the program. When the program wants the thread to
stop, it just sets the value of running to false. In the run() method, the thread checks
the value of running regularly. If it sees that the value of running has become false,
then the run() method should end. Here, for example, are the methods that the
Mandelbrot applet uses to start and to stop the thread:
void startRunning() {
// A simple method that starts the computational thread,
// unless it is already running. (This should be
// impossible since this method is only called when
// the user clicks the "Start" button, and that button
// is disabled when the thread is running.)
if (running)
return;
runner = new Thread(this);
// Creates a thread that will execute the run()
// method in this class, which implements Runnable.
running = true;
runner.start();
}

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.

startButton.setEnabled(false); // Disable "Start" button


stopButton.setEnabled(true); // and enable "Stop" button
// while thread is running.

int width = getWidth(); // Current size of this canvas.


int height = getHeight();

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);

for (size = 64; size >= 1 && running; size = size/2) {


// Outer for loop performs one pass, filling
// the image with squares of the given size.
// The size here is given in terms of pixels.
// Note that all loops end immediately if running
// becomes false.
double dx,dy; // Size of square in real coordinates.
dx = (xmax - xmin)/width * size;
dy = (ymax - ymin)/height * size;
double x = xmin + dx/2; // x-coord of center of square.
for (i = size/2; i < width+size/2 && running; i += size) {
// First nested for loop draws one column of squares.
double y = ymax - dy/2; // y-coord of center of square
for (j = size/2; j < height+size/2 && running; j += size) {
// Innermost for loop draws one square, by
// counting iterations to determine what
// color it should be, and then invoking the
// "painter" object to actually draw the square.
colorIndex = countIterations(x,y);
try {
SwingUtilities.invokeAndWait(painter);
}
catch (Exception e) {
}
y -= dy;
}
x += dx;
Thread.yield(); // Give other threads a chance to run.
}
}

running = false; // The thread is about to end, either


// because the computation is finished
// or because running has been set to
// false elsewhere. In the former case,
// we have to set running = false here
// to indicate that the thread is no
// longer running.

startButton.setEnabled(true); // Reset states of buttons.


stopButton.setEnabled(false);

} // end run()

Frames and Dialogs

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.

You might also like