1. Trang chủ
  2. » Công Nghệ Thông Tin

Java Programming for absolute beginner- P18 ppt

20 275 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 20
Dung lượng 510,12 KB

Nội dung

v.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.java to differentiate it from the original. The first visible change is the fact that I imported the java.applet.Applet package and extended Applet instead of GUIFrame. Instead of extending GUIFrame, I included a GUIFrame member, 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 frame object to the init() method. The reason for using the GUIFrame even when this is run as an applet is because, when you create a Dialog object, you have to pass either a Frame or TRICK 298 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 298 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. another Dialog to 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 Frame or 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 MadLibApplet object, 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 MadLibApplet to 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 C h a p t e r 8 W r i t i n g A p p l e t s JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 299 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. inputChoice.add("Other"); inputChoice.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 v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 300 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. "\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 MadLibApplet applet: <html> <head> <title>Mad Lib</title> </head> <body> <h1>Mad Lib</h1> <applet code="MadLibApplet.class" width=550 height=250></applet> </body> </html> The MadLibApplet is 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 C h a p t e r 8 W r i t i n g A p p l e t s JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 301 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Playing 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. AudioClip is actually an interface in the java.applet package. 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 URL object specifies the location of the audio clip. As you would imagine, it’s just a class in the java.net package 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 Applet class, which returns the URL where the applet class file exists. That’s all you need to know about the URL class in this book. The SoundTestApplet applet loads a sound file and gives you the option of play- ing, looping, 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 v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r FIGURE 8.10 The MadLibApplet program can run as an applet or an application. JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 302 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. first hand how the buttons work. I load the sound into the AudioClip member, sound, as follows: sound = getAudioClip(getCodeBase(), "stooges.au"); The second argument is the file name. stooges.au is 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 C h a p t e r 8 W r i t i n g A p p l e t s JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 303 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Here 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 SoundTestApplet looks like. 304 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r 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 Image object 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.*; JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 304 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. public 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 MediaTracker class found in the java.awt package. Here, I use the MediaTracker class to wait for the misty2.jpg image to load. I created a new MediaTracker object, mt, by passing this to the constructor. The one and only constructor accepts a Component argument, which specifies the component on which the image will eventually be drawn (the component that owns the Image object). I then added the image to mt by calling the addImage(Image, int) method. The Image object passed as the first argument is the one that you want to track and the int argument is the ID number. After I added the Image to 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 MediaTracker object to load, waitForAll(). Currently, MediaTracker does 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.html source code: <html> <head> <title>Image Applet</title> </head> <body> <h1 align=center>Image Applet</h1> 305 C h a p t e r 8 W r i t i n g A p p l e t s JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 305 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. <center> <applet code="ImageApplet.class" width=350 height=250> </applet> </center> </body> </html> Figure 8.12 shows ImageApplet displaying an image. 306 J a v a P r o g r am m i n g f o r t h e A b s o l ut e B e gi n n e r 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 QuizShowApplet applet. 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 QuizShowApplet asks. These are the parameters: nQuestions The number of questions asked by the QuizShowApplet. Qn Each question is specified in its own parameter. Q stands for “Question” and the n represents the question number, which must start with 1 and be incremented to the number of ques- tions specified in nQuestions without 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. JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 306 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Here 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 C h a p t e r 8 W r i t i n g A p p l e t s JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 307 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... itself as the ActionListener for the TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Writing Applets } Chapter 8 questionLabel.setText("Your Score is : " + Math.round( ((double)nCorrect) / questions.length * 100) + "%"); JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 310 Java Programming for the Absolute Beginner 310 okButton...JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 308 Java Programming for the Absolute Beginner 308 else { add(new Label("Parameters not properly set")); } } protected boolean readParams() throws Exception { questions = new String[Integer.parseInt(getParameter("nQuestions"))]; answers = getParameter("key").toCharArray(); if (questions.length != answers.length) return false; for (int i=0; i... g) { g.drawLine(10, 10, 50, 100); g.setColor(Color.blue); TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark The Graphics Class: Drawing Shapes, Images, and Text FIGURE 9.1 JavaProgAbsBeg-09.qxd 2/25/03 8:55 AM Page 316 Java Programming for the Absolute Beginner 316 g.drawLine(60, 110, 275, 50); g.setColor(Color.red); g.drawLine(50,... purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-09.qxd 2/25/03 8:55 AM Page 314 Java Programming for the Absolute Beginner 314 • Render text • Use the FontMetrics class • Display images • Understand the Color class The Project: Memory Game The project for this chapter is the Memory application In this game, a window opens up with 16 cells Initially they are all covered... into the paint(Graphics) method stores the component’s graphics This class has methods for drawing shapes such as lines, rectangles, and ovals, as well as for rendering text and images TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-09.qxd 2/25/03 8:55 AM Page 315 315 Chapter 9 The Memory game in action... so easy for someone to see the answers to your quiz Anyone that can read a text file can probably crack the T and F string code and figure out the answers before taking the quiz This would be better implemented either as some code that only you understand and can interpret in your applet’s class file or better yet, stored in a file on the server that is inaccessible to the users Java Server programming. .. int height) The actual width for a filled rectangle is x + width – 1 and the actual height is y + height – 1 If you were to draw a rectangle TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark The Graphics Class: Drawing Shapes, Images, and Text In the real world, graphics programming is used for many reasons Typically, programmers... the users Java Server programming is a huge subject in its own right and is not covered in this book, but is another great way to use Java TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 311 311 Summary 1 Rewrite the quizshow.html file’s parameters to create a different quiz 2... browsers interpret Java You now know that an applet that runs fine in one browser or the appletviewer, might not run at all in another browser, because it all depends upon the application the applet is embedded in You learned about applet security restrictions You also learned how to load and play sound files and display images In the next chapter, you learn about Java graphics programming in detail... relative to the component’s coordinate system (the top-left corner of the component is point (0, 0)) The LineTest application draws three lines Here is the source code for LineTest .java: /* * LineTest * Demonstrates drawing lines */ import java. awt.*; public class LineTest extends Canvas { public LineTest() { super(); setSize(300, 200); setBackground(Color.white); } public static void main(String args[]) . imagine, it’s just a class in the java. net package that encapsulates a Uniform Resource Loca- tor. It isn’t covered in this book, so for more information, consult the Java API documentation, which. 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. using * MediaTracker to wait for the images to load */ import java. applet.Applet; import java. awt.*; JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 304 TEAM LinG - Live, Informative, Non-cost and Genuine! Please

Ngày đăng: 03/07/2014, 05:20

TỪ KHÓA LIÊN QUAN