Java Programming Language Handbook 3
Java Programming Language Handbook 3
HANDBOOK
Anthony Potts
David H. Friedel, Jr.
10
Chapter
Java Applet
Programming
Techniques
10
Java Applet
Programming
Techniques
Once you master the basics of using the Java
language, youll want to learn as much as
you can about writing powerful applets.
The Java language offers a unique optionto be able to create programs that
run as a stand-alone applications or as applets that are dependent on a controlling program such as a Web browser. The big difference between applications
and applets is that applications contain enough code to work on their own and
applets need a controlling program to tell the applet when to do what.
By itself, an applet has no means of starting execution because it does not have a
main() method. In an application, the main() method is the place where execution starts. Any classes that are not accessed directly or indirectly through the
main() method of an application are ignored.
If you have programmed in a visual environment before, the concept of an applet
should be easy to understand. You can think of an applet as you would a type of
custom control. When a custom control is used, you dont have to create code to
make it go; that is handled for you. All you have to do is respond to events. With
applets, you do not have to create the code that makes it go; you only need to
write code to respond to events that the parent program callsusually the browser.
Applet Basics
Lets look closely at some of the key areas you need to be aware of when creating
applets. To start, you need to subclass the Applet class. By doing this, you inherit quite a bit of applet functionality that is built-in to the Applet class.
287
288 Chapter 10
This listing shows the hierarchy of the Applet class and Table 10.1 provides a
detailed look at the components of the Applet class that are inherited when you
implement it.
Table 10.1
Method
Description
destroy()
Cleans up whatever resources are being held. If the applet is active, it is first
stopped.
getAppletContext()
Returns a handle to the applet context. The applet context is the parent object
either a browser or applet viewer. By knowing this handle, you can control the
environment and perform operations like telling a browser to download a file or
jump to another Web page.
getAppletInfo()
Returns a string containing information about the author, version, and copyright
of the applet.
getAudioClip(URL)
Returns the data of an audio clip that is located at the given URL. The sound is not
played until the play() method is called.
getAudioClip(URL, String)
Returns the data of an audio clip that is located at the given location relative to
the documents URL. The sound is not played until the play() method is called.
getCodeBase()
getDocumentBase ()
Gets the URL of the document that the applet is embedded in. If the applet stays
active as the browser goes from page to page, this method will still return the
URL of the original document the applet was called from.
getImage(URL)
Gets an image at the given URL. This method always returns an image object
immediately even if the image does not exist. The actual image details are loaded
when the image is first needed and not at the time it is loaded. If no image exists,
an exception is thrown.
getImage(URL, String)
Gets an image at a URL relative to the documents URL. This method always
returns an image object immediately even if the image does not exist. The actual
image details are loaded when the image is first needed and not at the time it is
loaded. If no image exists, an exception is thrown.
getParameter(String)
289
Method
Description
getParameterInfo()
Returns an array of strings describing the parameters that are understood by this
applet. The array consists of sets of three strings: name, type, and description.
Often, the description string will be empty.
init()
Initializes the applet. You never need to call this method directly; it is called
automatically by the system once the applet is created. The init() method is
empty so you need to override it if you need anything initialized at the time your
applet is loaded.
isActive()
Returns true if the applet is active. An applet is marked active just before the
start() method is called.
play(URL)
This method plays an audio clip that can be found at the given URL. Nothing
happens if the audio clip cannot be found.
play(URL, String)
This method plays an audio clip that resides at a location relative to the current
URL. Nothing happens if the audio clip is not found.
resize(int, int)
Requests that an applet be resized. The first integer is height and the second is
width. This method overrides the resize() method of the Component class that
is part of the Applet classs hierarchy.
showStatus(String)
Shows a status message in the Applets context. This method allows you to display
a message in the applet contexts status bar, usually a browser. This is very useful
for displaying URLs when an action the user is about to do will result in a jump to
a new Web page.
start()
Starts the applet. You never need to call this method directly; it is called when the
applets document is visited. Once again, this method is empty and you need to
override it to make it useful. This is usually where you would put the guts of your
code. However, be aware that this method is called every time the page that
embeds the applet is called. So make sure that the applet is being destroyed if
necessary.
stop()
This method is called when the browser leaves the page the applet is embedded
in. It is up to you to take this opportunity to use the destroy() method to
terminate your applet. There may be times, however, when you do not want to
destroy it here and instead wait until a Quit button is pressed, or until the
browser itself closes (then everything is dumped rather ungraciously). stop() is
guaranteed to be called before the destroy() method is called. You never need
to call this method directly because the browser will call it for you.
If you return to Chapter 2 and walk through the ticker tape applet we presented,
you should get a good overview of the order in which key methods are called
and why. As the listing illustrates, the Applet class is a descendant of the
290 Chapter 10
Container class; thus, it can hold other objects. You do not need to create a panel
first to place objects on because the Applet class extends the Panel class. Finally,
because the Container class is derived from the Component class, we have the
ability to respond to events, grab and display images, and display text among
many other things. Table 10.2 presents some of the key methods you have access
to because of all the classes that have been extended to get to the Applet class.
Table 10.2
Gets the background color. If the component does not have a background color,
the background color of its parent is returned.
getFont()
Gets the font of the component. If the component does not have a font, the font
of its parent is returned.
getFontMetrics(Font)
Gets the font metrics for this component. It will return null if the component is
currently not on the screen. Font metrics tell you things like the height and width
of a string using the given font on the current component.
getForeground()
Gets the foreground color. If the component does not have a foreground color, the
foreground color of its parent is returned.
getGraphics()
Gets a Graphics context for this component. This method will return null if the
component is currently not visible on the screen.
handleEvent(Event)
Handles all events. Returns true if the event is handled and should not be passed
to the parent of this component. The default event handler calls some helper
methods to make life easier on the programmer.
hide()
inside(int, int)
locate(int, int)
location()
Returns the current location of this component. The location will be in the parents
coordinate space. The return value is a point object which is simply an x and y
integer value.
move(int, int)
Moves the component to a new location. The integers are the x and y coordinates
and are in the parents coordinate space.
repaint()
Repaints the component. This will result in a call to update as soon as possible.
The screen will also be cleared resulting in a brief flicker.
repaint(long)
Repaints the component. However, the extra argument is a long value that
instructs Java that it must perform the update within that value in milliseconds.
continued
291
Method
Description
Reshapes the component to the specified bounding box. The first two integers
represent the new x an y coordinates the component should be moved to, and the
second set of integers represent the new width and height.
resize(int, int)
setBackground(Color)
setFont(Font)
setForeground(Color)
show()
size()
Returns the current size of the component. The return value is a dimension object
that has two integer values representing the width and height.
update(graphics)
countComponents()
getComponents()
Gets all the components in this container. The return value is actually an array of
Component objects.
getLayout()
remove(Component)
removeAll()
Removes all the components from the container. It is dangerous to use if you are
not careful.
setLayout(LayoutManager)
Applet Drawbacks
Applets can really eat up system resources. If you do not use threads and you
create loops in an applet, you may run into serious performance problems with
your browser. The browser can get so busy working with the applet that it does
not have time to respond to Web page events such as refreshes, scrolls, and
mouse clicks.
When some developers first heard about applets and their ability to run on
many types of machines, there first response was, Thats dangerous! Many
were concerned that applets would be used for mischievous causes. To prevent
292 Chapter 10
applets from causing problems on machines, there are several built-in security
measures you can take advantage of.
NATIVE METHODS
The other option or loop-hole (depending on how you look at it) is the use of
native methods. You can create methods in C++ that can be called directly from
Java. This is a very powerful option, especially if you are creating platformspecific programs that need the extra speed that you can get from natively compiled code. However, it can also be a potential gateway for mischievous programs.
This feature may or may not be disabled, depending on the browser, so be cautious of how you use it.
FILE EXECUTION
Java applets are not allowed to execute programs on a users system. So, you cant
just run the Format program and wipe a hard drive.
NETWORK COMMUNICATION
Applets are only allowed to communicate with the server from which they were
downloaded. This is another one of the security features that may or not be in
effect depending on the browser. So, once again, do not program for it. This is
actually one security option we would like to see go away or at least be able to
have the user override it. The ability to talk with multiple servers could be incredibly powerful if implemented well. Just think of a large company with servers all over the world. You could create a little applet that could converse with
them all and gather information for the end users.
A DISCLAIMER
Just because Java provides a few security features does not mean that it is completely secure. Java is a language that is still very much in its infancy and someone, somewhere will find a way to hack the system. However, since Java was
293
Lets Play
Now that you have seen all the methods that you can use and learned a little
about applet security, lets create an applet that uses some of these features. We
wont explain every line of code as we did for the ticker tape applet in Chapter 2,
but we will show you a few cool things you can do in your applets.
The applet well create is a simple navigation applet that will offer the user several buttons with URLs as labels. When the user clicks on a button, the browser
will be instructed to go to a particular site. We have also included some sound
support just for the fun of it. Lets see the code first:
import java.applet.*;
import java.awt.*;
import java.net.*;
// testNav Class
public class testNav extends Applet {
AudioClip startClip;
AudioClip linkClip;
AudioClip stopClip;
public testNav() {
setLayout(new GridLayout(4, 1));
add(new Button("http://www.coriolis.com"));
add(new Button("http://www.javasoft.com"));
add(new Button("http://www.gamelan.com"));
add(new Button("http://www.microsoft.com"));
}
public boolean action(Event evt, Object arg) {
if (evt.target instanceof Button) {
linkClip.play();
fetchLink((String)arg);
return true;
}
return super.handleEvent(evt);
}
294 Chapter 10
void fetchLink(String s) {
URL tempURL = null;
try { tempURL = new URL(s); }
catch(MalformedURLException e) {
showStatus("Malformed URL Exception has been thrown!");
}
getAppletContext().showDocument(tempURL);
}
public void init(){
startClip = getAudioClip(getCodeBase(), "start.au");
linkClip = getAudioClip(getCodeBase(), "link.au");
stopClip = getAudioClip(getCodeBase(), "stop.au");
}
public void start(){
testNav TN = new testNav();
startClip.play();
}
public void stop(){
stopClip.play();
}
} // End testNav
Figure 10.1 shows the testNav applet running in the Netscape browser.
This method handles mouse and keyboard actions for us. The first thing it does
is check to see if the target of the action is a Button or not. If it is, we play a
sound file and call the fetchLink() method that we created to actually go to
other sites. We will cover the sound stuff in a minute. Right now, lets look at the
fetchLink() method and see how we instruct the browser to grab other pages:
Figure 10.1
Running the testNav applet.
296 Chapter 10
void fetchLink(String s) {
URL tempURL = null;
try { tempURL = new URL(s); }
catch(MalformedURLException e) {
showStatus("Malformed URL Exception has been thrown!");
}
getAppletContext().showDocument(tempURL);
}
297
Playing Sounds
For loading and playing sounds from within an applet we have two options.
First, we can use the play() method of the applet that loads and plays the given
sound right away. Second, we can load an applet into an AudioClip object using
the getAudioClip() method and play the sound whenever we want. Its up to
you to decide if the sounds should be loaded before they are played, or loaded
and played at the same time.
To use the play() method, you invoke the method, sending the URL of the
sound file you want as an argument. Or, you can split the URL into two pieces.
The first piece would be a URL representing the code base, and the second
argument would be the file name and directory relative to the code base. Here
are the declarations for these methods:
play(URL); // This is the full URL of the sound file you want to play
play(URL, String); // This is the call that uses a base URL and a string
// representing the file name.
The other option we have for playing sounds is to load them into an object first.
To do this we will create an AudioClip object and use the getAudioClip() method
to load the sound file into the audio object. Once the sound file is loaded, we
call the play() method of the AudioClip object to hear the sound. Here are the
declarations and calls to handle sounds in this manner:
getAudioClip(URL); // This requires a fully-qualified URL that points to a
// sound file
getAudioClip(URL, String); // This is the call that uses a base URL and a
// string representing the file name.
298 Chapter 10
You can also stop or loop the sound clip with these methods:
myClip.stop();
myClip.loop();
If a sound file being requested cannot be found, the AudioClip object will be set
to null. No exception will be raised, but if you then try to play, stop, or loop the
file, an exception will be thrown.
Displaying Images
One other key area we need to cover is the quick and painless use of images
within applets. Images are just as easy to download as sounds. Here is a little
sample applet that downloads an image and blasts it onto the screen:
import java.awt.*;
import java.applet.*;
public class testImg extends Applet {
Image testImage;
public void paint(Graphics g) {
g.drawImage(testImage, 0, 0, this);
}
public void init() {
testImage = getImage(getDocumentBase(), "sample.gif");
}
}
299
These image methods will support whatever format the browser supports.
Chapter
11
Event Handling
Event
Handling
11
Every time you perform an action while running a Java application, such as
Introducing Events
In the ticker tape applet we created in Chapter 2, the program scrolled a line of
text across the applet space. If you click the mouse button on top of the applet
while it is running, the scrolling text will stop and then start when the mouse is
clicked again. These mouse clicks cause events to occur. In our applet, the event
303
304 Chapter 11
was caused by pressing down the mouse button. Here is the portion of code
responsible for halting the scrolling text:
// Handle mouse clicks
public boolean handleEvent(Event evt) {
if (evt.id == Event.MOUSE_DOWN) {
if (suspended) {
ttapeThread.resume();
} else {
ttapeThread.suspend();
}
suspended = !suspended;
}
return true;
}
The key to the inner workings of this error handler method (handleEvent()) is
the argument evt. It is declared as an object of the Event class, a special class that
Java provides for processing events. In our code, we simply check the id instance
variable to make sure a MOUSE_DOWN event has occurred. If so, we either
resume or suspend the applet.
Event Types
Events in Java can be split into three main groups: mouse, keyboard, and system
events. All of these events can be handled very similarly. Java events are actually
objects derived from their own classes, as we saw in the applet example we just
discussed. This method of handling events makes perfect sense when you realize
the power you gain from being able to manipulate an event as an object. In other
programming languages, events only trigger certain methods, which limits you to
receiving very little information about the current state of the system. You also
cannot pass the event on to another handler, which you can do with Java.
Table 11.1 presents the variables defined in the Event class and Table 11.2 presents the methods. Later in this chapter youll learn more about how to apply
them. The variables that are listed in all capital letters represent static values that
Table 11.1
Variable
Description
SHIFT_MASK
The shift modifier constant. This is an integer that indicates if the Shift key was down
when the event occurred. This variable is used to process keyboard events.
CTRL_MASK
The control modifier constant. This is an integer that indicates if the Ctrl key was down
when the event occurred. This variable is used to process keyboard events.
ALT_MASK
The alt modifier constant. This is an integer that indicates if the Alt key was down
when the event occurred. This variable is used to process keyboard events.
HOME
END
PGUP
PGDN
UP
DOWN
LEFT
RIGHT
F1 ... F12
ESC
WINDOW_DESTROY
Represents the event that occurs when a user tries to close a frame or window.
WINDOW_EXPOSE
Represents the event that occurs when part of your application has been covered by
another application and the second app is removed.
WINDOW_ICONIFY
WINDOW_DEICONIFY
Represents the event that occurs when a window is restored from a minimized state.
WINDOW_MOVED
KEY_PRESS
Represents the event that occurs when any key on the keyboard is pressed down.
KEY_RELEASE
Represents the event that occurs when any key on the keyboard is released.
MOUSE_DOWN
Represents the event that occurs when a mouse button is pressed down.
MOUSE_UP
MOUSE_MOVE
Represents the event that occurs when a mouse button is moved across a part of the
application or applet.
continued
306 Chapter 11
Table 11.1
Variable
Description
MOUSE_ENTER
MOUSE_EXIT
MOUSE_DRAG
Represents the event that occurs when the mouse button is down and the mouse is
moved.
LIST_SELECT
Represents the event that occurs when an option is selected from within a list object.
LIST_DESELECT
Represents the event that occurs when an option is de-selected from within a list
object.
GOT_FOCUS
Represents the event that occurs when a component gains the focus.
LOST_FOCUS
Represents the event that occurs when a component loses the focus.
Target
When
Id
Key
Arg
An arbitrary argument.
Description
translate(int, int)
Translates an event relative to the given component. This involves translating the
coordinates so they make sense within the given component.
shiftDown()
controlDown()
ToString()
metaDown()
Checks to see if the meta key is pressed. Returns true if it is pressed. The meta
key is different for each operating system. On a PC, the meta key is the Alt key
and on a Mac, the meta key is the Apple key.
correspond to certain events and conditions. We will use these values to compare events that occur in our applications so that we can tell what event has
occurred.
Mouse Events
Now that you are familiar with the Event class, lets look at some of the methods
that are triggered when an event happens. The first ones well discuss are the
mouse events. These events are probably the most common ones that you will
need to check for. The methods for processing these events can be placed in
several different places in your program. At the highest level, you can override
the events of the GUI elements themselves. For example, you can create your
own button class by extending the Button class. Then, you can override the
default mouse events with your own code. The next option is to place a button
or multiple buttons on a panel and override a buttons mouse events. With this
scenario, you must use if or switch statements to detect which button is pressed.
The final option is to override the mouse events of the applet or frame you are
using for the entire program. This method gets difficult when you have complex
UI environments. Lets take a close look at each of the mouse events in detail.
MOUSEDOWN()
The first argument is an Event object that holds all the information about the event
that has occurred. The second and third arguments are the x and y coordinates
representing where the event took place. The values stored in these arguments are
the same as the values stored in the x and y variables found in the Events class.
Here is an example that uses the mouseDown() method. It illustrates that the
x,y coordinate values set by this method are the same as the values stored in the
x,y instance variables contained in the Events class:
308 Chapter 11
import java.awt.*;
class testEvents extends Frame {
Panel P1;
testEvents() {
super("Test Events");
P1 = new Panel();
setLayout(new FlowLayout());
P1.setBackground(new Color(255,255,255));
add(P1);
resize(300,200);
show();
}
public boolean mouseDown(Event evt, int x, int y) {
System.out.println("X, Y = " + x + ", " + y);
System.out.println("Event X, Y = " + evt.x + ", " + evt.y);
return true;
}
public static void main(String args[]) {
testEvents TE = new testEvents();
}
}
MOUSEUP()
The mouseUp() event method is implemented in the exact same way as the
mouseDown() event method. When you are creating routines that respond to
simple mouse clicks this is usually the place to put the code. Why here instead of
in a mouseDown event method? Well, think about how people use an interface.
Is it more natural for a mouse click event to occur the instant the button is
pressed, or when it is released? If you look at how other programs work, you will
notice that most, if not all, dont respond until the mouse button is released.
You should follow this paradigm for two reasons. First, it represents the standard way
of processing mouse clicks and you do not want to create an interface that seems
inconsistent to the user. Second, it gives the user an opportunity to change his or her
mind. After all, how many times have you started to press a button in a program
only to change your mind, move the mouse off the button, and then let go?
Here is the declaration for the mouseUp() method:
public boolean mouseUp(Event, int, int) {}
Once again, we are given three argumentsan Event object, and two integers
that give us the x and y coordinates of the event.
MOUSEM OVE() AND MOUSEDRAG()
The mouseMove() event method is used to constantly give feedback when the
mouse pointer is over a component. The mouseDrag() event method tells us the
same thing, but only while one of the mouse buttons is pressed. Whenever the
mouse is being moved over your component, one of these methods will constantly
be called. Be careful not to put code in these methods that takes too long to
execute. If you do, you may see some performance degradation in your program.
Here are the declarations for the mouseMove() and mouseDrag() event methods:
public boolean mouseMove(Event, int, int) {}
public boolean mouseDrag(Event, int, int) {}
Again, three arguments are used; an Event object, and two integers that represent the x and y coordinates where the event occurs.
Here is a very simple program that responds to mouse movement and dragging
by displaying the location of the event in the title bar:
import java.awt.*;
class testEvents extends Frame {
testEvents() {
super("Test Events");
resize(300,200);
show();
}
public boolean mouseMove(Event evt, int x, int y) {
setTitle("mouseMove at: " + x + ", " + y);
return true;
}
public boolean mouseDrag(Event evt, int x, int y) {
setTitle("mouseDrag at: " + x + ", " + y);
return true;
}
public static void main(String args[]) {
testEvents TE = new testEvents();
310 Chapter 11
}
}
As you can see, it is extremely easy to respond to mouse events. You may notice
that in this example and in the previous one, you cannot exit out of the program. Basically, what you need to do is check for another event, a system event
that tells you that the user is trying to close the window. This is a very easy thing
to look for, but we did not want to confuse the code with extra methods. Later
in this chapter well show you how to check for system events.
MOUSEE NTER() AND MOUSEEXIT ()
These two events come in handy for certain situations. For example, if you want
to provide feedback to the user when he or she moves the mouse pointer into or
out of your components, you may want to display a message in a status bar. You
can get basically the same effect by checking for the mouseMove() method, but
this method gets called many times while the mouse is over a component and
the mouseEnter() and mouseExit() methods get called only once. The declarations for these event methods are:
public boolean mouseEnter(Event, int, int) {}
public boolean mouseExit(Event, int, int) {}
These methods are also useful for keeping track of how long a person keeps their
mouse over a certain component. For example, assume you were creating a game
and you wanted to cause an event to occur if the player keeps the pointer over
the fire button for too long. You could then respond with a sound or message.
Here is an example that checks the time at which the user moves the mouse onto
the applet and if the user stays for more than two seconds, the status bar displays
an error message. When the user leaves the applet space and returns, the message
returns to normal.
import java.applet.*;
import java.awt.*;
import java.util.*;
// testNav Class
public class testTime extends Applet {
Button B1;
long downTime;
Keyboard Events
Handling keyboard events is similar to handling mouse events. The big difference is that when you process a mouse event, you have only one mouse button
to work. On the other hand, the user can press one of many possible keys, so
processing keyboard events requires an extra step. The two methods you can
use, keyDown() and keyUp(), are very similar to the mouseDown() and
mouseUp() event methods. The only difference is that the keyboard events do
not generate a location where the event has occurred. Instead, they generate an
integer value representing the key that was pressed.
KEYDOWN() AND KEYUP()
Here are the declaration statements for the keyDown() and keyUp() event methods:
312 Chapter 11
public boolean keyDown(Event, int) {}
public boolean keyUp(Event, int) {}
The integer argument stores the numeric value of each key on the keyboard
the ASCII equivalent of a key. Java offers us a simple technique for converting
this ASCII value to a character representation; we simply cast the integer to a
char and there we have it. Here is a simple example:
public boolean keyDown(Event evt, int key) {
System.out.println("Value = " + key + ", character = " + (char)key);
}
This little code snippet simply waits for a key to be pressed then prints the
numeric value of the key and the character representation of that value.
If you look back at the variables defined in the Event class (Table 11.1), youll
notice all of the key representations. These values represent the keys that do not
belong to the standard ASCII character set, including keys like Home, Page Up,
and the function keys. Heres a simple code example that waits for you to press
the F1 key to get help and the Ctrl-x combination to quit the program:
import java.awt.*;
class testKeys extends Frame {
testKeys() {
super("Test Keys");
resize(300,200);
show();
}
public boolean keyDown(Event evt, int key) {
if (evt.controlDown()) {
if (key == 24) {
System.exit(0);
return true;
}
}
if (key == Event.F1) {
setTitle("No help here!");
return true;
}
return false;
}
Hierarchy of Events
Now that youve seen how to create event handlers for specific events, lets look
at how you can create event handlers that capture everything in one central
location. Why would you want to do that? Assume that you have an applet that
uses a set of buttons that perform related operations. You can create separate
event handlers for each control individually, or you can create an event handler
that captures all the events at one location and then uses the information in the
Event object to determine what happened to a certain control.
If you recall from Chapter 9, we created an applet with four buttons. Each
button had a caption that represented a URL for a Web site. When a button is
pressed, the event handler of the applet, not the buttons themselves, processes
the event. This centralized approach makes the events easier to process; however, sometimes it can get a little crowded, especially if you have many components that must respond differently to certain events. In these cases it is up to
you to decide where to handle the events.
If you do not handle an event at the component level, make sure that a system is
in place to hand that event off to the container the particular control resides in.
Lets create a little program that has two buttons in a frame. In the first example
we will use a standard button and catch its events with the frame. In the second
example we will create our own button by subclassing the Button class and
adding our own event handler to that button. Here is the first example:
import java.awt.*;
class testEvents extends Frame {
myButton B1;
myButton B2;
314 Chapter 11
testEvents() {
super("Test Keys");
setLayout(new FlowLayout());
add(new Button("Hello!");
add(new Button("Goodbye!");
resize(300,200);
show();
}
public boolean mouseDown(Event evt, int x, int y) {
if (evt.target instanceof Button) {
System.out.println((String)evt.arg);
return true;
} else {
return super.mouseDown(evt, x, y);
}
}
public static void main(String args[]) {
testEvents TK = new testEvents();
}
}
316 Chapter 11
import java.applet.*;
import java.awt.*;
public class testEvents4 extends Applet {
Label L1 = new Label();
Label L2 = new Label();
Label L3 = new Label();
public testEvents4() {
setLayout(new GridLayout(2, 3));
add(new Label("handleEvent()"));
add(new Label("action()"));
add(new Label("mouseMove()"));
add(L1);
add(L2);
add(L3);
}
public boolean handleEvent(Event evt) {
if (evt.id == Event.MOUSE_MOVE) {
L1.setText("" + evt.when);
this.action(evt, evt.target);
return super.handleEvent(evt);
} else {
return false;
}
}
public boolean action(Event evt, Object arg) {
L2.setText("" + evt.when);
return true;
}
public boolean mouseMove(Event evt, int x, int y) {
L3.setText("" + evt.when);
return true;
}
public void init(){
testEvents TN = new testEvents();
}
} // End Application
Try switching some of the return statements and see what happens. Figure 11.1
shows the applet in action. The applet consists of six Label controls. They are
arranged in a grid. The top three labels list the three methods we are handling.
The three lower labels show the time at which the last event of the respective
type took place.
Figure 11.1
The sample events applet.
ACTION()
METHOD
HANDLEEVENT()
METHOD
The handleEvent() method is probably the most versatile of the event handling
methods. It can catch all the standard user interface events as well as system
events. The ability to catch system events is crucial to larger, more complex
programs. It is also essential to applications. Without the ability to catch system
events, applications would never know when the user has pressed any of the title
bar buttons or selected any of the title bar options.
Here is the declaration for the handleEvent() method:
public boolean handleEvent(Event) {}
318 Chapter 11
You probably have seen this method in use in several of our example programs.
When the user of an application clicks on the close icon for your application, it
sends a message indicating that the close icon has been pressed. This message
comes in the form of WINDOW_DESTROY. We need to catch this event and
then tell the application to quit. Here is a code snippet that will do just that:
public boolean handleEvent(Event evt) {
if (evt.id == Event.WINDOW_DESTROY) {
System.exit(0);
return true;
} else {
super. HandleEvent(evt);
return false;
}
}
This simply checks the event id variable to see if it equals the static variable
WINDOW_DESTROY defined in the Event class. If we receive this event
message, we tell the application to close by calling the exit() method of the
System class.
12
Chapter
Streams and
File I/O
12
Streams and
File I/O
Its now time to learn the ins and outs of
how streams are used in Java to perform
a variety of I/O operations.
What good is a program that has no means of communicating with the outside
world? If you think about it, most programs you write follow a simple pattern of
getting data from a user, processing the data, and presenting the user with the
results in one format or another. Java arranges the world of input/output (I/O)
into a system of byte streams. A byte stream is essentially an unformatted sequence
of data which can come from or be sent to a number of different sources including
the keyboard, screen, file, and so on. To help you process input and output streams
in your programs, Java provides special streams in the System class as well as other
custom classes including InputStream and OutputStream.
In this chapter well show you how to use the System class and the java.io package
to perform different types of stream I/O from reading strings typed in at the keyboard to writing data to files. After we introduce the three streams supported by
the System class well examine the other key stream processing classes including
InputStream, OutputStream, BufferedInputStream, BufferedOutputStream,
ByteArrayInputStream, ByteArrayOutputStream, DataInputStream,
DataOutputStream, FileInputStream, FileOutputStream, and others.
322 Chapter 12
Heres a simple program that uses System.in and System.out to read and write a
string of text:
import java.io.*;
public class ProcessALine {
public static void main(String arg[]) {
// Bring in the stream from the keyboard and pipe it to DataInput
DataInputStream aDataInput = new DataInputStream(System.in);
String aString;
try {
// Continue to read lines from the keyboard until ^Z is pressed
while ((aString = aDataInput.readLine()) != null) {
// Print the line out to the screen
System.out.println(aString);
}
} catch (IOException e) { // Check for I/O errors
System.out.println("An IOException has occurred");
}
}
}
The System.in stream is used to create an input stream object called aDataInput.
This object is created as an instance of the DataInputStream class. The advantage
of this class is that it contains methods like readLine() for processing input streams.
In fact the work of reading a string is accomplishing using a single line of code:
while ((aString = aDataInput.readLine()) != null)
...
The readLine() method will continue to read characters from the input stream
until a Ctrl-Z character is encountered, which terminates the input stream. (Thus,
when you run this program, make sure that you enter a Ctrl-Z at some point to
tell the program to stop reading characters from the input stream.)
This line would bring in the data from a file, buffering it in a stream called
aStream. Then, the data could be accessed all at once by using aStream. This
technique could be very valuable in applications that need to read data all at
once instead of having to read chunks and perform multiple read operations.
324 Chapter 12
Hi Everyone
1 0 1 1 0 1 1
5678432
1010010001
Input Stream
Bye Everyone
56798432
1 1 0 0 1 1 0 1
1010010001
Output Stream
Figure 12.1
A graphical example of converting data for input and output streams.
325
Method
Description
available()
Returns the number of bytes available in the stream without invoking a block.
close()
mark(int)
markSupported()
read()
read(byte[])
Reads a specified number of bytes from the stream and places them in an array
starting at a specified index position.
reset()
skip(long)
Table 12.2
Method
Description
close()
flush()
write(int)
write(byte[])
326 Chapter 12
ServerSocket mrsServer = null;
Socket socketReturn = null;
// Assigns the variable rawDataOut to the class OutputStream
OutputStream rawDataOut = null;
try {
mrsServer = new ServerSocket( 10, 2 );
socketReturn = mrsServer.accept();
serverScreen.appendText( "Connected to the mrsServer" );
// Creates an instanceof the class OutputStream named
// rawDataOut
// rawDataOut receives the stream from the Socket socketReturn
rawDataOut = socketReturn.getOutputStream();
DataOutputStream DataOut = new DataOutputStream(rawDataOut);
DataOut.write( 5 );
} catch( UnknownHostException e ) {
} catch( IOException e ) {
}
}
BufferedInputStream and
BufferedOutputStream Classes
These classes are used to implement streams responsible for collecting data from
a source that brings in data at a slower rate than the recipient. Then, the chunks
of data collected may be delivered in larger, more manageable blocks than in the
manner they were received. This proves beneficial for file systems and networks,
where the connection depends on a device for transmission.
Here are the declarations for these classes:
InputStream aStream = new BufferedInputStream(getStreamFromASource());
OutputStream aStream = new BufferedInputStream(getStreamToASource());
Method
Description
available()
Determines the number of bytes available in the stream without invoking a block.
mark(int)
markSupported()
read()
Reads a specified number of bytes from the stream and places them in an array
starting at a specified index position.
reset()
skip(long)
Table 12.4
Method
Description
flush()
write(int)
key methods defined in BufferedInputStream and Table 12.4 presents the methods defined in BufferedOutputStream.
Heres an example of an application that uses the BufferedInputStream class to
derive another class for performing a simple input operation:
import java.io.*;
// Reads from a file
public class ReadAFile extends Object {
ReadAFile(String s) {
String line;
FileInputStream fileName = null;
// Assigns the variable bufferedInput to the class
// BufferedInputStream
BufferedInputStream bufferedInput = null;
DataInputStream dataIn = null;
try {
fileName = new FileInputStream(s);
// Creates an instance of the class BufferedInputStream named
// bufferedInput
328 Chapter 12
// bufferedInput receives the stream from the FileInputStream
// fileName as it is read
bufferedInput = new BufferedInputStream(fileName);
dataIn = new DataInputStream(bufferedInput);
}
catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
}
catch(Throwable e) {
System.out.println("Error in opening file");
return;
}
try {
while ((line = dataIn.readLine()) != null) {
System.out.println(line + "\n");
}
fileName .close();
}
catch(IOException e) {
System.out.println("Error in reading file");
}
}
// Where execution begins in a stand-alone executable
public static void main(String args[]) {
new ReadAFile(args[0]);
}
}
ByteArrayInputStream and
ByteArrayOutputStream Classes
These streams create a new stream from an array of bytes to be processed. They
are used to perform the reverse operations of what most of the streams do. To
declare and create an object from these classes you would use statements like the
following:
InputStream aStream = new ByteArrayInputStream(getStreamFromASource());
OutputStream aStream = new ByteArrayInputStream(getStreamToASource());
Method
Description
available()
Returns the number of bytes available in the stream without invoking a block.
read()
Reads a specified number of bytes from the stream and places them in an array
starting at a specified index position.
reset()
skip(long)
Table 12.6
Method
Description
reset()
size()
toByteArray()
toString()
toString(int)
Converts input bytes to a string, sets the selected bytes first 8 bits of a 16 bit
Unicode to hibyte.
write(int)
writeTo(OutputStream)
330 Chapter 12
import java.io.*;
// Reads from a file
public class Byte2String extends Object {
Byte2String(String s) {
byte[] anArrayOBytes;
try {
// Creates an instanceof the class InputStream named byteDataIn
// byteDataIn receives the stream from the ByteArrayInputStream
// anArrayOBytes
InputStream byteDataIn = new ByteArrayInputStream(anArrayOBytes);
}
catch(IOException e) {
}
Notice in both declarations the need to declare the class type, DataInputStream
or DataOutputStream, instead of type InputStream or OutputStream. The
methods getStreamFromSource() and getStreamToASource() can be any methods
that return a stream. Once the stream is passed to the DataInputStream or
DataOutputStream object, the methods declared in the interface can be applied
to the stream. Table 12.7 presents the key methods defined in DataInputStream
and Table 12.8 presents the methods defined in DataOutputStream.
Method
Description
read(byte[])
Reads a specified number of bytes from the stream and places them in an array
starting at a specified index position.
readBoolean()
readByte()
readChar()
readDouble()
readFloat()
readFully(byte[])
Reads bytes from the stream, blocking until all bytes are read.
readFully(byte[], int, int) Reads bytes from the stream, blocking until all bytes are read. The starting point
to begin reading and the maximum number of bytes to read are passed as
parameters.
readInt()
readLine()
readLong()
readShort()
readUTF()
readUTF(DataInput)
readUnsignedByte()
readUnsignedShort()
skipBytes(int)
Table 12.8
Method
Description
flush()
size()
write(int)
writeBoolean(boolean)
writeByte(int)
writeBytes(String)
332 Chapter 12
Table 12.8
Method
Description
writeChar(int)
writeChars(String)
writeDouble(double)
writeFloat(float)
writeInt(int)
writeLong(long)
writeShort(int)
writeUTF(String)
Lets revisit our example of the client application once more to demonstrate the
use of a DataInputStream:
import java.io.*;
import java.net.*;
import java.awt.*;
public class mrClient extends Frame {
mrClient() {
super("Client Application");
TextArea clientScreen = new TextArea("mrClient's Screen:\n", 10, 40);
add("Center", clientScreen);
pack();
show();
Socket mrClient = null;
InputStream rawDataIn = null;
try {
mrClient = new Socket( InetAddress.getLocalHost(), 10 );
rawDataIn = mrClient.getInputStream();
// reads in the stream for the InputStream rawDataIn and pipes
// it to DataIn
DataInputStream DataIn = new DataInputStream(rawDataIn);
// the array of bytes is then read from the stream
clientScreen.appendText( "mrClient receives - " +
DataIn.read() );
} catch( UnknownHostException e ) {
} catch( IOException e ) {
}
}
Here the stream used with the Socket object, mrClient, is piped from the
InputStream to the DataInputStream. The bytes are then read from the stream,
DataIn, and appended to the text box with this line:
clientScreen.appendText("mrClient receives -
" + DataIn.read());
By simply changing the method, we can read any type of data that resides in the
stream. For example, if we wanted to read a stream of chars, we would use a
statement like this:
clientScreen.appendText("mrClient receives -
" + DataIn.readChar());
Method
Description
available()
Returns the number of bytes available in the stream without invoking a block.
close()
finalize()
getFD()
Returns the file descriptor of the file associated with the stream.
read()
read(byte[])
Reads a specified number of bytes from the stream and places them in an array
starting at a specified index position.
skip(long)
334 Chapter 12
Table 12.10 Key Methods Defined in the FileOutputStream Class
Method
Description
close()
finalize()
getFD()
Returns the file descriptor of the file associated with the stream.
write(int)
write(byte[])
Here is a practical example of how you can use the FileOutputStream and
FileInputStream classes:
import java.io.*;
public class WriteAFile {
WriteAFile(String s) {
write(s);
}
// Writes to a file
public void write(String s) {
// Assigns the variable writeOut to the class FileOutputStream
FileOutputStream writeOut = null;
DataOutputStream dataWrite = null;
try {
// Creates an instanceof the class FileOutputStream named writeOut
// writeOut receives the stream from the File designated in the
// variables
writeOut = new FileOutputStream(s);
dataWrite = new DataOutputStream(writeOut);
dataWrite.writeChars("This is a Test");
dataWrite.close();
}
catch(IOException e) {
System.out.println("Error in writing to file");
}
catch(Throwable e) {
System.out.println("Error in writing to file");
}
finally {
System.out.println("\n\n.....creating a backup file.");
335
try {
// Recreates an instanceof the class FileOutputStream named
// writeOut
// writeOut receives the stream from the File named
// "MyBackup.sav"
writeOut = new FileOutputStream("MyBackup.sav");
dataWrite = new DataOutputStream(writeOut);
dataWrite.writeChars("This is a Test");
dataWrite.close();
}
catch (IOException e) {
System.out.println("Error in writing backup file");
}
}
}
// Where execution begins in a stand-alone executable
public static void main(String args[]) {
new WriteAFile(args[0]);
}
}
FilterInputStream and
FilterOutputStream Classes
These are classes that act as channels for streams to be passed through. As a
stream is passed through the shell, a hierarchy of stream containers are created to
perform some processing of bytes as the methods are passed along with it. This
structure allows for a chaining effect of shells to break up a complicated task into
small steps. Here are the declarations for these classes:
FilterInputStream anotherStream = new FilterInputStream(aStream);
FilterOutputStream anotherStream = new FilterOutputStream(aStream);
336 Chapter 12
Table 12.11 Key Methods Defined in the FilterInputStream Class
Method
Description
available()
Returns the number of bytes available in the stream without invoking a block.
close()
finalize()
getFD()
Returns the file descriptor of the file associated with the stream.
read()
read(byte[])
Reads a specified number of bytes from the stream and places them in an array
starting at a specified index position.
skip(long)
Description
close()
flush()
write(int)
write(byte[])
LineNumberInputStream Class
This class allows for line numbering of each line processed through the stream.
It is useful for determining which lines errors have occurred on. To declare and
create an object from this class, you use a statement like the following:
LineNumberInputStream aStream =
LineNumberInputStream(getStreamFromASource());
338 Chapter 12
BufferedInputStream
BufferedInputStream bufferedInput = null;
DataInputStream dataIn = null;
try {
fileName = new FileInputStream(s);
// Creates an instanceof the class LineNumberInputStream named
// parsedData
// parsedData receives the stream from the FileInputStream
// fileName as it is read
LineNumberInputStream parsedData = new
LineNumberInputStream(fileName);
dataIn = new DataInputStream(parsedData);
}
catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
}
catch(Throwable e) {
System.out.println("Error in opening file");
return;
}
try {
while ((line = dataIn.readLine()) != null) {
// adds the current line number to the beginning of every line
System.out.println(parsedData.getLineNumber() + ": " + line +
"\n");
}
fileName .close();
}
catch(IOException e) {
System.out.println("Error in reading file");
}
}
// Where execution begins in a stand-alone executable
public static void main(String args[]) {
new ReadAFile(args[0]);
}
}
Description
available()
Returns the number of bytes available in the stream without invoking a block.
getLineNumber()
mark(int)
read()
Reads a specified number of bytes from the stream and places them in an array
starting at a specified index position.
reset()
setLineNumber(int)
skip(long)
PipedInputStream and
PipedOutputStream Classes
These classes allow for pipe-like connection between two threads to allow for
safe communication between a shared queue. For this technique to be effective,
both threads must implement the class. To declare and create objects from these
class, you use statements like the following:
PipedInputStream aThreadStreamIn =
PipedInputStream(getStreamFromASource());
PipedOutputStream aThreadStreamOut = PipedOutputStream(aThreadStreamIn);
Description
close()
connect(PipedOutputStream)
read()
Reads a specified number of bytes from the stream and places them in an
array starting at a specified index position.
340 Chapter 12
Table 12.15 Key Methods Defined in the PipedOutputStream Class
Method
Description
close()
connect(PipedInputStream)
write(int)
PrintStream Class
This class is most commonly used to create an instance of the System class,
where the methods print() and println() are referenced as class variables for use
in the System.out and System.err calls. The most common output device for
this class is the screen. The declaration for the PrintStream class is:
PrintStream aStream = new PrintStream( getStreamFromASource());
Along with this class accepting the write(), flush(), and close() methods, it supports a slew of print methods that will handle just about every I/O operation
you will need to perform. Most often, an object created from this class will be
used like this:
System.out.print(aStream);
System.out.println(aStream);
The only difference between the two calls is that the second call appends a return
character to the end of the stream. Table 12.16 presents the key methods defined in
PrintStream. Here is a simple example of how the PrintStream class can be used
to return a line that was typed in by the user:
import java.io.*;
public class ProcessALine {
public static void main(String arg[]) {
DataInputStream aDataInput = new DataInputStream(System.in);
String aString;
try {
// A Control Z exits
while ((aString = aDataInput.readLine()) != null) {
Description
checkError()
close()
flush()
print(Object)
Prints an Object.
print(String)
Prints a String.
print(char[])
print(char)
Prints a char.
print(int)
Prints an Integer.
print(long)
Prints a long.
print(float)
Prints a float.
print(double)
Prints a double.
print(boolean)
Prints a boolean.
println()
println(Object)
println(String)
println(char[])
println(char)
println(int)
println(long)
println(float)
println(double)
println(boolean)
write(int)
Writes an array of bytes, starting point to begin writing, n number of bytes to write.
342 Chapter 12
PushbackInputStream Class
This class causes the stream to reaccept a byte that was passed to it by the
InputStream. By forcing the byte back to the delivering InputStream, you can
reread the byte as if it had never been read. To declare a stream as
PushbackInputStream and instaniate it, you could type the following:
PushbackInputStream aStream =
new PushbackInputStream (getStreamFromASource());
SequenceInputStream Class
This class allows for two streams to be seamlessly joined. This is especially useful
when creating an exception that would pick up where it left off last in a transfer.
To declare a stream as type SequenceInputStream and instaniate it, you would
type the following:
InputStream aStream = new SequenceInputStream(firstStream, secondStream);
Description
available()
Returns the number of bytes available in the stream without invoking a block.
markSupported()
read()
Reads a specified number of bytes from the stream and places them in an array
starting at a specified index position.
unread(int)
Returns a char to the stream as if it had not been read in the first place.
Description
close()
read()
Reads a specified number of bytes from the stream and places them in an array
starting at a specified index position.
StringBufferInputStream Class
This class is very similiar to the ByteArrayInputStream class. The difference is
that it combines an array of char types into a stream. Note, an array of chars is
actually a string. To declare and create an object from this class, you use a statement like the following:
InputStream aStream = new StringBufferInputStream(String);
Description
available()
Returns the number of bytes available in the stream without invoking a block.
read()
Reads a specified number of bytes from the stream and places them in an array
starting at a specified index position.
reset()
skip(long)
344 Chapter 12
import java.io.*;
// Reads from a file
public class Char2Stream extends Object {
Char2Stream(String s) {
String aCommonString = "The quick brown fox jumped over the lazy dog";
try {
// Creates an instanceof the class InputStream named charDataIn
// charDataIn receives the stream from the
// StringBufferInputStream aCommonString
InputStream charDataIn = new
StringBufferInputStream(aCommonString);
}
catch(IOException e) {
}
Index
A
Abstract classes, 33, 121, 158
Abstract methods, 132
Abstract Window Toolkit, 32
Action( ) method, 294
Add method, 274
Addition, 98
Addressing
Internet, 353
Animation
buffering, 40
speed, 26
API documentation, 64
Applet class
hierarchy, 288
methods available, 288
methods derived, 290
Applets, 5, 6
browser interaction, 294
class, 287
closing, 51
compiling, 53
defined, 21
drawbacks, 291
file access, 292
file execution, 292
fonts, 43
images, 298
navigation sample, 293
network communication, 292
package, 31
parameters, 39
passing information, 367
sounds, 297
tags, 39
threading, 51
ticker tape sample, 22
vs. applications, 21
Appletviewer, 7
Applications
command line arguments, 86
defined, 21
networking, 353
sample menu, 268
vs. applets, 21
Architecture natural, 5
Arguments
accessing, 88
indexing, 89
numeric, 89
passing, 87
reading, 87
Arrays, 16, 82
accessing data, 86
declaring, 82
elements, 83
indexing, 85
multidimensional, 85
sizing, 83
Assignment boolean operators, 102
Assignment operators, 93, 95
Audio clips, 297
AWT, 31, 227
AWTError, 191
403
404 Index
class hierarchy, 230
components, 229
defined, 32
importing, 228
layout manager, 228
menus, 229
B
Bandwidth considerations, 360
Binary, 97
Binary integer operators, 99
Binary operators, 98
Bitwise complement, 97
Bitwise operators, 99
Blocking, 217
Body (class), 128
Boolean data type, 78
Boolean operators
assignment, 102
evaluation, 101
logical, 100
negation, 100
ternary, 102
BorderLayout class, 274
declaration, 275
methods, 275
Break statement, 110
Browsers
HotJava, 6
Netscape, 26
BufferedInput Stream class, 327
BufferedOutputStream class, 327
Buffering, 40, 45
Button class
declaration, 243
getLabel( ), 244
hierarchy, 243
setLabel( ), 244
Buttons, 32
Byte streams, 321
Byte type, 76
ByteArrayInputStream class, 328
C
Canvas class
declaration, 245
hierarchy, 244
paint( ), 245
CardLayout class, 282
declaration, 282
methods, 282
Case-sensitivity
declarations, 36
package names, 171
parameters, 40
variable names, 36
Casting
interfaces, 165
vs. creating, 151
Casts, 103
Catch statements, 187
Catch( ) method, 185
Catching errors, 186
CGI. See Common Gateway
Interface
Char data type, 79
Character arrays, 16
Character literals, 73
Checkbox class, 245
declaration, 246
getCheckboxGroup( ), 247
getLabel( ), 247
getState( ), 247
hierarchy, 246
setCheckboxGroup( ), 247
setLabel( ), 247
setState( ), 247
Choice class, 247
addItem( ), 249
countItems( ), 249
declaration, 248, 251
getItem( ), 249
Index
getSelectedIndex( ), 249
getSelectedItem( ), 249
hierarchy, 248, 250
methods, 251
select( ), 250
Classes, 5
abstract, 33, 121, 158
advantages, 116
applet, 287
body, 128
bufferedInputStream, 328
bufferedOutputStream, 327
button, 243
byteArrayInputStream, 328
byteArrayOutputStream, 328
canvas, 244
casting, 150
checkbox, 245
choice, 247
component, 290
container, 290
dataInputStream, 330
dataOutputStream, 330
declaring, 116
defined, 32
documenting, 63
error, 191
event, 304
exception, 193
extending, 124
fileInputStream, 333
fileOutputStream, 333
filterInputStream, 335
filterOutputStream, 335
final, 33, 123
flowLayout, 271
frame, 235
fully qualified name, 118
hiding, 177
identifiers, 124
importing packages, 176
InetAddress, 354
inputStream, 325
label, 241
lineNumberInputStream, 337
list, 250
menuItem, 265
modifiers, 33, 119
name space, 34, 129
naming, 124
networking, 353
object, 34
outputStream, 325
panel, 238
pipedInputStream, 339
pipedOutputStream, 339
printStream, 340
private, 33
protocols, 158
public, 33, 120
pushbackInputStream, 342
runtime, 194
scrollbar, 258
sequenceInputStream, 342
socket, 355
stringBufferInputStream, 343
super( ), 142
superclass, 34
System, 321
textArea, 253
textField, 253
throwable, 182
URL, 364
variables, 148
WriteAFile, 185
CLASSPATH, 171, 173, 174
Client, 350
Client/server technology, 350
Code parameter, 27
Color method, 37
Command line arguments, 86
indexing, 89
numeric, 89
passing arguments, 87
reading, 87
Comments, 30
styles, 59
tags, 67
405
406 Index
Common Gateway Interface, 10
Compilers, 7, 53
Component class
bounds( ), 232
disable( ), 232
enable([Boolean]), 232
getFontMetrics( ), 232
getGraphics( ), 232
getParent, 232
handleEvent(Event evt), 232
hide( ), 233
inside(int x, int y), 233
isEnabled( ), 233
isShowing( ), 233
isVisible( ), 233
locate(int x, int y), 233
location( ), 233
move(int x, int y), 233
repaint( ), 233
resize( ), 234
setFont( ), 234
show([Boolean]), 234
size( ), 235
Components, 60
Compound expressions, 104
Compound statements, 106
Constructors, 37, 138
body, 146
calling, 140
declaring, 140
FontMetrics, 48
Java default, 142
modifiers, 143
object creation, 148
protected, 143
public, 143
return type, 139
Container class, 290
Control flow, 106
Control structures
do...while, 108
for, 110
if...else, 106
labels, 111
D
Data types, 35
boolean, 78
byte, 76
casting, 103
char, 79
double, 78
float, 78
int, 71, 77
long, 71, 77
separators, 75
short, 76
string, 79
variables, 76
DataInputStream class, 330
DataOutputStream class, 330
Debugging, 181
Decrement operator, 98
Destroy( ) method, 222
Developers Kit, 17
Directories
Index
search path, 174
Disassembler program, 17
Distributed programming, 6
Distributed software, 10
Division, 98
Do...while, 108
Doc comment clauses, 119
Documenting classes, 63
Double buffering, 45
Double data type, 78
E
Encapsulation, 43
Equal to operators, 102
Error handling, 181
Errors
catching, 186
checking, 323
file not found, 189
input/output, 185
throws, 133
try clauses, 186
Evaluation operators, 101
Event class, 304
methods, 306
variables, 305
Event handling, 53
Events
hierarchy, 313
processing problems, 318
system, 315
types, 304
Exceptions, 15, 181, 182
class, 193
creating, 200
error, 191
file not found, 189
finally statements, 189
handler, 182
IOException, 185
try clauses, 186
URL, 364
Executable content, 10
Export statement, 228
Expressions
assignment, 105
writing, 104
Extending classes, 124
Extends keyword, 34
F
Fatal errors, 191
File
access, 292
execution, 292
input/output, 321
saving, 173
File Transfer Protocol. See FTP
FileInputStream class, 333
FileOutputStream class, 333
FilterInputStream, 335
FilterOutputStream class, 335
Final classes, 33
Final methods, 132
Finally statement, 189
Finger protocol, 349
Float data type, 78
Floating-point, 72
operators, 102
FlowLayout class, 271
declaration, 271
methods, 273
Font metrics, 48
Fonts, 43
For loops, 110
Frame class, 235
declaration, 235
dispose( ), 237
getIconImage( ), 237
getMenuBar, 237
getTitle( ), 237
hierarchy, 235
isResizable( ), 238
remove( ), 238
407
408 Index
setCursor( ), 238
setIconImage( ), 238
setMenuBar( ), 238
setResizeable( ), 238
setTitle( ), 238
FTP, 349
G
Garbage collection, 6, 15, 37
Gateways, 355
Graphical User Interface
button class, 243
canvas class, 244
checkbox class, 245
choice class, 247
component class, 231
frame class, 235
label class, 241
lists, 250
menu class, 263
menu items, 265
menuBar class, 261
panel class, 238
scrollbar class, 258
text areas, 253
text fields, 253
Graphics methods, 46
GridBagLayout class, 278
declaration, 281
methods, 281
variables to customize, 278
GridLayout class, 276
declaration, 277
methods, 277
H
Header files, 13
Height parameter, 27
Helper programs, 17
Hexadecimal format, 71
History of Java, 8
HotJava, 6, 10
HTML. See Hyper Text Markup
Language
applet tags, 39
HTTP, 349
Hyper Text Markup Language, 25
Hyper Text Transfer Protocol. See HTTP
I
Identifiers, 65
class, 118
classes, 124
errors, 67
If...else, 106
Image buffer, 41
Images, 298
Implements clause, 126
Implements keywords, 34
Import statements, 31, 228
Including packages, 31
Increment operator, 98
Index, 84
InetAddress class, 354
Init( ), 130
Input streams, 321, 324
InputStream class, 325
methods, 325
Instanceof operator, 17, 168
Int data type, 77
Integers, 71
literals, 72
operators, 93, 97
Interfaces, 34, 158
casting, 165
class, 126
declaring, 161
design issues, 160
implementation tips, 167
implementing, 161
implements clauses, 126
keyword, 161
Index
layout manager, 271
runnable, 34
tips on using, 165
Internet
addressing, 353
java.net package, 352
Request for Comments, 351
IOException, 324
J
Java language
advantages, 4
benefits, 11
compared to C++, 9
developers kit, 7, 17
history, 8
interfaces, 158
jargon, 5
tools, 8
virtual machine, 6
JAVAC, 7, 53
JAVADOC.EXE, 63
Java-enabled, 7
JAVAP, 17
JavaScript, 7
Just-in-Time compiler, 7
K
Keyboard events, 311
keyDown( ), 311
keyUp( ), 311
Keywords, 68
class, 124
extends, 34, 124
implements, 34, 162
interface, 161
list of keywords, 69
super, 135
this, 50, 135
L
Label class, 241
declaration, 241
getAlignment( ), 242
getText( ), 242
hierarchy, 241
setAlignment( ), 242
setText( ), 243
Labels, 111
Layout manager, 228, 270
borderLayout class, 274
cardLayout class, 282
flowLayout class, 271
gridBagLayout class, 278
gridLayout class, 276
Lexical structures, 58
comments, 59
identifiers, 65
keywords, 68
separators, 75
LineNumberInputStream class, 337
List class, 250
Literals, 71
character, 73
numeric, 71
Logical operators, 100
Long data type, 77
Long integers, 71
M
Main programs, 27
Menu class, 263
declaration, 264
hierarchy, 263
methods, 264
MenuBar class, 262
declaration, 262
hierarchy, 262
methods, 262
MenuItem class, 265
409
410 Index
declaration, 266
hierarchy, 266
methods, 267
Menus, 32
creating, 229
Methods, 7, 38, 130
abstract, 132
action( ), 294
add( ), 274
applet class, 288
body, 134
catch( ), 185
color, 37
constructors, 138
createImage( ), 230
declaring, 130
defined, 28
destroy( ), 222
disable( ), 230
documenting, 63
drawString( ), 48
final, 132
getGraphics( ), 41
getMessage, 198
getParameter( ), 40
graphics, 46
handleEvent( ), 53
hide( ), 230
init( ), 28, 130
main( ), 87
modifiers, 131
native, 132, 292
overloading, 137
overriding, 43, 137, 170
paint( ), 29, 44
parameter lists, 133
parse( ), 89
private, 132
protected, 131
public, 131
resume( ), 220
return type, 133
Run( ), 29, 214
sleep( ), 50
start( ), 29
static, 132
stop( ), 51, 221
suspend( ), 220
synchronized, 132
throwing an exception, 194
throws, 133
valueOf( ), 89
write( ), 184
yield, 221
Modifiers
abstract, 121
constructor, 143
final, 123, 150
method, 131
modifiers, 33, 119
public, 120
transient, 150
volatile, 150
Modulus operator, 99
Mouse events, 304, 307
mouseDown( ), 307
mouseDrag( ), 309
mouseEnter( ), 310
mouseExit( ), 310
mouseMove( ), 309
mouseUp( ), 308
Multidimensional arrays, 85
Multiple inheritance, 14
Multiplication, 98
Multithreading, 7, 208
grouping, 226
synchronizing, 222
N
Name space, 129
Native methods, 132, 292
Negation operator, 97
Netscape
applet, 294
Network communication, 292
Index
Network News Transfer Protocol.
See NNTP
Networking, 347
between applets, 367
classes, 353
client/server, 350
concerns, 360
java.net, 352
ports, 350
protocols, 348
sockets, 355
URLs, 364
New lines, 356
NNTP, 349
Not equal to operators, 102
Numeric literals, 71
O
Object-oriented programming, 12
Objects
arrays, 82
class, 34
creation, 148
declaring, 118
Octal integers, 71
Operators, 74, 93
addition, 98
assignment, 95, 102
binary, 98
binary integer, 99
bitwise, 99
bitwise complement, 97
boolean negation, 100
compound expressions, 104
decrement, 98
division, 98
equal to, 102
evaluation, 101
floating-point, 102
increment, 98
instanceof, 17, 168
integer, 97
P
Packages, 30
applet, 31
awt, 31
case sensitivity, 171
classes, 30
creating, 168
documenting, 63
import keyword, 169
java.io, 322
java.lang, 30
java.net, 352
naming, 170
public classes, 172
standard Java, 177
Paint( ) method, 44
Panel class, 238
declaration, 240
hierarchy, 240
setlayout( ), 241
Parameter lists
constructor, 146
Parameters, 39
code, 27
height, 27
speed, 26
values, 27
width, 27
Parsing, 89
411
412 Index
Performance issues
threading, 51
PipedInputStream class, 339
PipedOutputStream class, 339
Pointers, 13
Ports, 350
Internet, 351
numbers, 350
Precedence (operators), 93
PrintStream class, 340
Private
constructors, 143
methods, 132
Processing parameters, 39
Protected
constructors, 143
methods, 131
Protocols
class, 158
finger, 349
FTP, 349
Internet, 351
NNTP, 349
Request for Comments, 351
SMTP, 348
TCP/IP, 348
WhoIs, 349
Public
classes, 33, 120
constructors, 143
keyword, 162
method, 131
PushbackInputStream class, 342
R
Request for Comments. See Request for
Comments
Resizing, 239
Resource allocation, 37
Resume( ) method, 220
Return type, 133
Returns, 356
S
Savings files, 173
Scripting language, 7
Scrollbar class, 258
hierarchy, 260
methods, 260
Security, 12, 15, 292
Seprators, 75
SequenceInputStream class, 342
Servers, 350
sample, 361
setting up, 360
ServerSocket class, 360
Shadowing, 129
Short type, 76
Simple Mail Transfer Protocol.
See SMTP
Simple statements, 105
Single inheritance, 121
Sleep( ) method, 50, 219
Socket class, 360
Sockets, 355
Sounds, 297
Source code
saving, 173
Statements, 105
catch, 187
compound, 106
control flow, 106
finally, 189
simple, 105
switch, 109
using semi-colons, 106
writing, 104
Static methods, 132
Status bar, 296
Stop( ) method, 221
Index
Streams, 321
inputStream, 324
outputStream, 324
String arrays, 16
String type, 79
StringBufferInputStream class, 343
Subclasses, 44
Subtraction, 98
Super classes, 16
Super keyword, 135
Super( ), 142
Suspend( ) method
suspending execution, 220
Switch, 109
Synchronized methods, 132
System class, 321
system.in, 322
System events, 315
action( ), 317
handleEvent( ), 317
T
Tags, 67
TCP/IP, 348
Ternary operators, 102
TextArea class, 253
declaration, 254
hierarchy, 254
methods, 255
TextField class, 253
declaration, 254
hierarchy, 254
methods, 255
This keyword, 50, 135
ThreadGroup, 226
Threads, 29, 49, 182, 207, 212
blocking, 217
creating, 211
destroy( ) method, 222
first in first out, 217
grouping, 226
initializing, 215
413
U
Unary, 97
Unicode, 73
Uniform Resource Locator. See URLs
URLs, 364
User input, 52
User interface
component class, 231
layout manager, 271
menus, 229
V
Variable declarations, 35
Variables
constructors, 37
declarations, 79
modifiers, 149
naming, 36
414 Index
static, 149
variables, 148
vs. types, 76
Virtual machine, 6, 210
Volatile modifiers, 150
W
Web sites
Coriolis, 25
Javasoft, 54
While, 108
Y
Yield( ) method, 221