TEAM LinG - Live, Informative, Non-cost and Genuine!
JavaProgAbsBeg-00Fnt.qxd
2/25/03
8:11 AM
Page i
Java
®
Programming
TEAM LinG - Live, Informative, Non-cost and Genuine!
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 Publishing, P.O. Box 1260BK, Rocklin, CA 95677-1260; (916) 787-7000. On your letterhead, 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!
JavaProgAbsBeg-00Fnt.qxd
2/25/03
8:11 AM
Page iii
Java
®
Programming
Joseph P. Russell
TEAM LinG - Live, Informative, Non-cost and Genuine!
JavaProgAbsBeg-00Fnt.qxd
2/25/03
8:11 AM
Page iv
© 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 photocopying, 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 Communications, Inc., Roseville, California 95661. Java, Forte, NetBeans and all trademarks and logos based on Java, Forte and NetBeans are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries. Internet Explorer is a registered trademark of Microsoft Corporation in the United States and/or other countries. Netscape is a registered trademark of Netscape Communications Corporation in the U.S. and other countries. Important: Prima Publishing cannot provide software support. Please contact the appropriate software manufacturer’s technical support line or Web site for assistance. Prima Publishing and the author have attempted throughout this book to distinguish proprietary trademarks from descriptive terms by following the capitalization style used by the manufacturer.
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
Information contained in this book has been obtained by Prima Publishing from sources believed to be reliable. However, 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 information. 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!
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!
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 project. 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!
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 consulting and develops applications for commercial Internet based companies. In his spare time, he enjoys game programming, painting, and playing his electric 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
[email protected].
TEAM LinG - Live, Informative, Non-cost and Genuine!
JavaProgAbsBeg-00Fnt.qxd
2/25/03
8:11 AM
Page viii
This page intentionally left blank
TEAM LinG - Live, Informative, Non-cost and Genuine!
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 93
CHAPTER
4
Using Loops and Exception Handling
CHAPTER
5
Blackjack: Object-Oriented Programming
121
CHAPTER
6
Creating a GUI Using the Abstract Windowing Toolkit
171
Advanced GUI: Layout Managers and Event Handling
221
CHAPTER
7
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!
JavaProgAbsBeg-00Fnt.qxd
2/25/03
8:11 AM
Page x
Contents Introduction
1
C H A P T E R
xix
Getting Started
1
The Project: the HelloWeb Applet What Is Java? Java Is a Programming Language Java Is Platform Independent Java Is Object-Oriented Why Learn Java? Java Is Relatively Easy to Learn Java Works Everywhere Installing and Setting Up the Java SDK Windows (Win32) Installation and Setup Solaris Installation Linux Installation Writing Your First Application Hello, World! Compiling the Program Running the Application Learning Java Syntax Basics Including Comments The main() Method Writing Your First Applet Back to the HelloWeb Applet! Writing the HTML Running the Applet Summary
2 3 4 4 5 7 7 7 8 8 10 10 11 12 12 14 15 17 19 20 20 21 21 23
TEAM LinG - Live, Informative, Non-cost and Genuine!
JavaProgAbsBeg-00Fnt.qxd
2/25/03
3
C H A P T E R
Page xi
xi Variables, Data Types, and Simple I/O The Project: the NameGame Application Variables and Data Types Learning Primitive Data Types Understanding Literals Using Character Escape Codes Naming Variables Declaring and Assigning Values to Variables Working with Numbers The TipAdder Program Operator Precedence Getting Simple User Input Using the BufferedReader Class Handling the Exceptions The Math Game Parsing Strings to Numbers The TipCalculator Application Accepting Command-Line Arguments Strings and String Operations The String Class String Methods Getting Back to the Name Game Summary
The Fortune Teller: Random Numbers, Conditionals, and Arrays The Project: the Fortune Teller Generating Random Numbers The NumberMaker Application The java.util.Random Class The Math Class Controlling the Random Number Range Getting Values Larger Than 1 Specifying a Range The Dice Roller
TEAM LinG - Live, Informative, Non-cost and Genuine!
25 26 26 27 28 29 31 31 34 34 37 38 40 41 43 44 45 46 48 48 49 49 53
55 56 57 57 58 62 64 65 65 65
Table of Contents
2
C H A P T E R
8:11 AM
JavaProgAbsBeg-00Fnt.qxd
2/25/03
8:11 AM
Page xii
xii Table of Contents
The if Statement Conditions and Conditional Operators Using Boolean Logical Operators The LowTemp Program The if-else Statement The HighOrLowTemp Program Nesting if-else Structures The ManyTemps Program Indentation and Syntax Conventions Using the switch Statement The FuzzyDice Program Understanding Arrays Declaring an Array Assigning Values to and Accessing Array Elements Multidimensional Arrays The ArrayTest Program Back to the Fortune Teller Summary
4
C H A P T E R
Using Loops and Exception Handling The Project: The NumberGuesser Counting Forward with Loops The Racer Program The for Loop The Increment (++) Operator Skipping Values The CountByFive Program Using Compound Assignment Operators Counting Backwards Making a for Loop Count Backwards Nested for Loops Looping on Arrays Looping on Multidimensional Arrays The MultiplicationArray Program Using the while Loop The do-while Loop Preventing Endless Loops The break and continue Statements
TEAM LinG - Live, Informative, Non-cost and Genuine!
67 68 71 73 74 77 78 79 80 81 83 85 85 86 88 88 90 91
93 94 94 95 96 97 98 99 100 101 102 103 105 106 106 108 109 112 112
JavaProgAbsBeg-00Fnt.qxd
2/25/03
8:11 AM
Page xiii
xiii
5
C H A P T E R
Blackjack: Object-Oriented Programming The Project: the BlackJack Application Understanding Object-Oriented Concepts The SimpleCardDeck Class Learning About Objects Examining Member Variables Field Modifiers Defining and Using Methods The Automobile Class Declaring a Method Passing Parameters Method Overloading Returning Values Understanding Static Methods Defining Constructor Methods Learning another Keyword: this Understanding Access Modifiers Field and Method Access Modifiers Encapsulation The Card and CardDeck Classes Writing the Card Class Writing the CardDeck Class Extending a Class The BigTruck Class Overriding Methods Polymorphism Back to the BlackJack Game The RandomCardDeck Class The Vector Class The BlackJack Program The play() Method: BlackJack Driver Other BlackJack Methods Summary
TEAM LinG - Live, Informative, Non-cost and Genuine!
116 116 117 118 120
121 122 123 123 124 127 129 132 133 136 136 138 139 140 141 143 144 144 146 148 148 151 154 154 157 158 158 158 160 163 167 168 169
Table of Contents
Exception Handling Using the try-catch-finally Block Using Exceptions to Screen User Input Back to the NumberGuesser Program Summary
JavaProgAbsBeg-00Fnt.qxd
xiv
2/25/03
6
Table of Contents
C H A P T E R
7
C H A P T E R
8:11 AM
Page xiv
Creating a GUI Using the Abstract Windowing Toolkit The Project: MadLib Program The java.awt Package Components Events Graphics Using Frames The UselessFrame Application Learning about Containers Using the WindowListener Interface Using Components The Label Component The Button Component The TextField Component The TextArea Component The Choice Component The List Component The Checkbox Component Using the CheckboxGroup Class The Canvas Component The Menu Component The PopupMenu Component The Panel Component The Scrollbar Component The Dialog Component Back to the MadLib Game Application Creating the MadDialog Component Telling the Story: Creating the MadLib Game Frame Summary
Advanced GUI: Layout Managers and Event Handling The Project: the AdvancedMadLib Application Using Layout Managers Using FlowLayout Using GridLayout Using BorderLayout
TEAM LinG - Live, Informative, Non-cost and Genuine!
171 172 172 173 177 177 178 178 180 180 182 183 185 187 191 193 195 198 200 202 203 207 208 209 212 214 214 218 219
221 222 223 223 225 228
JavaProgAbsBeg-00Fnt.qxd
2/25/03
8:11 AM
Page xv
xv
8
C H A P T E R
Writing Applets The Project: QuizShow Applet Understanding Applets Knowing the Difference between Applets and Applications How Do Applets Work? Hello Again! The Applet Class Including an Applet in a Web Page The