v.addElementnFields[3].getText; v.addElementvFields[3].getText;v.addElementoFields[1].getText; v.addElementnFields[4].getText; v.addElementnFields[5].getText; v.addElementvFields[3].getT
Trang 1v.addElement(nFields[3].getText()); v.addElement(vFields[3].getText());
v.addElement(oFields[1].getText()); v.addElement(nFields[4].getText());
v.addElement(nFields[5].getText()); v.addElement(vFields[3].getText());
v.addElement(oFields[1].getText()); v.addElement(nFields[6].getText());
v.addElement(vFields[7].getText()); v.addElement(nFields[7].getText());
v.addElement(vFields[3].getText()); v.addElement(oFields[1].getText());
v.addElement(vFields[0].getText()); v.addElement(vFields[0].getText());
v.addElement(vFields[0].getText()); v.addElement(oFields[0].getText());
v.addElement(vFields[1].getText()); v.addElement(oFields[2].getText());
v.addElement(nFields[0].getText()); v.addElement(vFields[0].getText());
v.addElement(vFields[0].getText()); v.addElement(vFields[0].getText());
v.addElement(oFields[0].getText()); v.addElement(vFields[2].getText());
v.addElement(oFields[5].getText()); v.addElement(vFields[4].getText());
v.addElement(vFields[4].getText()); v.addElement(oFields[6].getText());
s = new String[v.size()];
v.copyInto(s);
return s;
} }
When you are writing an applet, it is best to refrain from using the newest Java features, because browser support for the newest releases always comes later than the release dates of the Java API Another potential problem is that even when new versions are released, most users do not keep their Java VMs up to date To reach the widest possible audience, try to use features and classes of Java that are well established Be careful, however, about deprecation A class, field, or method is deprecated when the standard version of Java encourages you not to use it (usually because a better method has been developed or because the future releases will not support this aging method) The newest ver-sion of Java might support it, but when you compile your code, you will get a warning Future releases of Java will probably omit the deprecated features altogether.
Rewriting the MadLib Game
This section describes the changes that I made to the AdvancedMadLib.java source code, which I renamed to MadLibApplet.javato differentiate it from the original The first visible change is the fact that I imported the java.applet.Appletpackage and extended Appletinstead of GUIFrame Instead of extending GUIFrame, I included a GUIFramemember, frame, which I use when this
is run as an application or to its own dialog box when it runs as an applet I moved the code that used to reside in the AdvancedMadLib constructor to the init()method I also added the instantiation of the frameobject to the init() method The reason for using the GUIFrameeven when this is run as an applet is because, when you create a Dialog object, you have to pass either a Frame or
T R I C K 298
J a
s o
l ut
n e
Trang 2another Dialogto be its owner You can see that when I construct the storyDia-log object, I pass in frame instead of this because the Applet class does not extend either Frameor Dialog Okay, so far, that’s all you need to do to run this
as an applet
To be able to run this as an application also, I added a main()method The main() method creates a new MadLibAppletobject, mla, calls its init()method to build
up its GUI, and then adds the Applet to the frame object by calling showIn-Frame() showInFrame()adds this MadLibAppletto frame, packs it, and makes it visible There, once the HTML is written, this game can be run as both an applet and an application Here is the source code for MadLibApplet.java:
/*
* MadLibApplet
* A Rewrite of the AdvancedMadLib Application from Chapter 7
* so that it can be run as an Applet or an Application.
*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class MadLibApplet extends Applet { GUIFrame frame;
Panel navPanel;
MadInputPanel inputPanel;
Button prev, next, showStory;
Choice inputChoice;
Dialog storyDialog;
TextArea story;
public void init() { setLayout(new BorderLayout());
frame = new GUIFrame("Create your own Song");
//Card Panel (contains other panels in a CardLayout) inputPanel = new MadInputPanel();
add(inputPanel, BorderLayout.CENTER);
//Navigation Panel navPanel = new Panel();
navPanel.setLayout(new GridLayout(0, 4, 10, 0));
prev = new Button("<- Prev");
prev.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { inputPanel.previous();
} });
navPanel.add(prev);
inputChoice = new Choice();
inputChoice.add("Nouns");
inputChoice.add("Verbs");
299
Trang 3inputChoice.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { inputPanel.show((String)e.getItem());
} });
navPanel.add(inputChoice);
next = new Button("Next ->");
next.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { inputPanel.next();
} });
navPanel.add(next);
showStory = new Button("Show/Refresh Story");
showStory.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createStory();
storyDialog.setVisible(true);
} });
navPanel.add(showStory);
add(navPanel, BorderLayout.SOUTH);
storyDialog = new Dialog(frame, "Your Song");
storyDialog.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { storyDialog.setVisible(false);
} });
story = new TextArea("", 27, 50);
story.setEditable(false);
storyDialog.add(story);
storyDialog.pack();
} public void showInFrame() { frame.add(this);
frame.pack();
frame.setVisible(true);
} public static void main(String args[]) { MadLibApplet mla = new MadLibApplet();
mla.init();
mla.showInFrame();
} private void createStory() { String song = "";
String[] segs = {", ", ", ", " my ", "\nDon't ", " a ", " ",
"\n", ", ", ", ", " my ", "\nJust ", " your pretty ",
300
J a
s o
l ut
n e
Trang 4"\nI'll be ", " you again \nI'll be ", " you in ",
"\n\nDon't ", " to me oh ",
"\nYour ", "'s in a ", " ",
", yeah \nDon't ", " to me oh ",
"\nShould have ", " it a-",
" on\nDon't ", " to me oh ",
"\nI don't know it was ", " your ",
"\nDon't ", " to me oh ",
"\nDead-end ", " for a dead-end ",
"\nDon't ", " to me oh ",
"\nNow your ", " ", " on the ",
"\nDon't ", " to me oh ",
"\n\n", ", ", ", ", " my ", "\nDon't ", " a ", " ",
"\n", ", ", ", ", " my ", "\nJust ", " your pretty ",
"\nI'll be ", " you again \nI'll be ", " you in "};
String[] s = inputPanel.getStringArray();
for (int i = 0; i < segs.length; i++) { song += s[i] + segs[i];
} song += s[s.length - 1];
story.setText(song);
} } Here is the HTML file to include the MadLibAppletapplet:
<html>
<head>
<title>Mad Lib</title>
</head>
<body>
<h1>Mad Lib</h1>
<applet code="MadLibApplet.class" width=550 height=250></applet>
</body>
</html>
The MadLibAppletis shown in Figure 8.10 running as an applet You can also run
it as an application by typing java MadLibApplet at your command prompt It will look and run exactly as it did in Chapter 7
Using Sounds and Images
The Applet class has built-in support for playing sounds and loading and dis-playing images In this section, you learn how to do both of these things from applets First, I’ll go over playing audio files, and then get into displaying images
301
Trang 5Playing Sound Files
Playing sound files from applets is actually very easy You can use getAudio-Clip(URL)or getAudioClip(URL, String)to load an audio clip as an AudioClip instance AudioClipis actually an interface in the java.appletpackage It has three methods:
void play() Plays an audio clip from beginning to end
void loop() Continuously plays this audio clip in a loop from
begin-ning to end
void stop() Stops playing the audio clip
The URLobject specifies the location of the audio clip As you would imagine, it’s just a class in the java.netpackage that encapsulates a Uniform Resource Loca-tor It isn’t covered in this book, so for more information, consult the Java API
documentation, which you can find at the URL http://java.sun.com/j2se/1.3/docs/ api/index.html Instead of getting into URLs, I use the getCodeBase() method from the Appletclass, which returns the URL where the applet class file exists That’s all you need to know about the URLclass in this book
The SoundTestAppletapplet loads a sound file and gives you the option of play-ing, loopplay-ing, and stopping the audio clip, by adding those corresponding meth-ods to three buttons ActionListener, this Any time you click one of those buttons, the method associated with that button is called You can therefore see
302
J a
s o
l ut
n e
FIGURE 8.10
The MadLibApplet program can run as
an applet or an application.
Trang 6first hand how the buttons work I load the sound into the AudioClipmember, sound, as follows:
sound = getAudioClip(getCodeBase(), "stooges.au");
The second argument is the file name stooges.auis a Sun audio file I chose this format because Internet Explorer does not support other audio files to be loaded
in this way Appletviewer didn’t have a problem playing other types of sound files Sound file types supported by Java include AU, AIFF, MIDI, and WAV Keep in mind, that when you’re using sounds and images, the applet takes time to load these Users with slow Internet connections can get frustrated waiting for your applet to start running Here is the source code listing for SoundTestApplet.java: /*
* SoundTestApplet
* Tests playing a sound file from an applet
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class SoundTestApplet extends Applet
implements ActionListener { AudioClip sound;
Button playButton, stopButton, loopButton;
public void init() { playButton = new Button("Play");
playButton.addActionListener(this);
add(playButton);
loopButton = new Button("Loop");
loopButton.addActionListener(this);
add(loopButton);
stopButton = new Button("Stop");
stopButton.addActionListener(this);
add(stopButton);
sound = getAudioClip(getCodeBase(), "stooges.au");
} public void actionPerformed(ActionEvent e) {
if (e.getSource() == playButton) { sound.play();
} else if (e.getSource() == loopButton) { sound.loop();
} else if (e.getSource() == stopButton) { sound.stop();
} } }
303
Trang 7Here is the HTML:
<html>
<head>
<title>Sound Test Applet</title>
</head>
<h1 align=center>Sound Test Applet</h1>
<body>
<center>
<applet code="SoundTestApplet.class" width=200 height=100>
</applet>
</center>
</body>
</html>
Figure 8.11 shows what the GUI interface of the SoundTestAppletlooks like
304
J a
s o
l ut
n e
FIGURE 8.11
This applet can play sound files.
Loading and Displaying Images
An applet can also load and display images You will learn all about images in Chapter 9, “The Graphics Class: Drawing Shapes, Images, and Text,” but images are displayed slightly differently in applets so I’ll just show you how to load an image here and in Chapter 9, you can learn more about images as well as other graphics programming You can get an Imageobject by calling the getImage(URL)
or getImage(URL, String) methods, which are similar to the getAudioClip()
methods
/*
* ImageApplet
* Demonstrates displaying an image in an applet and using
* MediaTracker to wait for the images to load
*/
import java.applet.Applet;
import java.awt.*;
Trang 8public class ImageApplet extends Applet { Image img;
public void init() { showStatus("Loading Image ");
MediaTracker mt = new MediaTracker(this);
img = getImage(getCodeBase(), "misty2.jpg");
mt.addImage(img, 0);
//An InterruptedException might occur try {
mt.waitForID(0);
} catch (InterruptedException ie) {}
showStatus("Image Loaded.");
} public void paint(Graphics g) { g.drawImage(img,
(getSize().width - img.getWidth(this)) / 2, (getSize().height - img.getHeight(this)) / 2, this);
} } This example also demonstrates how to wait for an image to load This is done through the use of the MediaTrackerclass found in the java.awtpackage Here,
I use the MediaTrackerclass to wait for the misty2.jpgimage to load I created a new MediaTrackerobject, mt, by passing thisto the constructor The one and only constructor accepts a Componentargument, which specifies the component
on which the image will eventually be drawn (the component that owns the Imageobject)
I then added the image to mtby calling the addImage(Image, int)method The Imageobject passed as the first argument is the one that you want to track and the intargument is the ID number After I added the Imageto the MediaTracker,
I called mt.waitForID(0), which is a method that waits for the image specified
by the int argument (the ID that is passed to addImage(int)) There is also a method for waiting for all images that were added to the MediaTrackerobject to load, waitForAll() Currently, MediaTrackerdoes not support waiting for other file types such as audio files, but that can be added in future releases
This is a listing of the imagetest.htmlsource code:
<html>
<head>
<title>Image Applet</title>
</head>
<body>
<h1 align=center>Image Applet</h1>
305
Trang 9<applet code="ImageApplet.class" width=350 height=250>
</applet>
</center>
</body>
</html>
Figure 8.12 shows ImageAppletdisplaying an image
306
J a
s o
l ut
n e
Back to the QuizShowApplet Applet
All right, now you know a lot about how to create and run applets In this sec-tion, you use this information to build the QuizShowAppletapplet In this applet that you saw at the beginning of this chapter, the users are prompted with a series of true or false questions and get a score at the end based on how many they answered correctly This applet is actually parameter-driven It is versatile in that it accepts parameters that build the whole thing up You can change the parameters at any time to change the questions that are asked, the answers to those questions, and also the number of questions that the QuizShowAppletasks These are the parameters:
nQuestions The number of questions asked by the QuizShowApplet
Qn Each question is specified in its own parameter Qstands for
“Question” and the nrepresents the question number, which must start with 1 and be incremented to the number of ques-tions specified in nQuestionswithout skipping any numbers
key A string of Ts and Fs that indicate the answers to the
ques-tions in order The length of this string must be equal to the number of questions
FIGURE 8.12
This applet displays
an image.
Trang 10Here is the source code for QuizShowApplet.java: /*
* QuizShowApplet
* Asks a series of True and False Questions that
* are passed in as parameters and grades the results
*
* See the getParameterInfo() method for parameter info
*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class QuizShowApplet extends Applet
implements ActionListener { String[] questions;
char[] answers;
int score, nCorrect, currQ;
Label questionLabel, rightWrong;
Checkbox t, f;
CheckboxGroup groupTorF;
Button okButton;
public void init() { boolean paramsOK = false;
try { paramsOK = readParams();
} catch (Exception e) { System.out.println(e); }
if (paramsOK) { setLayout(new BorderLayout());
setBackground(Color.blue);
nCorrect = currQ = 0;
questionLabel = new Label("1 " + questions[0], Label.CENTER);
questionLabel.setFont(new Font("TimesRoman",
Font.BOLD, 16));
questionLabel.setForeground(Color.yellow);
add(questionLabel, BorderLayout.CENTER);
Panel controlPanel = new Panel();
controlPanel.setBackground(SystemColor.control);
groupTorF = new CheckboxGroup();
t = new Checkbox("True", false, groupTorF);
controlPanel.add(t);
f = new Checkbox("False", false, groupTorF);
controlPanel.add(f);
okButton = new Button("That's my final answer!");
okButton.addActionListener(this);
controlPanel.add(okButton);
add(controlPanel, BorderLayout.SOUTH);
rightWrong = new Label("", Label.CENTER);
rightWrong.setForeground(Color.white);
add(rightWrong, BorderLayout.NORTH);
}
307