Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Working with Threads 271

TheclassDeclaration


The first thing you need to do in this applet is to use importfor classes in
the packages java.awt, java.net,java.applet, java.awt.event, and
javax.swing.


After you have used importto make some classes available, you’re ready
to begin the applet with the following statement:


public class LinkRotator extendsJApplet
implementsRunnable, ActionListener {


This statement creates the LinkRotatorclassas a subclass of the JApplet
class. It also indicates that two interfaces are supported by this class—
Runnableand ActionListener. By implementing the Runnableclass, you are
able to use a run()method in this applet to make a thread begin running.
The ActionListenerinterfaceenables the applet to respond to mouse clicks.


Setting Up Variables


The first thing to do in LinkRotatoris create the variables and objects of
the class. Create a six-element array of Stringobjects called pageTitle
and a six-element array of URLobjects called pageLink:


String[] pageTitle= new String[6];
URL[] pageLink= new URL[6];


The pageTitlearrayholds the titles of the six websites that are displayed.
The URLclass of objects stores the value of a website address. URLhas all
the behavior and attributes needed to keep track of a web address and use
it to load the page with a web browser.


The last three things to create are a Colorobject named butterscotch, an
integer variable called current, and a Threadobject called runner:


Color butterscotch= newColor(255, 204, 158);
intcurrent= 0;
Thread runner;


Colorobjects represent colors you can use on fonts, user interface compo-
nents, and other visual aspects of Swing. You find out how to use them
during Hour 23, “Creating Java2D Graphics.”


The currentvariable keeps track of which site is being displayed so you
can cycle through the sites. The Threadobject runnerrepresents the thread
this program runs. You call methods of the runnerobject when you start,
stop, and pause the operation of the applet.

Free download pdf