Tải bản đầy đủ (.pdf) (20 trang)

Java Programming for absolute beginner- P1 docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.71 MB, 20 trang )

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Java
Programming
®
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page i
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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 />Send Us Your Comments
To comment on this book or any other PRIMA TECH title, visit our reader
response page on the Web at />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.
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page ii
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Java
Programming
Joseph P. Russell
®
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page iii
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
© 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
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page iv

TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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.
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page v
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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.
A
c
k
n
o
wl
e
d
gm

e
n
t
s
I
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page vi
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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 (). 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 (). 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
A
b
o
u
t t
he
A

u
t
h
o
r
J
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page vii
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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.
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
C
on
t
e
n
t
s a
t
a
G
la
n
c
e
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page ix
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Introduction xix
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
C
on
t
e
n
t
s
1
CHAPTER
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page x
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Variables, Data Types, and
Simple I/O 25

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
The Fortune Teller: Random
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
xi
Ta
b
l
e
of C
o
n
ten
t
s
2
CHAPTER
3
CHAPTER
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xi
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The if Statement 67
Conditions and Conditional Operators 68
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
Using Loops and Exception
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

xii
Ta
b
l
e
of C
o
n
ten
t
s
4
CHAPTER
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xii
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Exception 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
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
xiii
Ta
b
l
e

of C
o
n
ten
t
s
5
CHAPTER
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xiii
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Creating a GUI Using the
Abstract Windowing Toolkit 171
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
Advanced GUI: Layout
Managers and Event
Handling 221
The Project: the AdvancedMadLib Application 222
Using Layout Managers 223
Using FlowLayout 223
Using GridLayout 225
Using BorderLayout 228
xiv
Ta
b
l
e
of C
o
n
ten
t
s

6
CHAPTER
7
CHAPTER
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xiv
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Using GridBagLayout 229
Creating the GUIFrame Class 237
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
Writing Applets 277
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 <applet> 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
xv
Ta
b
l
e
of C
o
n
ten
t
s
8
CHAPTER
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xv

TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Using Sounds and Images 301
Playing Sound Files 302
Loading and Displaying Images 304
Back to the QuizShowApplet Applet 306
Summary 311
The Graphics Class: Drawing
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
Animation, Sounds, and
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
xvi
Ta
b
l
e
of C
o
n
ten
t
s
9
CHAPTER
10
CHAPTER
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xvi
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
xvii
Ta
b
l

e
of C
o
n
ten
t
s
Performing 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
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
11
CHAPTER
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xvii
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Creating Your Own
Components and Packages 429
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
Using the CD-ROM 477
Java Language Summary 481
Index 491
xviii
Ta
b
l
e
of C
o
n
ten
t
s
A
APPENDIX
B

APPENDIX
12
CHAPTER
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xviii
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
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
I
n
t
ro
d
u
c
t
i
o
n
H
JavaProgAbsBeg-00Fnt.qxd 2/25/03 8:11 AM Page xix
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×