Java Programming for absolute beginner- P1

Chia sẻ: Cong Thanh | Ngày: | Loại File: PDF | Số trang:20

0
51
lượt xem
9
download

Java Programming for absolute beginner- P1

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Java Programming for absolute beginner- P1:Hello and welcome to Java Programming for the Absolute Beginner. You probably already have a good understanding of how to use your computer. These days it’s hard to find someone who doesn’t, given the importance of computers in today’s world. Learning to control your computer intimately is what will separate you from the pack! By reading this book, you learn how to accomplish just that through the magic of programming.

Chủ đề:
Lưu

Nội dung Text: Java Programming for absolute beginner- P1

  1. Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  2. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page i Java ® Programming TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  3. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page ii Check the Web for Updates To check for updates or corrections relevant to this book and/or CD-ROM visit our updates page on the Web at http://www.prima-tech.com/support. Send Us Your Comments To comment on this book or any other PRIMA TECH title, visit our reader response page on the Web at http://www.prima-tech.com/comments. How to Order For information on quantity discounts, contact the publisher: Prima Publish- ing, P.O. Box 1260BK, Rocklin, CA 95677-1260; (916) 787-7000. On your letter- head, include information concerning the intended use of the books and the number of books you want to purchase. For individual orders, turn to the back of this book for more information. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  4. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page iii Java ® Programming Joseph P. Russell TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  5. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page iv © 2001 by Prima Publishing. All rights reserved. No part of Publisher: this book may be reproduced or transmitted in any form or Stacy L. Hiquet by any means, electronic or mechanical, including photo- copying, recording, or by any information storage or Managing Editor: retrieval system without written permission from Prima Sandy Doell Publishing, except for the inclusion of brief quotations in a Acquisitions Editor: review. Melody Layne A Division of Prima Publishing Project Editor: Prima Publishing and colophon are registered Kezia Endsley trademarks of Prima Communications, Inc. Technical Reviewer: PRIMA TECH is a trademark of Prima Communi- Michelle Jones cations, Inc., Roseville, California 95661. Copy Editor: Java, Forte, NetBeans and all trademarks and logos based on Kezia Endsley Java, Forte and NetBeans are trademarks or registered trade- marks of Sun Microsystems, Inc. in the U.S. and other coun- Associate Marketing tries. Internet Explorer is a registered trademark of Microsoft Manager: Corporation in the United States and/or other countries. Heather Buzzingham Netscape is a registered trademark of Netscape Communica- tions Corporation in the U.S. and other countries. Interior Layout: William Hartman Important: Prima Publishing cannot provide software sup- port. Please contact the appropriate software manufacturer’s Cover Design: technical support line or Web site for assistance. Prima Design Team Prima Publishing and the author have attempted through- Indexer: out this book to distinguish proprietary trademarks from Sharon Shock descriptive terms by following the capitalization style used Proofreader: by the manufacturer. Jenny Davidson Information contained in this book has been obtained by Prima Publishing from sources believed to be reliable. How- ever, because of the possibility of human or mechanical error by our sources, Prima Publishing, or others, the Publisher does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any errors or omissions or the results obtained from use of such informa- tion. Readers should be particularly aware of the fact that the Internet is an ever-changing entity. Some facts may have changed since this book went to press. ISBN: 0-7615-3522-5 Library of Congress Catalog Card Number: 2001-091380 Printed in the United States of America 00 01 02 03 04 BB 10 9 8 7 6 5 4 3 2 1 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  6. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page v This book is dedicated to Brianne, Tyler, and to the rest of my family, past, present, and future. You all make life on this great big ball of dung worth living. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  7. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page vi Acknowledgments I would like to thank my parents, Joe and Joan, for cheering me on and helping me out with Brianne and Tyler while I was working on this book. Thanks also to Brianne and Tyler for keeping me happy while I wasn’t. Thanks also to my sister Roseanne, for putting me on the right career path. I love all of you. I’d also like to thank Kezia Endsley for doing a great editing job and rewording my babble so that it actually makes sense. Thanks to Melody Layne for finding me and bringing me in to work in this pro- ject. Thanks also to Michelle Jones, Jenny Davidson, and everyone else that was a part of this project. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  8. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page vii About the Author J oseph P. Russell is a development programmer for Meditech, a major medical information systems software and service company, developing software for their client/server financial products. He is a Sun certified programmer for the Java 2 platform. He is also a contributing writer for eastcoastgames.com (http://www.eastcoastgames.com). He is a graduate from Rhode Island College where he majored in computer science. He also worked as a Web developer for their Web site (http://www.ric.edu). It was during his college years that he acquired a passion for Web development and decided to learn Java and JavaScript. After graduating, he worked as a Web developer/programmer for Progressive Systems Technology, a company that provides Progress database con- sulting and develops applications for commercial Internet based companies. In his spare time, he enjoys game programming, painting, and playing his elec- tric bass guitar. He is a father of two beautiful children, a girl and a boy, and he loves being a family man. You can visit his home page at http://members. home.net/j.p.russell or e-mail him at j.p.russell@home.com. TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  9. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page viii This page intentionally left blank TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  10. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page ix Contents at a Glance Introduction xix CHAPTER 1 Getting Started 1 CHAPTER 2 Variables, Data Types, and Simple I/O 25 CHAPTER 3 The Fortune Teller: Random Numbers, Conditionals, and Arrays 55 CHAPTER 4 Using Loops and Exception Handling 93 CHAPTER 5 Blackjack: Object-Oriented Programming 121 CHAPTER 6 Creating a GUI Using the Abstract Windowing Toolkit 171 CHAPTER 7 Advanced GUI: Layout Managers and Event Handling 221 CHAPTER 8 Writing Applets 277 CHAPTER 9 The Graphics Class: Drawing Shapes, Images, and Text 313 CHAPTER 10 Animation, Sounds, and Threads 353 CHAPTER 11 Custom Event Handling and File I/O 377 CHAPTER 12 Creating Your Own Components and Packages 429 APPENDIX A Using the CD-ROM 477 APPENDIX B Java Language Summary 481 Index 491 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  11. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page x Contents Introduction xix 1 C H A P T E R Getting Started 1 The Project: the HelloWeb Applet 2 What Is Java? 3 Java Is a Programming Language 4 Java Is Platform Independent 4 Java Is Object-Oriented 5 Why Learn Java? 7 Java Is Relatively Easy to Learn 7 Java Works Everywhere 7 Installing and Setting Up the Java SDK 8 Windows (Win32) Installation and Setup 8 Solaris Installation 10 Linux Installation 10 Writing Your First Application 11 Hello, World! 12 Compiling the Program 12 Running the Application 14 Learning Java Syntax Basics 15 Including Comments 17 The main() Method 19 Writing Your First Applet 20 Back to the HelloWeb Applet! 20 Writing the HTML 21 Running the Applet 21 Summary 23 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  12. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xi xi 2 Variables, Data Types, and C H A P T E R Simple I/O 25 Table of Contents The Project: the NameGame Application 26 Variables and Data Types 26 Learning Primitive Data Types 27 Understanding Literals 28 Using Character Escape Codes 29 Naming Variables 31 Declaring and Assigning Values to Variables 31 Working with Numbers 34 The TipAdder Program 34 Operator Precedence 37 Getting Simple User Input 38 Using the BufferedReader Class 40 Handling the Exceptions 41 The Math Game 43 Parsing Strings to Numbers 44 The TipCalculator Application 45 Accepting Command-Line Arguments 46 Strings and String Operations 48 The String Class 48 String Methods 49 Getting Back to the Name Game 49 Summary 53 3 The Fortune Teller: Random C H A P T E R Numbers, Conditionals, and Arrays 55 The Project: the Fortune Teller 56 Generating Random Numbers 57 The NumberMaker Application 57 The java.util.Random Class 58 The Math Class 62 Controlling the Random Number Range 64 Getting Values Larger Than 1 65 Specifying a Range 65 The Dice Roller 65 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  13. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xii xii The if Statement 67 Conditions and Conditional Operators 68 Table of Contents Using Boolean Logical Operators 71 The LowTemp Program 73 The if-else Statement 74 The HighOrLowTemp Program 77 Nesting if-else Structures 78 The ManyTemps Program 79 Indentation and Syntax Conventions 80 Using the switch Statement 81 The FuzzyDice Program 83 Understanding Arrays 85 Declaring an Array 85 Assigning Values to and Accessing Array Elements 86 Multidimensional Arrays 88 The ArrayTest Program 88 Back to the Fortune Teller 90 Summary 91 4 Using Loops and Exception C H A P T E R Handling 93 The Project: The NumberGuesser 94 Counting Forward with Loops 94 The Racer Program 95 The for Loop 96 The Increment (++) Operator 97 Skipping Values 98 The CountByFive Program 99 Using Compound Assignment Operators 100 Counting Backwards 101 Making a for Loop Count Backwards 102 Nested for Loops 103 Looping on Arrays 105 Looping on Multidimensional Arrays 106 The MultiplicationArray Program 106 Using the while Loop 108 The do-while Loop 109 Preventing Endless Loops 112 The break and continue Statements 112 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  14. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xiii xiii Exception Handling 116 Using the try-catch-finally Block 116 Table of Contents Using Exceptions to Screen User Input 117 Back to the NumberGuesser Program 118 Summary 120 5 Blackjack: Object-Oriented C H A P T E R Programming 121 The Project: the BlackJack Application 122 Understanding Object-Oriented Concepts 123 The SimpleCardDeck Class 123 Learning About Objects 124 Examining Member Variables 127 Field Modifiers 129 Defining and Using Methods 132 The Automobile Class 133 Declaring a Method 136 Passing Parameters 136 Method Overloading 138 Returning Values 139 Understanding Static Methods 140 Defining Constructor Methods 141 Learning another Keyword: this 143 Understanding Access Modifiers 144 Field and Method Access Modifiers 144 Encapsulation 146 The Card and CardDeck Classes 148 Writing the Card Class 148 Writing the CardDeck Class 151 Extending a Class 154 The BigTruck Class 154 Overriding Methods 157 Polymorphism 158 Back to the BlackJack Game 158 The RandomCardDeck Class 158 The Vector Class 160 The BlackJack Program 163 The play() Method: BlackJack Driver 167 Other BlackJack Methods 168 Summary 169 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  15. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xiv xiv 6 Creating a GUI Using the C H A P T E R Abstract Windowing Toolkit 171 Table of Contents The Project: MadLib Program 172 The java.awt Package 172 Components 173 Events 177 Graphics 177 Using Frames 178 The UselessFrame Application 178 Learning about Containers 180 Using the WindowListener Interface 180 Using Components 182 The Label Component 183 The Button Component 185 The TextField Component 187 The TextArea Component 191 The Choice Component 193 The List Component 195 The Checkbox Component 198 Using the CheckboxGroup Class 200 The Canvas Component 202 The Menu Component 203 The PopupMenu Component 207 The Panel Component 208 The Scrollbar Component 209 The Dialog Component 212 Back to the MadLib Game Application 214 Creating the MadDialog Component 214 Telling the Story: Creating the MadLib Game Frame 218 Summary 219 7 Advanced GUI: Layout C H A P T E R Managers and Event Handling 221 The Project: the AdvancedMadLib Application 222 Using Layout Managers 223 Using FlowLayout 223 Using GridLayout 225 Using BorderLayout 228 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  16. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xv xv Using GridBagLayout 229 Creating the GUIFrame Class 237 Table of Contents Using CardLayout 238 Handling AWT Events 242 Handling WindowEvents 242 Using Inner Adapter Classes 246 Handling ActionEvents 247 Knowing the Source of an Event 248 More ActionEvent Handling 252 Handling Focus Events 254 Handling ItemEvents 256 Handling AdjustmentEvents 259 Handling TextEvents 260 Handling MouseEvents 262 Handling KeyEvents 265 Getting Back to the AdvancedMadLib Application 268 Creating the MadInputPanel Class 269 Creating the AdvancedMadLib Application 272 Summary 275 8 Writing Applets 277 C H A P T E R The Project: QuizShow Applet 278 Understanding Applets 279 Knowing the Difference between Applets and Applications 279 How Do Applets Work? 280 Hello Again! 280 The Applet Class 282 Including an Applet in a Web Page 283 The HTML Tag 284 Passing Parameters to Applets 284 Using Frames with Applets 288 Security Restrictions 290 Learning Applet Methods: init(), start(), stop(), and destroy() 291 Printing Status Messages 293 Writing Java Programs that Can Run as Applets or Applications 294 Rewriting MadInputPanel 295 Rewriting the MadLib Game 298 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  17. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xvi xvi Using Sounds and Images 301 Playing Sound Files 302 Table of Contents Loading and Displaying Images 304 Back to the QuizShowApplet Applet 306 Summary 311 9 The Graphics Class: Drawing C H A P T E R Shapes, Images, and Text 313 The Project: Memory Game 314 The Graphics Class 314 Drawing Lines 315 Drawing Rectangles 317 Drawing 3D Rectangles 319 Drawing Ovals 321 Drawing Arcs 322 Drawing Polygons 323 Drawing Strings 326 Fonts and FontMetrics 327 The Font Class 327 The FontMetrics Class 328 Drawing Images 333 Using the Color Class 337 Color Values 340 Getting Back to the Memory Game 344 Creating the MemoryCell Class 344 Creating the Memory Class 348 Summary 351 10 Animation, Sounds, and C H A P T E R Threads 353 The Project: ShootingRange Game 354 Threading 354 Extending the Thread Class 356 Implementing the Runnable Interface 358 Problems Associated with Multithreading 359 Writing Thread-Safe Code 360 Using wait(), notify(), and notifyAll() 361 Putting a Thread to Sleep 362 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  18. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xvii xvii Performing Animation 363 The Sprite Class 363 Table of Contents Testing the Sprite Class 365 Double Buffering 367 Playing Sound from Applications 369 Back to the ShootingRange Game 370 Summary 376 11 Custom Event Handling and C H A P T E R File I/O 377 The Project: The Block Game 378 Building the Block Class 378 Representing the Block’s Area and Shape 379 Including Useful Block Methods 380 Creating the BlockGrid Class 384 Representing the Block’s Area 385 BlockGrid Methods 386 Painting the Picture 389 Building the PlayArea Event Model 395 Building Your Own Event Model 395 The PlayAreaEvent Class 397 The PlayAreaListener Interface 397 Registering PlayAreaListeners 398 Firing PlayAreaEvents 398 Creating the PlayArea Class 399 Inner Classes 399 Accepting User Input for Block Movements 401 Making Blocks Fall 404 The EventThread Inner Class 407 Putting it All Together 409 Creating the ScoreInfoPanel Class 415 Reading and Writing Files 416 Keeping Score 418 Creating the Block Game Application 423 Summary 427 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  19. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xviii xviii 12 Creating Your Own C H A P T E R Components and Packages 429 Table of Contents The Project: MinePatrol 430 Creating Lightweight Components 431 The Swing Package 431 Creating Your Own Lightweight Components 432 Preparing to Create the jpr.lightweight Package 434 Declaring Packages 434 Abstract Classes 435 The javadoc Utility 436 Creating the jpr.lightweight Package 438 Creating the JPRComponent3D Class 438 Creating the JPRRectComponent3D Class 444 Creating the JPRButton3D Class 448 Generating the Documentation for jpr.lightweight 451 Testing the JPRButton3D Class 453 Building the MineCell Classes 455 The MineCellEvent Class 455 The MineCellListener Interface 456 The MineCell Class 456 Testing the MineCell Class 462 Creating the Mine Field Classes 464 The MineFieldEvent Class 464 The MineFieldListener Interface 465 The MineField Class 465 Creating the MinePatrol Application 474 Summary 476 A Using the CD-ROM 477 APPENDIX B Java Language Summary 481 APPENDIX Index 491 TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
  20. JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xix Introduction H ello and welcome to Java Programming for the Absolute Beginner. You prob- ably already have a good understanding of how to use your computer. These days it’s hard to find someone who doesn’t, given the importance of computers in today’s world. Learning to control your computer inti- mately is what will separate you from the pack! By reading this book, you learn how to accomplish just that through the magic of programming. There is a world of difference between using a computer and controlling its oper- ations. When I was a kid, I didn’t merely play with my toys. I found more enjoy- ment in taking them apart to see how they worked from the inside out. Similarly, when I started playing computer games in elementary school, I wasn’t happy with just playing them. Sure, the games were fun, but I wanted to see how they worked. I found the source code to one of the games we were allowed to play in the school library, so I changed a few things. Needless to say, the game no longer worked and I was banned from using the computer, but my interest in programming was sparked that very day. This book thoroughly covers basic programming concepts using the Java pro- gramming language. You apply these concepts through programming games that are not only challenging and rewarding to create, but are fun to play! In addition, you can apply your knowledge to change the game programs to work the way you want them to, just as I did when I started programming. Even better than that, you can program your own games from the ground up. Java has infinitely more uses in the real world than game development. The pur- pose of this book is not to teach game development. I use game programs as fun examples that demonstrate programming concepts that you can apply to any kind of Java programming solution. Many companies use Java because of its platform independence. Another use of Java is to create applets for Internet solutions. Internet companies, such as online stores, can use Java to create user interfaces that online shoppers can use to pur- chase their goods. They can also use server-side Java programs to keep their data- bases up to date as their products are being purchased. Knowledge of Java is a TEAM LinG - Live, Informative, Non-cost and Genuine! Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Đồng bộ tài khoản