服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

the java programming tutorial: vol. 2


  the java programming tutorial: vol. 2
classes, threads, and applets

by mark c. reynolds
reprinted from web developer? magazine, vol. 2 no. 2 may/june 1996 ?
1996
the java language provides everything one would expect in a modern object-orie
nted programming language. it has all the standard control constructs, a reaso
nably comprehensible object model, and tools for creating standalone applicati
ons or smaller applets that are designed to run inside web pages.

the power of java does not reside primarily in the language itself, however; i
t resides in the libraries that accompany it: the java class hierarchy. the fi
rst part of this tutorial, in the spring 1996 issue of web developer?, dea
lt with the java language and the construction of simple applets. this part wi
ll focus on the set of java classes associated with graphics, known as the adv
anced windowing toolkit, or awt. applet construction will also be revisited, w
ith an eye toward event handling and multitasking.

programming low-level graphics is often like constructing a sand castle one gr
ain of sand at a time. higher-level toolkits allow more rapid construction of
user interfaces, but they lack fine control and involve certain design comprom
ises and limitations. very high-level gui builders can be extremely powerful,
but they can also be the source of enormous frustration when asked to do somet
hing outside their repertoire. where does java s awt fit in?

in many ways, the advanced windowing toolkit will seem very familiar to anyone
who has ever used a toolkit to write a graphics program under almost any wind
owing system. the design issues are the same: the suite of components (buttons
, labels, scrollbars, cuboctohedra) that are available, how these components a
re arranged visually, and the mechanisms involved in communicating between the
components and the application program itself. you want a button labeled canc
el, you want it in the lower right-hand corner of your graphic, and you want t
o tie it to a function named cancelaction(), for example. the awt gives you se
veral ways to accomplish these goals. it also provides a set of very powerful
classes and methods that give java programmers some distinctly different highe
r-level tools (as well as some distinctly different programming challenges).

there are four aspects to programming with the awt: establishing the layout, i
mplementing the components, manipulating global resources such as colors and f
onts, and handling events. each of these aspects interacts with the others in
well-defined ways.

one of the strengths of the awt is that it was designed to be platform-indepen
dent. this does not guarantee that any piece of awt code will look exactly the
same on a unix machine, a windows 95 box, or a macintosh, but only that the b
ehavior of the awt will be the same on each. we will consider each of the four
aspects of awt programming in turn.

unlike many toolkits, the awt does not really enforce a specific layout policy
. instead, it provides five standard layout classes that correspond to commonl
y encountered types of layouts. these are the borderlayout, cardlayout, flowla
yout, gridlayout, and gridbaglayout classes. it is also possible to create one
s own layout class (although this is not for the faint of heart) or to eschew
any formalized layout altogether and place one s components at absolute (x,y)
coordinates. most awt applets will end up using flowlayout, gridlayout, or bo
rderlayout, which are conceptually the simplest.

in order to understand the idea behind the layout classes, we will start with
a simple example using borderlayout. in a borderlayout, components may be plac
ed at the north, south, east, or west locations, or they may be placed in the
center. it is called a "border" layout because each component that s added sti
cks to its corresponding border (with the exception of the center component, w
hich occupies the unused space in the middle). figure 1 shows a code fragment
that creates a border layout with four buttons, one at each cardinal point.

this code first creates a new instance of the borderlayout class using the new
operator, and then calls the setlayout method with that instance as its sole
argument. what is the purpose of this statement? we can guess that this establ
ishes the borderlayout as the default layout for the applet. the real reason t
hat it works is that a java applet is actually an instance of the applet class
, and the applet class is actually a subclass of a graphical container class k
nown as a panel. just as any applet must extend the applet class, so applet ex
tends panel. the call to setlayout is actually manipulating the panel in which
the applet resides.

the next four statements create four buttons named for their intended location
s. the text of each button is taken from the instance variables north, south,
east, and west, which have been declared with the keywords static and final.

this is the standard approach to declaring constants in java. java has no cons
t keyword, like c++. instead it uses the keywords final, which indicates that
the instance variable may not be changed, and static, which says that this ins
tance variable is shared among all instances of its class. it is very importan
t to realize that while the static keyword has the same meaning of permanence
it has in c and c++, it does not affect the scope of the instance variable, as
it would in c and c++. other keywords (private and protected) are used for th
at purpose.

after the buttons have been created, they are entered into the layout using th
e add method. a final call is then made to the show method to ensure that all
the components are drawn. each of the five layout classes has its own peculiar
form of the add method. in the case of borderlayout, it wants add to have two
arguments: the first is the placement location, and the second is the compone
nt to be added. note that in this example, the button labels are identical to
their placement locations. this is by no means necessary; the buttons could ju
st as easily have been named moe, larry, curly, and shemp. the add method, how
ever, must be given one of the cardinal directions exactly as shown or it will
fail to understand. you cannot add(norte, el_amador), even if el_amador is a
valid button instance.

this example is, of course, extremely boring. the buttons are not connected to
anything, so that pressing them will not have any meaningful results. it is s
traightforward to modify this code into a complete applet that will do somethi
ng meaningful. in particular, we can change it so that it will illustrate some
thing interesting about applet events. a text-area component will be added at
the center location. we will also add an event handler, which will write infor
mation into that text area about the events received by the applet. the comple
te code for this simple evlab (event lab) applet is shown in figure 2.

this code uses a little bit of everything. it declares and uses the borderlayo
ut class; it incorporates three types of graphical components (button, textfie
ld and textarea); it makes use of one of the global graphical elements, namely
font; and it incorporates some rudimentary event handling. it also represents
a new type of applet, one that is not threaded. this last point will be discu
ssed in more detail below.

the init() method of the evlab applet is similar to the blex.java code shown p
reviously. this code make more extensive use of other graphical components. it
still places buttons at the north, east, and west locations. this version of
init() creates a textfield and puts that at south, and also creates a textarea
and puts that in the center position of the borderlayout. these two text comp
onents are almost identical to the html elements of the same names. a textfiel
d is used to display a single line of text. it may be read/write or read-only.
in our example it has been created with no initial text (the first argument t
o the constructor is "") and has width 70. by default, textfields are read/wri
te so that it will be possible to type into this particular component.

the construction of the centrally placed textarea is a little more elaborate.
a textarea is a multiline text entity, which can also be read/write or read-on
ly. in our case it has been created with an initial size of 10 x 70. the call
to the seteditable() method with the false argument declares that the user wil
l not be able to modify the contexts of this text area. a specific font to be
used is also set by calling the setfont() method. this is done for both the ed
itable text field down south and the text area in the center.

the font was obtained by calling the font() constructor with three arguments:
the name of the font, the font style, and the font size. times roman is one of
a small number of fonts that java guarantees to provide (the others include h
elvetica and courier). the style argument indicates whether we want the plain
version (font.plain), bold version (font.bold), italic version (font.italic),
or some other style. styles may be combined, so that if the second argument ha
d been font.bold + font.italic, java would have tried to find a times roman 14
-point font that was both bold and italic. the init() method concludes by succ
essively adding each of the five components to the borderlayout and then calli
ng show() to insure that they are shown.

in addition to the init() method, which initializes the graphic environment, t
his applet also has an action() method (and two placeholder methods, start() a
nd stop(), discussed below).

as one might guess, the action method is used to capture events. the action()
method is passed two arguments: an event instance ev and an object arg. the ev
ent instance ev describes the event that just happened. the second argument, a
rg, represents component-specific information that the awt gives you to help h
andle the event. when a button is pressed, for example, the action method will
be called, with arg set equal to the label of the button that was just presse
d.
figure 3

in our evlab example, we do not attempt to do anything to the incoming events
and their arguments except to display information about them. the first statem
ent of the action() method uses the settext method of the text area tfe to dis
play the event id of the incoming event. using settext ensures that any previo
us text in this text area is cleared. the event id is a somewhat mystical numb
er describing the type of event. the next four statements of the action() meth
od append additional information about the event ev and the argument arg to th
e text area. since each string used ends with a newline "", each will be on
its own line. the x and y coordinates of the site of the event are printed, as
well as the target of the event (which component was affected), and the arg f
ield of the event ev. it is often the case that ev.arg and the argument arg ar
e identical. figure 3 shows the appearance of the evlab applet after the west
button has been pressed.

the final statement of the action() method is return(false). this is necessary
because our action() method overrides a built-in applet method that returns a
boolean value. the return code is used to indicate if the event has been hand
led. like many windowing systems, the awt uses a hierarchical event-handling m
odel. just as graphics may be built in a layered fashion, so events may be gen
erated and handled at any of the various levels. our action() method returns f
alse to indicate that the event has not been handled.

an excellent way to use the event lab applet to demonstrate the event hierarch
y is to type some text into the text field in the south position, and then hit
return. this will generate an event that will be displayed in the text area i
n the center of the applet. the third line of text, the one describing the eve
nt target, will be too long, and it will be necessary to scroll the text area
using the horizontal scrollbar on the bottom of the text area. when you hit th
is scrollbar, it will scroll the central text area, and it will not generate a
nother event. in reality, when the scrollbar is activated it does generate ano
ther event, but that event is intercepted and processed by the text area itsel
f. the result is the scroll action that we see.

since that event is completely processed by the text area, it never reaches th
e action() event handler of the evlab applet--it has been consumed by the text
area s own built-in event handler. the reader is strongly encouraged to exper
iment with the evlab applet by placing other types of graphical components (as
described below) in the south position and determining what types of events a
re generated.

what of the other layout methods? flowlayout is the simplest of the five types
. when this form of layout is used, components are added from left to right. w
hen all the available space in a given row has been used, a new row will be cr
eated. rows can be center justified (the default) or left or right justified.
flowlayout is typically used for rows of similar items, such as buttons. an ex
ample of this layout approach will be given below.

gridlayout is a structured layout format in which graphical components are pla
ced on a grid with a fixed size. if a gridlayout is created with a grid of 3 r
ows by 5 columns, for example, then we can add a component at location (2,3),
which will correspond to the third column of the second row. gridbaglayout is
an extensible form of grid layout, in which the grid is permitted to expand as
new elements are added. gridbaglayout is the most general layout strategy, an
d also the most complex. finally, cardlayout implements a hypercard-style layo
ut. graphical components are added to individual cards, which are then display
ed sequentially, rather than simultaneously.

figure 4 lists the graphical components, such as button, and the global graphi
cal elements, such as font, that are provided by the awt. if you have ever don
e any sort of graphics programming, many of these items will be very familiar
to you. a list is actually a scrolling listbox, rather than a lisp-like list.
a checkboxgroup is called a radio button by most other graphics systems.

note that the list of graphical components includes items that are containers,
such as panel. this makes the hierarchical organization described above possi
ble. we could modify the event lab applet to put a panel in the central positi
on, give that panel its own layout, and then proceed to add components to that
panel. this panel might have a gridlayout, even though the applet s panel has
a borderlayout.

the java api provides all the details on using the various components and glob
al elements. rather than attempt an exhaustive description of all of them, thi
s article will conclude by focusing on a small set of classes related to anima
tion. we have already seen a very simple demonstration of image loading in the
first part of this tutorial. a java vcr will now be developed that will allow
us to load a set of images and then smoothly display them under user control.
to do this, however, we must make a short detour and discuss the topic of thr
eads in java.

threads
most modern operating systems support the concept of multitasking, in which mu
ltiple independent processes timeshare the same physical cpu. soon after the f
irst multitasking os was created, it was realized that it would be delightful
to support the same sort of multiple-task model inside application programs, r
ather than just at the command-line level. the first implementations of this i
dea were cumbersome, and involved copying the entire code and data space of th
e parent task to all newly created child tasks. eventually, the concept of thr
eads was born. a thread is a lightweight task, without much context. good thre
ad implementations should allow a top-level application to create multiple thr
eads, assign each a piece of work, coordinate them, and ultimately clean up wh
en all of them are done. java supports just such a threaded programming model.


the concept of threads not only applies to stand-alone java applications, but
also to java applets. the evlab.java applet in figure 2 does not make explicit
use of threads. it has an init() method, which is called when the applet is l
oaded; a start() method, which is called after loading is complete (and when a
previously loaded java page is revisited); and a stop() method, which is call
ed when a page containing the java applet is unloaded, or when another page is
visited. both the tiny applets shown in the first part of the tutorial, as we
ll as the vcr.java applet shown in figure 5, are threaded applets. we know thi
s because they implement the runnable interface: the phrase "implements runnab
le" is part of the applet s class declaration. a runnable applet will also hav
e a run() method, which will be entered whenever a new thread is created for t
he applet s class. if this explanation seems a bit obscure, it should become m
ore clear as we work through the code of the java vcr.

the init() method does a number of very familiar things. its goal is to load a
number of images, specified by the html param attribute "nimgs." these images
are to be found at a location specified by the param "imgloc" relative to the
document base. each image has a numerical suffix, as well as the suffix .gif.
thus if nimgs is 10 and imgloc is images/myanim, then the applet will look fo
r its images in files named images/myanim1.gif through images/myanim10.gif. th
e first few lines of the init() method retrieve these parameters from the html
environment using getparameter() and do some sanity checking. if everything s
eems reasonable, a new instance of the mediatracker class is created and store
d in the instance variable tracker. space is also allocated for an array of ni
mgs images in the instance variable imgs. a for loop is then used to attempt t
o load each of the images into that array. note that two loop variables are us
ed, because the imgs[] array is 0-indexed, while the image names have suffixes starting from 1.

the for loop also contains the statement tracker.addimage(imgs[i], 0). the med
iatracker class is being used to keep track of the progress of the images bein
g loaded. this is necessary because getimage() does not actually get the image
--it simply arranges to start getting it. the call to the addimage() method of
tracker tells the tracker instance to begin keeping track of that image. the
second argument to addimage() is an arbitrary id, 0 in this case, which can be
used to subsequently inquire about the progress of all images with that id. e
ffectively, we are placing all the images in a single pool, associated with id
0, whose status will be queried later.

the init() method next builds a layout in which the images and a series of con
trol buttons will be displayed. a borderlayout with two elements is used for t
he applet s panel. the north element will be a panel that will hold the images
as they are being animated, while the south element will be another panel tha
t will hold the control buttons. the variable nodim is used to store the apple
t s preferred size (set by the width and height attributes in the applet tag).
we make the north panel as wide as the entire applet, but carve 50 pixels out
of its height for the south panel to occupy.

the south panel is constructed using a left-justified flowlayout. this means t
hat the buttons we add to it will be added from left to right. the remainder o
f the init() method constructs these buttons, sets the button font to 14 point
helvetica, and then adds those buttons to the south panel. note that it is ne
cessary to explicitly say so.add(). if we had used add(), the buttons would ha
ve been added to the top-level borderlayout. this code illustrates hierarchica
l organization using the awt. the top-level applet panel is a borderlayout pan
el with two elements: both panels themselves. the north panel contains no sube
lements, while the south panel contains four: the four buttons labeled fwd, re
v, stop, and eject.

before we discuss the run() method, let us first consider the start() and stop
() methods. when init() method completes, the start() method will be invoked.
it will examine the instance variable animthread, discover that it is null, an
d therefore will create a new thread with the argument this. this statement ac
tually creates a new java thread based on the vcr class. the next statement, a
nimthread.start(), runs that thread. by virtue of this statement, the run() me
thod will be entered in that separate thread of control. the stop() method is
the inverse of the start() method. when the page is unloaded, the stop() metho
d will be called. it will terminate the animthread thread using animthread.sto
p(), and then reset the animthread variable to null. this ensures that if the
page is reloaded or revisited, the start() method will create a new thread yet
again.

the run() method and the action() event handler work together to display the i
mages according to the controls that the user has pressed. the run() method st
arts out by doing some additional sanity checking. it then calls tracker.waitf
orid(0). this call will wait until all the images associated with id 0 (which
will be all the images in this case) have been fully loaded and prepared for o
n-screen display. this method invocation in encased in a peculiar construction
known as a try block. try blocks are necessary because some methods can raise
exceptions, which must be caught. if such an exception occurs (because there
is not enough memory for all the images, for example), the run() method return
s via the catch clause.

the next two statements are a little bit of thread magic. the run method disco
vers the current thread and places that in the local variable me. it then lowe
rs its own thread priority to one below the normal thread priority. this ensur
es that the other thread--the one actually doing the drawing--has higher prior
ity, which is what most animation applications would want. after this is done,
the run() method enters a loop. if the instance variable imginc is nonzero, t
hen the index of the image to be displayed will be updated and a call to repai
nt() made to ensure that the new image is shown. the instance variable whichim
g is used to hold the index of the image currently being drawn. great care is
taken to ensure that whichimg stays within range. it must never be less than 0
(the minimum image number) or greater than nimgs-1 (the maximum image number)
. after the image has been updated, the thread puts itself to sleep for 100 mi
croseconds. this is another thread trick, ensuring that the java runtime will
actually look for another thread to run. after all, there really is only a
single cpu and a single applet, so java must somehow decide when to run the
various threads. when java notices that one thread has put itself tosleep, all
other threads become runnable.

the action() method controls the critical-instance variables imginc and done.
the action() method looks for events that are associated with buttons. the ev.
target field will always indicate the type of graphical object that was associ
ated with the event. java has a very convenient operator, instanceof, to test
if something opaque like ev.target is actually an instance of a particular cla
ss--button, in this case. if the test passes, then the local variable thelab i
s set to the label of the button. a four-way test is now done. if the user pre
ssed fwd, then imginc is set to 1 and the images move forward. if rev was pres
sed, imginc becomes -1 and the images move backward. if stop is pressed, imgin
c is set to 0, and the images move no more; they rest at the current image. fi
nally, if eject is pressed, the instance variable done is set to true.

the paint() method does the work of actually drawing the images. if done is fa
lse, then it performs a number of sanity checks, and finally uses the drawimag
e() method to draw the current image, represented by the index whichimg. becau
se of the use of the mediatracker at the top of the run method, we can be sure
that all images are loaded and ready to be drawn so that the animation will g
o quite smoothly. if done is true, then the paint() method clears the entire d
rawing area, erasing all images but leaving the buttons intact. note that the
paint() method can be called by the browser environment itself, not just by re
paint(). if you obscure the applet s drawing area with another window and then
reexpose it, the paint() method will be called. this is why it is important t
hat the instance variable whichimg always have a sane value.
figure 7

figure 6 shows a simple html file that can be used to load images into the vcr
applet. figure 7 shows the applet captured in motion, at about image 7. sun s
tumbling duke gifs were used to create this particular animation, although an
y set of images could have been used. if you download the java development kit
(jdk), these images will be found in the demo/tumblingduke/images directory.

this vcr applet can serve as a template for animation applets, since it contai
ns all the basic elements of a threaded graphics applet. the start() and stop(
) methods can be used as shown. the mediatracker code and the thread manipulat
ion portions of the init() and run() methods are also quite generic. more work
needs to be done in order to make this applet robust, however. the applet nev
er checks to see if the image dimensions will actually fit in the applet s pan
el, for example.

developing yourself
the java development kit may be obtained at ftp.javasoft. almost all major pla
tforms, including several flavors of unix, windows nt, windows 95, and the mac
intosh now support some version of the jdk. sun also has a web server at
http://javasoft.com but it is often overloaded. one of the most comprehensive
and accessible java sites, the gamelan repository, has many useful public-
domain classes,applets, and applications. sun itself is publishing a set of
definitive reference works on java. the reader may also benefit from lemay and
perkins book teach yourself java in 21 days.

figure 1
creating four buttons using the border layout class
public static final string north = "north";
public static final string south = "south";
public static final string east = "east";
public static final string west = "west";

public void init() {
setlayout(new borderlayout());
button no = new button(north);
button ea = new button(east);
button we = new button(west);
button so = new button(south);
add(north, no);
add(south, so);
add(east, ea);
add(west, we);
show();
}

figure 2
capturing and displaying applet events
import java.awt.*;
import java.applet.*;
import java.net.*;

public class evlab extends applet {
public static final string north = "north";
public static final string south = "south";
public static final string east = "east";
public static final string west = "west";
textarea tfe;

public void init() {
setlayout(new borderlayout());
button no = new button(north);
button ea = new button(east);
button we = new button(west);
textfield tff = new textfield("", 70);
font fo = new font("timesroman", font.bold, 14);
tfe = new textarea(10, 70);
tfe.seteditable(false);
tfe.setfont(fo);
tff.setfont(fo);
add("center", tfe);
add(south, tff);
add(north, no);
add(east, ea);
add(west, we);
show();
}

public void start() {
}

public void stop() {
}

public boolean action(event ev, object arg) {
tfe.settext("id = " + ev.id + "");
tfe.appendtext("x,y = " + ev.x + "," + ev.y + "");
tfe.appendtext("target = " + ev.target.tostring() + "");
tfe.appendtext("arg = " + ev.arg + "");
tfe.appendtext("object = " + arg.tostring());
return(false);
}

}

figure 3:

figure 4
graphical components and global elements of the java awt
awt components
button canvas checkbox checkboxgroup

choice dialog filedialog frame

label list menu menubar

menuitem panel scrollbar textarea

textfield window

awt global elements

color dimension font fontmetrics

graphics image insets mediatracker

point polygon rectangle

figure 5
a vcr animation applet in java

/**
a vcr in java
@author mark c. reynolds
@version 1.0, 23 feb, 1996
*/

import java.applet.*;
import java.awt.*;
import java.net.*;

public class vcr extends applet implements runnable {
mediatracker tracker;
dimension nodim;
thread animthread = null;
image imgs[];
static final string fwd = "fwd";
static final string rev = "rev";
static final string stop = "stop";
static final string eject = "eject";
int whichimg = 0;
int imginc = 0; // +1 = forward, -1 = reverse, 0 = stop
int nimgs = 0;
boolean done = false;

public void init() {
borderlayout nl;
flowlayout fl;
button bu[];
font fo;
panel so;
panel no;
string tmp;
string imgloc;

imgloc = getparameter("imgloc");
if ( imgloc != null ) {
tmp = getparameter("nimgs");
if ( tmp != null ) {
nimgs = integer.parseint(tmp);
if ( nimgs > 0 ) {
imgs = new image[nimgs];
tracker = new mediatracker(this);
for(int i = 0, j = 1; i < nimgs; i++, j++) {
imgs[i] = getimage(getdocumentbase(), imgloc + j + ".g
if");
tracker.addimage(imgs[i], 0);
}

nl = new borderlayout();
setlayout(nl);
no = new panel();
nodim = preferredsize();
no.resize(nodim.width, nodim.height-50);
add("north", no);
so = new panel();
fl = new flowlayout(flowlayout.left);
so.setlayout(fl);
add("south", so);
bu = new button[4];
bu[0] = new button(vcr.fwd);
bu[1] = new button(vcr.rev);
bu[2] = new button(vcr.stop);
bu[3] = new button(vcr.eject);
fo = new font("helvetica", font.plain, 14);
for(int i = 0; i < 4; i++)
bu[i].setfont(fo);
so.add(bu[0]);
so.add(bu[1]);
so.add(bu[2]);
so.add(bu[3]);
}
}
}
}

public void run() {
thread me;

if ( nimgs < 1 || imgs == null ) return;
try {
tracker.waitforid(0);
} catch (interruptedexception e) {

return;
}
me = thread.currentthread();
me.setpriority(thread.norm_priority-1);
while ( animthread != null ) {
whichimg += imginc;
if ( whichimg < 0 )
{
whichimg = 0;
imginc = 0;
}
if ( whichimg >= nimgs )
{
whichimg = (nimgs - 1);
imginc = 0;
}
if ( imginc != 0 ) repaint();
try {
thread.sleep(100);
} catch (interruptedexception e) {
break;
}
}
}

public void paint(graphics g) {
if ( done == false ) {
if ( ( imgs != null ) && ( 0 <= whichimg ) && ( whichimg < nimgs ) &
&
( imgs[whichimg] != null ) ) {
g.drawimage(imgs[whichimg], 0, 0, this);
}
} else {
g.clearrect(0, 0, nodim.width, nodim.height);
}
}

public void start() {
if ( animthread == null ) {
animthread = new thread(this);
animthread.start();
}
}

public void stop() {
if ( animthread != null ) {
animthread.stop();
animthread = null;
repaint();
}
}

public boolean action(event evt, object arg) {
button thebut;
string thelab;
boolean handled = false;

if ( evt.target instanceof button ) {
thebut = (button)(evt.target);
thelab = thebut.getlabel();
if ( thelab.equals(vcr.fwd) ) {
imginc = 1;
handled = true;
} else if ( thelab.equals(vcr.rev) ) {
imginc = (-1);
handled = true;
} else if ( thelab.equals(vcr.stop) ) {
imginc = 0;
handled = true;
} else if ( thelab.equals(vcr.eject) ) {
imginc = 0;
done = true;
stop();
handled = true;
}
}
return(handled);
}
}

figure 5
/**
a vcr in java
@author mark c. reynolds
@version 1.0, 23 feb, 1996
*/

import java.applet.*;
import java.awt.*;
import java.net.*;

public class vcr extends applet implements runnable {
mediatracker tracker;
dimension nodim;
thread animthread = null;
image imgs[];
static final string fwd = "fwd";
static final string rev = "rev";
static final string stop = "stop";
static final string eject = "eject";
int whichimg = 0;
int imginc = 0; // +1 = forward, -1 = reverse, 0 = stop
int nimgs = 0;
boolean done = false;

public void init() {
borderlayout nl;
flowlayout fl;
button bu[];
font fo;
panel so;
panel no;
string tmp;
string imgloc;

imgloc = getparameter("imgloc");
if ( imgloc != null ) {
tmp = getparameter("nimgs");
if ( tmp != null ) {
nimgs = integer.parseint(tmp);
if ( nimgs > 0 ) {
imgs = new image[nimgs];
tracker = new mediatracker(this);
for(int i = 0, j = 1; i < nimgs; i++, j++) {
imgs[i] = getimage(getdocumentbase(), imgloc + j + ".g
if");
tracker.addimage(imgs[i], 0);
}

nl = new borderlayout();
setlayout(nl);
no = new panel();
nodim = preferredsize();
no.resize(nodim.width, nodim.height-50);
add("north", no);
so = new panel();
fl = new flowlayout(flowlayout.left);
so.setlayout(fl);
add("south", so);
bu = new button[4];
bu[0] = new button(vcr.fwd);
bu[1] = new button(vcr.rev);
bu[2] = new button(vcr.stop);
bu[3] = new button(vcr.eject);
fo = new font("helvetica", font.plain, 14);
for(int i = 0; i < 4; i++)
bu[i].setfont(fo);
so.add(bu[0]);
so.add(bu[1]);
so.add(bu[2]);
so.add(bu[3]);
}
}
}
}

public void run() {
thread me;

if ( nimgs < 1 || imgs == null ) return;
try {
tracker.waitforid(0);
} catch (interruptedexception e) {

return;
}
me = thread.currentthread();
me.setpriority(thread.norm_priority-1);
while ( animthread != null ) {
whichimg += imginc;
if ( whichimg < 0 )
{
whichimg = 0;
imginc = 0;
}
if ( whichimg >= nimgs )
{
whichimg = (nimgs - 1);
imginc = 0;
}
if ( imginc != 0 ) repaint();
try {
thread.sleep(100);
} catch (interruptedexception e) {
break;
}
}
}

public void paint(graphics g) {
if ( done == false ) {
if ( ( imgs != null ) && ( 0 <= whichimg ) && ( whichimg < nimgs ) &
&
( imgs[whichimg] != null ) ) {
g.drawimage(imgs[whichimg], 0, 0, this);
}
} else {
g.clearrect(0, 0, nodim.width, nodim.height);
}
}

public void start() {
if ( animthread == null ) {
animthread = new thread(this);
animthread.start();
}
}

public void stop() {
if ( animthread != null ) {
animthread.stop();
animthread = null;
repaint();
}
}

public boolean action(event evt, object arg) {
button thebut;
string thelab;
boolean handled = false;

if ( evt.target instanceof button ) {
thebut = (button)(evt.target);
thelab = thebut.getlabel();
if ( thelab.equals(vcr.fwd) ) {
imginc = 1;
handled = true;
} else if ( thelab.equals(vcr.rev) ) {
imginc = (-1);
handled = true;
} else if ( thelab.equals(vcr.stop) ) {
imginc = 0;
handled = true;
} else if ( thelab.equals(vcr.eject) ) {
imginc = 0;
done = true;
stop();
handled = true;
}
}
return(handled);
}
}

figure 6
the html file which drives the java vcr

<html>
<head>
<title>a java vcr</title>
</head>
<body>
<hr>
<applet code="vcr.class" width=300 height=150>
<param name=imgloc value="images/t">
<param name="nimgs" value="16">
</applet>
<hr>
<a href="vcr.java">the source.</a>
</body>
</html>

figure 7

扫描关注微信公众号