Introduction xixCHAPTER 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
Trang 2Programming
®
Trang 3Check 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
Trang 4Programming
®
Trang 5© 2001 by Prima Publishing All rights reserved No part of this book may be reproduced or transmitted in any form or
by any means, electronic or mechanical, including photo-copying, recording, or by any information storage or retrieval system without written permission from Prima Publishing, except for the inclusion of brief quotations in a review.
A Division of Prima Publishing Prima Publishing and colophon are registered trademarks of Prima Communications, Inc.
PRIMA TECH is a trademark of Prima Communi-cations, Inc., Roseville, California 95661.
Java, Forte, NetBeans and all trademarks and logos based on Java, Forte and NetBeans are trademarks or registered trade-marks of Sun Microsystems, Inc in the U.S and other coun-tries Internet Explorer is a registered trademark of Microsoft Corporation in the United States and/or other countries.
Netscape is a registered trademark of Netscape Communica-tions Corporation in the U.S and other countries.
Important: Prima Publishing cannot provide software
sup-port Please contact the appropriate software manufacturer’s technical support line or Web site for assistance.
Prima Publishing and the author have attempted through-out this book to distinguish proprietary trademarks from descriptive terms by following the capitalization style used
by the manufacturer.
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
Publisher:
Stacy L Hiquet
Managing Editor:
Sandy Doell
Acquisitions Editor:
Melody Layne
Project Editor:
Kezia Endsley
Technical Reviewer:
Michelle Jones
Copy Editor:
Kezia Endsley
Associate Marketing Manager:
Heather Buzzingham
Interior Layout:
William Hartman
Cover Design:
Prima Design Team
Indexer:
Sharon Shock
Proofreader:
Jenny Davidson
Trang 6This 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.
Trang 7would 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
Acknowledgments
I
Trang 8oseph 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.
About the Author
J
Trang 9This page intentionally left blank
Trang 10Introduction xix
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
CHAPTER 9 The Graphics Class: Drawing Shapes, Images,
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
Contents at a
Glance
Trang 11Introduction xix
The Project: the HelloWeb Applet 2
Java Is a Programming Language 4 Java Is Platform Independent 4
Java Is Relatively Easy to Learn 7
Installing and Setting Up the Java SDK 8 Windows (Win32) Installation and Setup 8
Writing Your First Application 11
Back to the HelloWeb Applet! 20
Summary 23
Contents
1
C H A P T E R
Trang 12Variables, Data Types, and
The Project: the NameGame Application 26
Learning Primitive Data Types 27
Using Character Escape Codes 29
Declaring and Assigning Values to Variables 31
Using the BufferedReader Class 40
Parsing Strings to Numbers 44 The TipCalculator Application 45 Accepting Command-Line Arguments 46 Strings and String Operations 48
Getting Back to the Name Game 49 Summary 53
The Fortune Teller: Random Numbers, Conditionals, and
The Project: the Fortune Teller 56
The NumberMaker Application 57 The java.util.Random Class 58
Controlling the Random Number Range 64 Getting Values Larger Than 1 65
xi
2
C H A P T E R
3
C H A P T E R
Trang 13The if Statement 67 Conditions and Conditional Operators 68 Using Boolean Logical Operators 71
Nesting if-else Structures 78
Indentation and Syntax Conventions 80
Assigning Values to and Accessing Array Elements 86
Summary 91
Using Loops and Exception
The Project: The NumberGuesser 94
The Increment (++) Operator 97
Using Compound Assignment Operators 100
Making a for Loop Count Backwards 102
Looping on Multidimensional Arrays 106 The MultiplicationArray Program 106
The break and continue Statements 112
xii
l e
4
C H A P T E R
Trang 14Exception Handling 116 Using the try-catch-finally Block 116 Using Exceptions to Screen User Input 117 Back to the NumberGuesser Program 118 Summary 120
Blackjack: Object-Oriented
The Project: the BlackJack Application 122 Understanding Object-Oriented Concepts 123
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 CardDeck Class 151
Polymorphism 158
The play() Method: BlackJack Driver 167
xiii
5
C H A P T E R
Trang 15Creating a GUI Using the
The Project: MadLib Program 172
Components 173 Events 177 Graphics 177
The UselessFrame Application 178 Learning about Containers 180 Using the WindowListener Interface 180
Using the CheckboxGroup Class 200
Back to the MadLib Game Application 214 Creating the MadDialog Component 214 Telling the Story: Creating the MadLib Game Frame 218 Summary 219
Advanced GUI: Layout Managers and Event
The Project: the AdvancedMadLib Application 222
xiv
l e
t C H A P T E R6
7
C H A P T E R
Trang 16Using GridBagLayout 229 Creating the GUIFrame Class 237
Using Inner Adapter Classes 246
Knowing the Source of an Event 248 More ActionEvent Handling 252
Handling AdjustmentEvents 259
Getting Back to the AdvancedMadLib Application 268 Creating the MadInputPanel Class 269 Creating the AdvancedMadLib Application 272 Summary 275
The Project: QuizShow Applet 278
Knowing the Difference between Applets and Applications 279
Including an Applet in a Web Page 283 The <applet> HTML Tag 284 Passing Parameters to Applets 284 Using Frames with Applets 288
Learning Applet Methods: init(), start(), stop(),
Writing Java Programs that Can Run as Applets or Applications 294
xv
8
C H A P T E R
Trang 17Using Sounds and Images 301
Loading and Displaying Images 304 Back to the QuizShowApplet Applet 306 Summary 311
The Graphics Class: Drawing
Getting Back to the Memory Game 344 Creating the MemoryCell Class 344 Creating the Memory Class 348 Summary 351
Animation, Sounds, and
The Project: ShootingRange Game 354 Threading 354 Extending the Thread Class 356 Implementing the Runnable Interface 358 Problems Associated with Multithreading 359
Using wait(), notify(), and notifyAll() 361
xvi
l e
9
C H A P T E R
10C H A P T E R
Trang 18Performing Animation 363 The Sprite Class 363 Testing the Sprite Class 365 Double Buffering 367 Playing Sound from Applications 369 Back to the ShootingRange Game 370 Summary 376
Custom Event Handling and
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
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
Creating the Block Game Application 423 Summary 427
11C H A P T E R
Trang 19Creating Your Own
Creating Lightweight Components 431
Creating Your Own Lightweight Components 432 Preparing to Create the jpr.lightweight Package 434
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 MineCellListener Interface 456
Testing the MineCell Class 462 Creating the Mine Field Classes 464
The MineFieldListener Interface 465
Creating the MinePatrol Application 474 Summary 476
xviii
l e
A
A P P E N D I X
B
A P P E N D I X
12C H A P T E R
Trang 20ello 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 propro-gramming 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-Introduction
H