You’re now ready to create the program and test it. Create a new empty Java file named LinkRotator
and type in the text from Listing 19.2.
1: import java.applet.*;
2: import java.awt.*;
3: import java.awt.event.*;
4: import javax.swing.*;
5: import java.net.*;
6:
7: public class LinkRotator extends JApplet
8: implements Runnable, ActionListener {
9:
10: String[] pageTitle = new String[6];
11: URL[] pageLink = new URL[6];
12: Color butterscotch = new Color(255, 204, 158);
13: int current = 0;
14: Thread runner;
15:
16: public void init() {
17: pageTitle = new String[] {
18: "Sun's Java site",
19: "Cafe au Lait",
20: "JavaWorld",
21: "Java in 24 Hours",
22: "Sams Publishing",
23: "Workbench"
24: };
25: pageLink[0] = getURL("http://java.sun.com");
26: pageLink[1] = getURL("http://www.ibiblio.org/javafaq");
27: pageLink[2] = getURL("http://www.javaworld.com");
28: pageLink[3] = getURL("http://www.java24hours.com");
29: pageLink[4] = getURL("http://www.samspublishing.com");
30: pageLink[5] = getURL("http:// workbench.cadenhead.org");
31: Button goButton = new Button("Go");
32: goButton.addActionListener(this);
33: FlowLayout flow = new FlowLayout();
34: setLayout(flow);
35: add(goButton);
36: }
37:
38: URL getURL(String urlText) {
39: URL pageURL = null;
40: try {
41: pageURL = new URL(getDocumentBase(), urlText);
42: } catch (MalformedURLException m) { }
43: return pageURL;
44: }
45:
46: public void paint(Graphics screen) {
47: Graphics2D screen2D = (Graphics2D) screen;
48: screen2D.setColor(butterscotch);
49: screen2D.fillRect(0, 0, getSize().width, getSize().height);
50: screen2D.setColor(Color.black);
51: screen2D.drawString(pageTitle[current], 5, 60);
52: screen2D.drawString("" + pageLink[current], 5, 80);
53: }
54:
55: public void start() {
56: if (runner == null) {
57: runner = new Thread(this);
58: runner.start();
59: }
60: }
61:
62: public void run() {
63: Thread thisThread = Thread.currentThread();
64: while (runner == thisThread) {
65: current++;
66: if (current > 5) {
67: current = 0;
68: }
69: repaint();
70: try {
71: Thread.sleep(10000);
72: } catch (InterruptedException e) {
73: // do nothing
74: }
75: }
76: }
77:
78: public void stop() {
79: if (runner != null) {
80: runner = null;
81: }
82: }
83:
84: public void actionPerformed(ActionEvent event) {
85: if (runner != null) {
86: runner = null;
87: }
88: AppletContext browser = getAppletContext();
89: if (pageLink[current] != null) {
90: browser.showDocument(pageLink[current]);
91: }
92: }
93: }
After you save the program, you need to create a web page in which to put the applet—it won’t work correctly if you use Run, Run File to test it in NetBeans because links can’t be opened that way. Create a new web page—choose File, New File, and then click Other to find the HTML File option in the File Types pane of the Choose File Type dialog. Name the web page LinkRotator
, which NetBeans saves as NetBeans.html
, and then enter Listing 19.3 as the web page’s markup.
1: <applet
2: code="LinkRotator.class"
3: codebase="..\build\classes"
4: width="300"
5: height="100"
6: >
7: </applet>
When you’re done, right-click the name LinkRotator.html
in the Project pane and choose View. The page opens in a web browser, and the applet displays each of the links in rotation. Click the Go
button to visit a site. Figure 19.2 shows what the applet looks like in Internet Explorer.
Threads are a powerful concept implemented with a small number of classes and interfaces in Java. By supporting multithreading in your programs, you make them more responsive and can speed up how quickly they perform tasks.
Even if you learned nothing else from this hour, you now have a new term to describe your frenzied lifestyle. Use it in a few sentences to see if it grabs you:
• “Boy, I was really multithreading yesterday after we held up that string of liquor stores.”
• “I multithreaded all through lunch, and it gave me gas.”
• “Not tonight, dear, I’m multithreading.”
Q. Are there any reasons to do nothing within a catch
statement, as the LinkRotator
applet does?
A. It depends on the type of error or exception being caught. In the LinkRotator
applet, you know with both catch
statements what the cause of an exception would be, so you can be assured that doing nothing is always appropriate. In the getURL()
method, the MalformedURLException
would be caused only if the URL sent to the method is invalid.
Q. Whatever happened to the band that sang “My Future’s So Bright, I Gotta Wear Shades”?
A. Their future was not bright. Timbuk3, a band formed by husband and wife Pat and Barbara K. MacDonald, never had another hit after the song that became a top 20 single in 1986. They produced six albums from 1986 to 1995, when they broke up the band and divorced.
Pat MacDonald continues to perform and release albums under his own name. He’s also written songs for Cher, Peter Frampton, Night Ranger, Aerosmith, and other musicians.
Barbara Kooyman performs as Barbara K and has several albums, one that reinterprets Timbuk3 songs. She also formed the artist’s free speech charity Artists for Media Diversity.
Their best known song, widely taken to be a positive message about the future, was supposed to be ironic. The MacDonalds said the bright future was actually an impending nuclear holocaust.
Set aside your threads (in the Java sense, not the nudity sense) and answer the following questions about multithreading in Java.
1. What interface must be implemented for a program to use threads?
A. Runnable
B. Thread
C. JApplet
2. If an interface contains three different methods, how many of them must be included in a class that implements the interface?
A. None of them.
B. All of them.
C. I know, but I’m not telling.
3. You’re admiring the work of another programmer who has created a program that handles four simultaneous tasks. What should you tell him?
A. “That’s not half as exciting as the Anna Kournikova screensaver I downloaded off the Web.”
B. “You’re the wind beneath my wings.”
C. “Nice threads!”
1. A. Runnable
must be used with the implements
statement. Thread
is used inside a multithreaded program, but it is not needed in the class statement that begins a program.
2. B. An interface is a guarantee that the class includes all the interface’s methods.
3. C. This compliment could be confusing if the programmer is well dressed, but let’s be honest, what are the chances of that?
If this long workshop hasn’t left you feeling threadbare, expand your skills with the following activities:
• If you are comfortable with HTML, create your own home page that includes the LinkRotator
applet and six of your own favorite websites. Use the applet along with other graphics and text on the page.
• Add a button to the PrimeFinder
application that can stop the thread while the sequence of prime numbers is still being calculated.
To see Java programs that implement these activities, visit the book’s website at www.java24hours.com.
3.145.57.254