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

Ebook Java: An introduction to problem solving & programming (Sixth edition) – Part 1

514 21 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

This book is designed to teach you the Java programming language and, even more importantly, to teach you basic programming techniques. It requires no previous programming experience and no mathematics other than some simple high school algebra. Ebook Java: An introduction to problem solving & programming (Sixth edition) – Part 1 presents the following chapters: Chapter 1 introduction to computers and java, chapter 2 basic computation, chapter 3 flow of control: branching, chapter 4 flow of control: loops, chapter 5 defining classes and methods, chapter 6 more about objects and methods.

LOCATION OF VIDEONOTES IN THE TEXT Chapter Compiling a Java program, p 20 Writing an algorithm, p 25 Recognizing a hidden error, p 28 Another applet example, p 38 Writing an algorithm for Project 5, p 42 Chapter Another sample program, p 61 Writing arithmetic expressions and statements, p 72 Processing strings, p 87 Pitfalls involving nextLine(), p 97 Solving a conversion problem, p 130 Solution to Project 13, p 132 Chapter Using multibranch if-else statements, p 159 Using switch statements, p 177 Solution to Project 2, p 190 Responding to user input, p 190 Chapter Using nested while loops, p 213 Comparing loop statements, p 221 Debugging a loop, p 238 Solution to Project 9, p 252 Nesting for statements, p 253 Chapter Writing and involving methods, p 292 Investigating public and private access, p 300 Objects and references, p 326 Exploring parameters of class types, p 345 Developing a solution to Project 8, p 363 Solution to Project 12, p 366 Chapter Writing construction, p 387 Using static and non-static methods, p 396 Writing and invoking overloaded methods, p 433 Solving a similar problem, p 468 Solution to Project 12, p 469 (Continued on Inside Back Cover) get with the programming Through the power of practice and immediate personalized feedback, MyProgrammingLab improves your performance Learn more at www.myprogramminglab.com This page intentionally left blank ™ An Introduction to Problem Solving & Programming This page intentionally left blank ™ 6th edition An Introduction to Problem Solving & Programming Walter Savitch University of California, San Diego Contributor Kenrick Mock University of Alaska Anchorage Prentice Hall Boston Columbus Indianapolis New York San Francisco Upper Saddle River Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi Mexico City São Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo Editorial Director: Marcia Horton Editor-in-Chief: Michael Hirsch Acquisitions Editor: Matt Goldstein Editorial Assistant: Chelsea Bell Director of Marketing: Patrice Jones Marketing Manager: Yezan Alayan Marketing Coordinator: Kathryn Ferranti Managing Editor: Jeff Holcomb Production Project Manager: Heather McNally Senior Operations Supervisor: Alan Fischer Operations Specialist: Lisa McDowell Art Director: Kristine Carney Text Designer: Jerilyn Bockorick, Nesbitt Graphics, Inc Cover Designer: Rachael Cronin Manager, Rights and Permissions: Michael Joyce Text Permission Coordinator: Jennifer Kennett Cover Art: Aron Jungermann / Getty Images Media Director: Daniel Sandin Media Project Manager: Wanda Rockwell Full-Service Project Management: Rose Kernan, Nesbitt Graphics, Inc Composition: Glyph International Ltd Interior Printer/Bindery: Edwards Brothers Cover Printer: Coral Graphics Credits and acknowledgments borrowed from other sources and reproduced, with permission, in this textbook appear on appropriate page within text Microsoft® and Windows® are registered trademarks of the Microsoft Corporation in the U.S.A and other countries Screen shots and icons reprinted with permission from the Microsoft Corporation This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation Copyright © 2012, 2009, 2005, 2004, 2001 Pearson Education, Inc., publishing as Prentice Hall, Lake Street, Upper Saddle River, New Jersey, 07458 All rights reserved Manufactured in the United States of America This publication is protected by Copyright, and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise To obtain permission(s) to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, Lake Street, Upper Saddle River, New Jersey, 07458 Many of the designations by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed in initial caps or all caps Library of Congress Cataloging-in-Publication Data LIBRARY OF CONGRESS CATALOGING-IN-PUBLICATION DATA ON FILE 10 1—EB—15 14 13 12 11 ISBN 10: 0-132-16270-9 ISBN 13: 978-0-132-16270-8 Preface for Instructors Welcome to the sixth edition of Java: An Introduction to Problem Solving & Programming This book is designed for a first course in programming and computer science It covers programming techniques, as well as the basics of the Java programming language It is suitable for courses as short as one quarter or as long as a full academic year No previous programming experience is required, nor is any mathematics, other than a little high school algebra The book can also be used for a course designed to teach Java to students who have already had another programming course, in which case the first few chapters can be assigned as outside reading Changes in This Edition The following list highlights how this sixth edition differs from the fifth edition: ■ Updates have been made for Java version 7, including strings in switch statements and the use of type inference in generic instance creation ■ Additional case studies including unit testing, use of the Comparable interface, processing comma-separated value files, and others ■ Chapter now begins with a simpler class to more gradually introduce how classes are constructed ■ Chapter has been reorganized with a greater emphasis and more examples on polymorphism and interfaces ■ Chapter describes how to create a Swing application using the JFrame class so thereafter students have the option of implementing graphics in applets or in an application ■ Chapter 12 includes an overview of the Java Collections Framework and examples using the HashMap and HashSet classes ■ A description of System.out.printf has been added to Chapter ■ A description of Math.random has been added to Chapter ■ Twenty new programming projects have been added ■ New VideoNotes added throughout the text to enhance student understanding of programming concepts and techniques vii viii PREFACE FOR INSTRUCTORS Latest Java Coverage All of the code in this book has been tested using a pre-release version of Oracle’s Java SE Development Kit (JDK), version 7.0 Any imported classes are standard and in the Java Class Library that is part of Java No additional classes or specialized libraries are needed Flexibility If you are an instructor, this book adapts to the way you teach, rather than making you adapt to the book It does not tightly prescribe the sequence in which your course must cover topics You can easily change the order in which you teach many chapters and sections The particulars involved in rearranging material are explained in the dependency chart that follows this preface and in more detail in the “Prerequisites” section at the start of each chapter Early Graphics Graphics supplement sections end each of the first ten chapters This gives you the option of covering graphics and GUI programming from the start of your course The graphics supplement sections emphasize applets but also cover GUIs built using the JFrame class Any time after Chapter 8, you can move on to the main chapters on GUI programming (Chapters 13 through 15), which are now on the Web Alternatively, you can continue through Chapter 10 with a mix of graphics and more traditional programming Instructors who prefer to postpone the coverage of graphics can postpone or skip the graphics supplement sections Coverage of Problem-Solving and Programming Techniques This book is designed to teach students basic problem-solving and programming techniques and is not simply a book about Java syntax It contains numerous case studies, programming examples, and programming tips Additionally, many sections explain important problem-solving and programming techniques, such as loop design techniques, debugging techniques, style techniques, abstract data types, and basic object-oriented programming techniques, including UML, event-driven programming, and generic programming using type parameters Early Introduction to Classes Any course that really teaches Java must teach classes early, since everything in Java involves classes A Java program is a class The data type for strings of characters is a class Even the behavior of the equals operator (==) depends on whether it is comparing objects from classes or simpler data items Classes cannot be avoided, except by means of absurdly long and complicated “magic formulas.” This book introduces classes fairly early Some exposure to using classes is given in Chapters and Chapter covers how to define classes All 444 CHAPTER / More About Objects and Methods FIGURE 6.5 A Package Name myjavastuff \myjavastuff\libraries libraries is a class path base directory (is on the class path) general general.utilities is the package name utilities AClass.java Classes in the package AnotherClass.java subdirectories given by the package name For example, suppose the following is a class path base directory (your operating system might use / instead of \): \myjavastuff\libraries and suppose your package classes are in the directory \myjavastuff\libraries\general\utilities In this case, the package must be named general.utilities Setting the class path variable Notice that a package name is not arbitrary, but must be a list of directories leading from a class path base directory to the package classes Thus, the package name tells Java what subdirectories to go through—starting from the base class directory—to find the package classes This organization is depicted in Figure 6.5 The dot in the package name means essentially the same thing as the \ or /, whichever symbol your operating system uses for directory paths You specify the class path base directories by setting the class path (environment) variable The way you set the class path variable depends on ZPVSPQFSBUJOHTZTUFN*GZPVBSFPOB6/*9TZTUFN ZPVBSFMJLFMZUPCFBCMF to set the class path with some command similar to the following: export CLASSPATH=/myjavastuff/libraries:/home/username/ javaclasses; 6.7 Packages 445 RECAP Package Names A package name must be a path name for the directory that contains the classes in the package, but the package name uses dots in place of \ or / (whichever your operating system uses) When naming the package, you use a relative path name that starts from any directory named in the class path (environment) variable EXAMPLES general.utilities java.io If you are using a Windows machine, you can set the class path variable by using the Control Panel to set or create an environment variable named CLASSPATH You can list more than one base directory in a class path variable, typically by separating them with semicolons For example, the following might be a class path: c:\myjavastuff\libraries;f:\yourjavastuff This means that you can create package directories as either subdirectories of c:\myjavastuff\libraries or subdirectories of f:\yourjavastuff When looking for package directories, Java will first look in subdirectories of c:\myjavastuff\libraries If it does not find the package there, it will then look in subdirectories of f:\yourjavastuff Whenever you set or change the class path variable, be sure to include the current directory as one of the alternatives The current directory is the directory in which your program (or other class) is located On most systems, the current directory is indicated by a dot So you would use the following for your class path variable: c:\myjavastuff\libraries;f:\yourjavastuff; with the dot—the current directory—added to the end Then if the package is not found in either of the previous two base directories, Java will look in the subdirectories of the current directory—that is, in subdirectories of your program (or whatever class you are compiling) If you want Java to check the The current directory contains your program 446 CHAPTER / More About Objects and Methods current directory before it checks the other directories on the class path, list the current directory (the dot) first GOTCHA Not Including the Current Directory in Your Class Path Omitting the current directory from the class path variable not only will limit the locations you can use for your packages, but can interfere with programs that not use packages If you not create packages, but instead place all classes in the same directory—as we in the rest of this book—Java will not be able to find the classes unless the current directory is on the class path (This problem will not occur if you have no class path variable at all; it arises only if you decide to set the class path variable.) ■ Name Clashes Avoid name clashes Packages are a convenient way to group and use libraries of classes, but there is also another reason for using packages They can help in dealing with name clashes; that is, they can help in handling situations in which two classes have the same name If different programmers writing different packages have used the same name for a class, the ambiguity can be resolved by using the package name For example, suppose a package named mystuff contains a class called CoolClass, and another package named yourstuff contains a different class named CoolClass You can use both of these classes in the same program by using the more complete names mystuff.CoolClass and yourstuff CoolClass, as the following statements demonstrate: mystuff.CoolClass object1 = new mystuff.CoolClass(); yourstuff.CoolClass object2 = new yourstuff.CoolClass(); If you list the package name along with the class name like this, you not need to import the package, since this longer class name includes the package name S E L F -TE S T QU ESTI ONS 42 Suppose you want to use classes in the package mypackages.library1 in a program you write What you need to put near the start of the file containing your program? 43 Suppose you want to add a class to a package named mypackages library1 What you need to put in the file containing the class definition? Where does this statement go in the file? 44 Can a package have any name you might want, or are there restrictions on what you can use for a package name? Explain any restrictions 45 On your system, place the class Pet (Listing 6.1) into a package so that you can use the class in any Java program by including a suitable import statement without moving Pet to the same directory (folder) as your program 6.8 Graphics Supplement 447 6.8 GRAPHICS SUPPLEMENT Now you see it; now you don’t —COMMON MAGICIAN’S SAYING *OUIJTTFDUJPOXFTIPXZPVIPXUPBEECVUUPOTBOEJDPOTUPBOBQQMFUPS(6* application and how to make components, such as labels, icons, and buttons, change from visible to invisible and back A button is an object in your applet or application that has a button-like appearance and that does something when you click it with your mouse An icon is a small picture ■ PROGRAMMING TIP Code the Appearance and Actions Separately 8IFOEFTJHOJOHBOEDPEJOHBOBQQMFUPS(6*BQQMJDBUJPO POFHPPEUFDIOJRVF is to first program what the program will look like For example, how many buttons will it display, and what is written on each button? After you have the applet looking the way you want, you can then go on to program the action(s) that it will perform, such as what will happen when the user clicks a button In this way, one large task is broken down into two smaller and more manageable tasks We will use this technique to introduce buttons We will first show you how to add buttons to an applet These buttons will not anything when clicked After you learn how to add buttons to an applet, we will go on to show you how to program actions to respond to button clicks ■ Adding Buttons You create a button object in the same way that you create a label object, but you use the class JButton instead of the class JLabel For example, the applet in Listing 6.21 creates a button as follows: JButton sunnyButton = new JButton("Sunny"); The argument to the constructor for the class JButton, in this case "Sunny", is a string that will appear on the button when the button is displayed If you MPPLBUUIFBQQMFUTPVUQVUJO-JTUJOH ZPVXJMMTFFUIBUUIFUXPCVUUPOT are labeled Sunny and Cloudy After you create a button, you add it to the content pane of an applet in the same way that you add a label For example, sunnyButton is added to the Add buttons to content pane of the applet in Listing 6.21 as follows: the content pane Container contentPane = getContentPane(); contentPane.add(sunnyButton); 6OMJLFMBCFMT ZPVDBOBTTPDJBUFBOBDUJPOXJUIBCVUUPOTPUIBUXIFOUIF user clicks the button with a mouse, the applet performs some action If you click 448 CHAPTER / More About Objects and Methods either of the buttons in the applet in Listing 6.21, nothing happens, because we IBWFOUZFUQSPHSBNNFEBDUJPOTGPSUIFN5PEPUIJT XFVTFBEJGGFSFOULJOEPG programming technique known as event-driven programming We will briefly introduce this technique before we show you how to program button actions LISTING 6.21 Adding Buttons to an Applet import javax.swing.JApplet; import javax.swing.JButton; import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import java.awt.Graphics; /** Simple demonstration of adding buttons to an applet These buttons not anything That comes in a later version */ public class PreliminaryButtonDemo extends JApplet { public void init() { Container contentPane = getContentPene(); contentPane.setBackground(Color.WHITE); contentPane.setLayout(new FlowLayout()); JButton sunnyButton = new JButton("Sunny"); contentPane.add(sunnyButton); JButton cloudyButton = new JButton("Cloudy"); contentPane.add(cloudyButton); } } Applet Output If the user clicks either of these buttons, nothing happens 6.8 Graphics Supplement 449 Event-Driven Programming "QQMFUTBOE(6*BQQMJDBUJPOTVTFFWFOUTBOEFWFOUIBOEMFST"Oevent is an Fire an event object that represents some user action that elicits a response, such as clicking a button with the mouse When an object generates an event, it is said to fire the event For example, when the user clicks a button, the button fires an event In an applet or application, every object that can fire events can have one or more listener objects that receive events automatically A listener Listeners handle object has methods that specify what will happen when the listener receives events events of various kinds These methods are called event handlers You the programmer specify what objects are the listener objects for any given object that might fire an event You also define the event-handler methods The relationship between an event-firing object, such as a button, and its event-handling listener is illustrated in Figure 6.6 Event-driven programming is very different from the kind of programming ZPVWF TFFO CFGPSF OPX *O FWFOUESJWFO QSPHSBNNJOH  ZPV DSFBUF PCKFDUT that can fire events, and you create listener objects to react to the events For the most part, your program does not determine the order in which things happen The events determine that order When an event-driven program is running, the next thing that happens depends on the next event Programming Buttons To review, clicking a button using your mouse creates an object known as an event and sends the event to one or more other objects known as the listeners This is called firing the event The listener then performs some action When we say that the event is “sent” to the listener object, what we really mean is that some method in the listener object is invoked and given the event object as the argument This invocation happens automatically Your applet class definition will not normally contain an invocation of this method However, your applet class definition does need to two things: FIGURE 6.6 button Event Firing and an Event Listener event This event object is the result of a button click The event object goes from the button to the listener listener This listener object performs some action, such as making text visible in the applet, when it receives the event object 450 CHAPTER / More About Objects and Methods • For each button, it needs to specify what objects are listeners that will respond to events fired by that button; this is called registering the listener • It must define the method(s) that will be invoked when the event is sent to the listener Register the listener by calling addAction Listener Recall that within the definition of a class, an object of that class is called this The following statement registers this as a listener to receive events from the button named sunnyButton: sunnyButton.addActionListener(this); Steps to register a listener A similar statement also registers this as a listener to receive events from the button named cloudyButton Because the argument is this, the statements mean that the class itself is the listener class for the buttons inside of it To be a bit more precise, if ButtonDemo is our applet class, each applet object of ButtonDemo is the listener for the buttons in that object This is diagrammed in Figure 6.7 Next we explain how to make a class, such as ButtonDemo, into a listener class for events fired by buttons Different kinds of components require different kinds of listener classes to handle the events they fire A button fires events known as action events, which are handled by listeners known as action listeners An action listener is an object of type ActionListener ActionListener is not a class but is a property that you can give to any class you define Properties such as ActionListener are known as interfaces and are discussed in more detail in Chapter To make a class into an action listener, we need to two things: • Add the phrase implementsActionListener to the beginning of the class definition, normally at the end of the first line • Define a method named actionPerformed FIGURE 6.7 Buttons and an Action Listener sunnyButton e These buttons fire action events, named e in our code An applet of the class ButtonDemo is the listener for both of its buttons applet e cloudyButton When action event e is fired, the applet executes this.actionPerformed(e); 6.8 Graphics Supplement 451 Here is an outline of the definition of the class ButtonDemo: public class ButtonDemo extends JApplet implements ActionListener { public void actionPerformed(ActionEvent e) { } } Although we could have defined a separate class that did nothing but handle button events, we instead made the applet class ButtonDemo into the action listener that will handle button events, because button events are supposed to change the applet, and the easiest way to change an applet is by using a method within the applet itself If the user clicks one of the buttons inside the applet, using the mouse, an action event is sent to the action listener for that button Because the applet itself is the action listener for the buttons, the action event goes to the applet object When an action listener receives an action event, the event is automatically passed to the method actionPerformed The method actionPerformed typically contains a branching statement that asks what kind of action event was fired and then performs some appropriate action The method actionPerformed for our applet class ButtonDemo is public void actionPerformed(ActionEvent e) { Container contentPane = getContentPane(); if (e.getActionCommand().equals("Sunny")) contentPane.setBackground(Color.BLUE); else if (e.getActionCommand().equals("Cloudy")) contentPane.setBackground(Color.GRAY); else System.out.println("Error in button interface."); } In this case, the method actionPerformed needs to know whether the action event came from the button labeled Sunny or the button labeled Cloudy If e is an action event that was fired by clicking a button, e.getActionCommand() returns the string written on the button; in this case it returns either "Sunny" or "Cloudy" This string is known as the action command (You can specify a different action command, but we postpone that detail until Chapter 13, XIJDIJTBWBJMBCMFPOUIFCPPLT8FCTJUF All the method actionPerformed needs to is see whether the action command returned by e.getActionCommand() is the string "Sunny" or getAction Command returns an action command 452 CHAPTER / More About Objects and Methods the string "Cloudy" and perform the appropriate action for that button Since e.getActionCommand() returns an object of the class String, we use String's method equals to make this test, using a method invocation of the following form: e.getActionCommand().equals(String_Argument) 6TJOHUIJTJOWPDBUJPOJOBO if statement allows us to change the color of the content pane accordingly by using a statement like contentPane.setBackground(Color.BLUE); %FGJOJOH BO BDUJPO MJTUFOFS DMBTT SFRVJSFT UIF GPMMPXJOH BEEJUJPOBM JNQPSU statements: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; RECAP Action Events and Action Listeners Buttons and certain other components fire events as objects of the class ActionEvent These events are action events and are handled by one or more action listeners Any class—including an applet class—can become an action listener by taking the following steps: t "EEUIFQISBTFimplements ActionListener to the end of the heading of the class definition t BLFUIFCVUUPOPSPUIFSDPNQPOFOUUIBUXJMMGJSFUIFBDUJPOFWFOUSFHJTUFS the action listener by invoking the method addActionListener and passing it an object of the ActionListener class as an argument t "EEBEFGJOJUJPOGPSBNFUIPEOBNFEactionPerformed to the class An action listener may serve some other purpose in addition to being an action listener EXAMPLE See Listing 6.22 RECAP The Method actionPerformed To be an action listener, a class must—among other things—have a method named actionPerformed that has one parameter of type ActionEvent This is the only method required by the ActionListener interface (continued) 6.8 Graphics Supplement SYNTAX public void actionPerformed(ActionEvent e) { Code_for_Actions_Performed } The Code_for_Actions_Performed is typically a branching statement that depends on some property of the argument e Often the branching depends on the invocation e.getActionCommand(), which returns an action command If e is an event fired by clicking a button, the action command returned is the string written on the button EXAMPLE See Listing 6.22 PROGRAMMING EXAMPLE A Complete Applet with Buttons Listing 6.22 contains an applet that starts out looking just like the applet in Listing 6.21, but in this version the buttons “work.” If you click the button labeled Sunny, the background turns blue If you click the button labeled Cloudy, the background turns gray Note that the final else clause should never execute We wrote it to provide a warning if we made some unnoticed mistake in the code LISTING 6.22 Adding Actions to the Buttons (part of 3) import javax.swing.JApplet; The code for this applet adds the import javax.swing.JButton; highlighted text to Listing 6.21 import java.awt.Color; import java.awt.Container; import java.awt.FlowLayout; import java.awt.Graphics; Use of ActionEvent and import java.awt.event.ActionEvent; ActionListener requires import java.awt.event.ActionListener; these import statements /** Simple demonstration of adding buttons to an applet These buttons something when clicked */ (continued) 453 454 CHAPTER / More About Objects and Methods LISTING 6.22 Adding Actions to the Buttons (part of 3) public class ButtonDemo extends JApplet implements ActionListener { public void init() { Container contentPane = getContentPane(); contentPane.setBackground(Color.WHITE); contentPane.setLayout(new FlowLayout()); JButton sunnyButton = new JButton("Sunny"); contentPane.add(sunnyButton); sunnyButton.addActionListener(this); JButton cloudyButton = new JButton("Cloudy"); contentPane.add(cloudyButton); cloudyButton.addActionListener(this); } public void actionPerformed(ActionEvent e) { Container contentPane = getContentPane(); if (e.getActionCommand().equals("Sunny")) contentPane.setBackground(Color.BLUE); else if (e.getActionCommand().equals("Cloudy")) contentPane.setBackground(Color.GRAY); else System.out.println("Error in button interface."); } } (continued) 6.8 Graphics Supplement LISTING 6.22 Adding Actions to the Buttons (part of 3) ■ PROGRAMMING TIP Applets Do Not Use Constructors Applets are atypical classes in that they normally have no constructors The JOJUJBMJ[BUJPOBDUJPOTUIBUZPVNJHIUFYQFDUUPQVUJOBOBQQMFUTDPOTUSVDUPS ■ are instead placed in the special method init S E L F-TE S T QU E S TIO N S 46 The method actionPeformed in Listing 6.22 contains the following line: Container contentPane = getContentPane(); %PFT UIF DPOUFOU QBOF IBWF UP CF OBNFE contentPane, or could it be named something else, as in the following: Container insideOfApplet = getContentPane(); 455 456 CHAPTER / More About Objects and Methods 47 What does it mean when we say that an event is “sent” to a listener object? 48 In Listing 6.22, suppose we replaced the parameter e in the method actionPerformed with the identifier buttonEvent What effect would this change have on the program? Adding Icons Use ImageIcon to convert a picture file to an icon As we mentioned at the beginning of this section, an icon is simply a picture The picture usually is small, although it is not actually required to be The picture you use can be of anything Pictures are produced in a number of formats—such as GIF and JPEG—that can be displayed on a computer screen You can use a picture in almost any standard format as the basis for an icon You store the picture files in the same folder (directory) as your program Swing converts a digital picture file into an icon, and you can then add the icon to a label, button, or other component You can display an icon, a string, or both an icon and a string on any label or button The class ImageIcon in the Swing library is used to convert a digital picture file into a Swing icon For example, the following statement converts the digital picture file named duke_waving.gif to an icon named dukeIcon: ImageIcon dukeIcon = new ImageIcon("duke_waving.gif"); Add an icon to a label You can add this icon to a label by using the method setIcon, as follows: niceLabel.setIcon(dukeIcon); Listing 6.23 contains a simple example of these steps The label niceLabel also has the string "Java is fun!", so in this case the label displays both a string and an icon LISTING 6.23 An Applet with an Icon Picture (part of 2) import javax.swing.ImageIcon; import javax.swing.JApplet; import javax.swing.JLabel; public class IconDemo extends JApplet { public void init() { JLabel niceLabel = new JLabel("Java Is fun!"); ImageIcon dukeIcon = new ImageIcon("duke_waving.gif"); niceLabel.setIcon(dukeIcon); getContentPane().add(niceLabel); } } (continued) 6.8 Graphics Supplement 457 LISTING 6.23 An Applet with an Icon Picture (part of 2) Applet Output4 To omit the string from the label, you could change the definition of niceLabel in Listing 6.23 to the following: JLabel niceLabel = new JLabel();//No argument, so no string As a result, the sentence Java is fun! would not appear in the applet You can also use the method setIcon to add an icon to a button For example, if you add the highlighted statements in the following code to Listing 6.22, the button with the text Sunny will also display the picture in the file smiley.gif: Add an icon to a button JButton sunnyButton = new JButton("Sunny"); ImageIcon smileyFaceIcon = new ImageIcon("smiley.gif"); sunnyButton.setIcon(smileyFaceIcon); contentPane.add(sunnyButton); sunnyButton.addActionListener(this); The screen output would appear as shown in Figure 6.8 The complete applet code is in the file ButtonIconDemo.java included with the source code for this book that is available on the Web S E L F-TE S T QU E S TIO N 49 The previous section showed you how to change the code in the applet in Listing 6.22 so that the button labeled Sunny contained the picture smiley.gif as well as text, as shown in Figure 6.8 Make additional  +BWB  %VLF  BOE BMM +BWBCBTFE USBEFNBSLT BOE MPHPT BSF USBEFNBSLT PS SFHJTUFSFE USBEFNBSLTPG0SBDMF *ODJOUIF6OJUFE4UBUFTBOEPUIFSDPVOUSJFT %VLFJTUIFGJHVSF waving.) Extra code on the Web 458 CHAPTER / More About Objects and Methods FIGURE 6.8 A Button Containing an Icon The code for this applet is in the file ButtonIconDemo.java in the source code on the Web changes to the code so that the button labeled Cloudy contains the picture nasty.gif as well as text (The file nasty.gif is included with the source code provided on the Web.) Changing Visibility An invisible button is inoperable Every label and just about every button and other component we will introduce later has a method named setVisible This method can change a component from visible to invisible or from invisible to visible according to the boolean value passed to it as an argument If a label or other component invokes the method setVisible and gives it an argument of true, the component will become visible On the other hand, an argument of false makes the component invisible If setVisible is not invoked at all, the component will be visible by default When a component, such as a button, is invisible, you cannot click it with your mouse to get an action An “invisible” component is not just invisible; it is not there at all The next programming example demonstrates the use of the setVisible method PROGRAMMING EXAMPLE An Example of Changing Visibility The applet in Listing 6.24 defines a label that is initially invisible When the user clicks the button in the applet, the label becomes visible The label is named response and is made invisible by the following invocation of setVisible within the method init: response.setVisible(false); ... FIGURE 1. 1 Main Memory Bytes Byte addresses 30 21 111 10000 3022 11 0 011 00 3023 10 1 010 10 3024 11 0 011 10 3025 0 011 00 01 3026 11 1000 01 3027 011 00 011 3028 10 100 010 3029 011 111 11 3030 10 0000 01 30 31 1 011 110 0... DATA ON FILE 10 1? ??EB? ?15 14 13 12 11 ISBN 10 : 0 -13 2 -16 270-9 ISBN 13 : 978-0 -13 2 -16 270-8 Preface for Instructors Welcome to the sixth edition of Java: An Introduction to Problem Solving & Programming. .. ‰$)"3 -&4 4"/ %&3 4 1& * 3 $& (18 3 9? ?1 914 ) INTRODUCTION This chapter gives you a brief overview of computer hardware and software Much of this introductory material applies to programming in any language,

Ngày đăng: 09/01/2023, 02:56

Xem thêm:

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN