Tricks
     of the
      Java Programming Gurus

        by Glenn L. Vanderburg. et al.



C  O  N  T  E  N  T  S


Introduction

Chapter 1  Communication Between Applets

Chapter 2  Using the Media Tracker

Chapter 3  Exploiting the Network

Chapter 4  Using Java's Audio Classes

Chapter 5  Building Special-Purpose I/O Classes

Chapter 6  Effective Use of Threads

Chapter 7  Concurrency and Synchronization

Chapter 8  All About GridBaglayout and Other Layout managers

Chapter 9  Extending AWT Components

Chapter 10  Combining AWT Components

Chapter 11  Advanced Event Handling

Chapter 12  Image Filters and Color Models

Chapter 13  Animation Techniques

Chapter 14  Writing 2D Games

Chapter 15  A Virtual Java-Creating Behaviors in VRML 2.0

Chapter 16  Building STand-Alone Applications

Chapter 17  Network-Extensible Applications with Factory Objects

Chapter 18  Developing Database Applications and Applets

Chapter 19  Persistence

Chapter 20  A User's View of Security

Chapter 21  Creating a Security Policy

Chapter 22  Authentication, Encryption, and Trusted Applets

Chapter 23  Pushing the Limits of Java Security

Chapter 24  Integrated Development Environments

Chapter 25  Class Organization and Documentation

Chapter 26  The Java Debugging API

Chapter 27  Alternatives to Java

Chapter 28  Moving C and C++ Code to Java

Chapter 29  Using Tcl with Java

Chapter 30  When and Why to Use Native Methods

Chapter 31  The Native Method Interface

Chapter 32  Interfacing to Existing C and C++ Libraries

Chapter 33  Securing Your Native Method Libraries

Chapter 34  Client/Server Programming

Chapter 35  Taking Advantage of the Internet in Development

Chapter 36  Fulfilling the Promise of Java

Appendix A  API Quick Reference

Appendix B  Class Hierarchy Diagrams

Credits



Copyright © 1996 by Sams.net Publishing

FIRST EDITION

All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions. Neither is any liability assumed for damages resulting from the use of the information contained herein. For information, address Sams.net Publishing, 201 W. 103rd St., Indianapolis, IN 46290.

International Standard Book Number: 1-57521-102-5


HTML conversion by :
    M/s. LeafWriters (India) Pvt. Ltd.
    Website : http://leaf.stpn.soft.net
    e-mail : leafwriters@leaf.stpn.soft.net

About the Authors

LEAD AUTHOR

Glenn Vanderburg (glv@metronet.com, http://www.utdallas.edu/~glv/) is an Internet Development Specialist at The University of Texas at Dallas, where he helps maintain the University's Internet services and tries to find the time to develop new ones. He holds a B.S. degree in Computer Science from Texas A&M University. He wrote his first Java program in January 1995, and is interested in exploring the benefits of Java (and its security features) for full-scale software projects. Glenn wrote chapters 1, 3, 5, 16, 17, 20, 21, 22, 27, 29, 33, and 36. Glenn was invaluable as a sounding board and reviewer of the various outlines.

CONTRIBUTING AUTHORS

Bob Besaha is a Java instructor and developer. He may be reached at bbesaha@usa.net. Currently, Bob is developing beginning and advanced Java courseware, and also, Smalltalk and general Client-Server workshops for licensing by corporations and other development shops. Bob contributed to Chapter 34, "Client/Server Programming."

David R. Chung (dchung@inav.net) is a senior programmer in the Church Software Division of Parsons Technology in Hiawatha, Iowa. David's current projects include Windows and the Internet. David moonlights teaching C and C++ to engineers for a local community college. David is the father of six children whose names all begin with "J." In his spare time, David enjoys bicycling, teaching adult Sunday School, rollerblading, skiing, windsurfing, preaching in a nursing home, tennis, 2- and 6-player volleyball, playing the clarinet, and speaking French. David wrote Chapters 9 and 10, covering advanced AWT topics.

Justin Couch (justin@localnet.com.au) has completed B.Sc in computer science and BE(elec) in information systems from Sydney University. He works as a software engineer for ADI in simulation systems and the Australian Army Battle Simulation Group. His current research interests focus on using VRML for large scale worlds and developing the Cyberspace Protocol. He is involved with the Terra Vista virtual community. To keep sane he glides and performs as a classical musician. Justin can be reached via the Web at http://vlc.localnet.com.au/. Justin wrote Chapter 15, "A Virtual Java-Creating Behaviors in VRML 2.0."

Henrik Eriksson is an associate professor of Computer Science at Linköping University, Linköping, Sweden. His research interests include expert systems, knowledge acquisition, reusable problem-solving methods, and medical informatics. He got his MSc in Computer Science from Linköping University in 1987, and his Ph.D. in computer science at Linköping University in 1991. He was a postdoctoral fellow and research scientist at Stanford University between 1991 and 1994. He can be reached at the Department of Computer and Information Science, Linköping University, S-581 83 Linköping, Sweden; her@ida.liu.se. Henrik wrote Chapter 8, "All about GridBagLayout and Other Layout Managers."

Steve Ingram is a computer consultant in the Washington D.C. metro area specializing in embedded data communications and object-oriented design. He holds an electrical engineering degree from Virginia Tech and has been programming for 15 years. He was the architect behind the language of Bell Atlantic's Stargazer interactive television project, where he first encountered Java. When he's not working, Steve likes to sail the Chesapeake Bay with his wife and son. He can be reached at singram@qnet.com. Steve wrote Chapter 14, "Writing 2D Games."

Mark D. LaDue works as a Consulting Engineer for the Radio Dynamics Corporation, based in Silver Spring, Maryland, and is completing his Ph.D. in applied mathematics at the Georgia Institute of Technology. Mark is the creator of the Hostile Applets Home Page. He lives in Atlanta with his wife, Mariana, a research mathematician and Professor of Mathematics from Silistra, Bulgaria. You may write to him at mladue@math.gatech.edu. Mark is responsible for Chapter 23, "Pushing the Limits of Java Security."

Julie A. Kent (jkent@umbc.edu) is currently employed by SAIC and is working on constructing an Intranet at Trippler Army Medical Center. She recently completed her Master's degree in Computer Science at the University of Maryland Baltimore County and has eight years of experience in application development and database design. She has been involved in Internet development for the last two years, with particular focus in providing Web access to information stored in relational databases. She enjoys reading, hiking, swimming, and kayaking with her husband Scott. Julie wrote Chapter 24, "Integrated Development Environments."

Michael Morrison (74037.3444@compuserve.com) is a contributing author to Java Unleashed and the co-author of Windows 95 Game Developer's Guide: Using the Game SDK. He currently lives in Scottsdale, Arizona with his female accomplice, Mahsheed. When not busy being a Java guru, Michael enjoys skateboarding, mountain biking, and teaching his parents how to use Word. Mike wrote chapters 2, 4, 12, 13, and 28.

Jan Newmarch (jan@ise.canberra.edu.au) is a professor at the University of Canberra where he teaches Computer Science. He has written books on Prolog and Motif, and published papers in Physics, Artificial Intelligence, and User Interface Programming. He has written a number of systems, such as the awtCommand package, tclMotif (a binding of tcl to Motif), replayXt (a test and replay system for Xt/Motif), and others that are available as source code from ftp://ftp.canberra.edu.au/pub/motif/. He likes listening to music of most kinds, and enjoys eating and drinking wines of as high a quality as he can afford. Jan wrote Chapter 11, "Advanced Event Handling."

Tim Park is a recent graduate of the Stanford Graduate School of Electrical Engineering. Now working for a major computer company in Silicon Valley, he is currently working on a Java 3D graphics library for the Internet. His interests include distributed computing, computer graphics, and mountain biking. Tim can be reached at tpark@leland.stanford.edu. He wrote chapters 31 and 32 on native methods and interfacing to existing C and C++ libraries.

Larry Rau (larryrau@aol.com) is currently a Software Technologist with The ImagiNation Network, an online network dedicated to gaming and entertainment. He received a BA in Computer Science and Mathematics from Anderson University in Anderson, Indiana. His primary interest is in computer languages and compilers, although he often branches out to a wide range of interests. Most recently he has been lucky enough to work with Java on a daily basis, and Larry would like to acknowledge The ImagiNation Network, Inc. for providing him with the opportunity to use the Java language and contribute to this book. Outside of the computer field he likes to play almost any sport, with running and hockey high on the list. Larry is also lucky to share his life with his loving wife, Wendy, and his wonderful children, Nicholas and Olivia. Larry wrote chapters 6, 26, and 30.

George Reese (borg@imaginary.com) holds a philosophy degree from Bates College in Lewiston, Maine. He currently works as a consultant with York and Associates, Inc. and as a magazine columnist for the Java Developer's Journal. George has written some of the most popular MUD software on the Internet, including the Nightmare Object Library and the Foundation Object Library. For Java, he was the creator of the first JDBC implementation, the Imaginary JDBC Implementation for mSQL. His Internet publications include the free textbooks on the Lpc programming language, Lpc Basics and Intermediate Lpc. George lives in Bloomington, Minnesota with his two cats Misty and Gypsy. He wrote chapters 18 and 35 and contributed to Chapter 34.

Mary Dombek Smiley (gmsmiley@ix.netcom.com) is a Senior Software Engineer with Lockheed Technical Operations Corporation, working on the Hubble Space Telescope Program in Lanham, Maryland. Mary has a bachelors degree in computer science from University of Iowa and a masters degree in software engineering from Penn State. She was assisted in researching this chapter by Jeff Johnson (jeffadie@earthlink.net), Senior Staff Engineer with Lockheed Martin Space Mission Systems. Jeff has a bachelors degree in computer science from Colorado State University. Mary wrote Chapter 25, "Class Organization and Documentation Tools."

Eric Williams is a team leader and software engineer for Sprint's Long Distance Division. Although currently focusing on C++ and Smalltalk development, Eric has been active in the Java community, contributing to the comp.lang.java newsgroup and delivering presentations about Java to various user groups. Eric was also responsible for identifying a Java 1.0.1 security flaw related to sockets and DNS. He can be reached by email at williams@sky.net or via the Web at http://www.sky.net/~williams. Eric wrote Chapter 7, "Concurrency and Synchronization" and Chapter 19, "Persistence."

Tell Us What You Think!

As a reader, you are the most important critic and commentator on our books. We value your opinion and want to know what we're doing right, what we could do better, what areas you'd like to see us publish in, and any other words of wisdom you're willing to pass our way. You can help us make strong books that meet your needs and give you the computer guidance you require.

Do you have access to CompuServe or the World Wide Web? Then check out our CompuServe forum by typing GO SAMS at any prompt. If you prefer the World Wide Web, check out our site at http://www.mcp.com.

Note
If you have a technical question about this book, call the technical support line at (800) 571-5840, ext. 3668.

As the team leader of the group that created this book, I welcome your comments. You can fax, e-mail, or write me directly to let me know what you did or didn't like about this book-as well as what we can do to make our books stronger. Here's the information:

FAX:317/581-4669
E-mail:newtech_mgr@sams.mcp.com
Mail:Mark Taber
Comments Department
Sams Publishing
201 W. 103rd Street
Indianapolis, IN 46290


Introduction

by Glenn Vanderburg

"Java gurus? Already? But Java's a brand new language!"

It's true that as I write this, Java has only been available to the public for about a year (and only a few months in a supported release). As programming languages go, Java is quite new, and the complete Java guru is an exceedingly rare individual. No one person could have written this book.

In some ways, though, Java is not so new. It has existed within Sun Microsystems Laboratories, in one form or another, for several years. Programmers within Sun have used Java for a while and gained a lot of experience with it, and that experience shows in the code for the Java library, which is freely available.

Furthermore, none of the individual features of Java are really new at all. Java's inventors cheerfully acknowledge that Java consists primarily of tried and true ideas, combined in a novel, tasteful, clean way. The whole of Java is new: no previous language has incorporated the same combination of features, and although some other languages have come close, few have been as simple or comfortable to use as Java. But while the combination is new, the individual pieces are not. Pick any one of them, and there are quite a few programmers around the world who have a deep understanding of the topic. Those are the programmers who have come together to write Tricks of the Java Programming Gurus.

Audience and Focus

At the start of this project, I began by outlining the book that I wanted to read-the book that I wished was already available. I listed things that I wanted to learn about Java: deep topics which weren't being covered by the tutorials or reference books which were coming on the market, and questions about how Java could be used for advanced tasks. Editors, friends, and other authors proposed chapters on topics which I had overlooked, and the result, I think, meets my goal. In writing my chapters, and reading the chapters contributed by the other authors, I've learned the answers to the questions I had at the beginning, and many others besides.

The topics covered by Tricks of the Java Programming Gurus fall into three categories:

If you are interested in any of those things-if you want to take Java beyond animated coffee cups and flashy Web pages-you should read this book. It is filled with tricks on both small and large scales: handy snippets of code, complete sample classes, and high-level design strategies designed to help you make the most of Java's unique combination of features.

The authors of this book like Java and think that it has tremendous promise, but you won't find much breathless hype here. We assume that readers are already familiar with the basics of the Java language and API, and if you know that much, you've heard the claims already. So instead of asking you to sit through that again, we've tried to concentrate on information that you can actually use to bring some of the promises to reality. We have been frank about deficiencies in Java and its libraries, steering you away from problem areas, and warning you about bugs and misfeatures which may need to change in some future version of the libraries. We've also tried to provide some of the knowledge you'll need to work around some of the problems on your own.

Roadmap for Readers

This book, as the table of contents shows, is organized in ten parts, each devoted to a different part of the Java environment, or a different aspect of Java programming. The organization is logical, and if it's your goal to become a complete Java expert, you might want to start at the beginning and read straight through to the end. Most readers, however, will have more pragmatic goals, and will want to choose the chapters that are particularly relevant to their needs. Hopefully, somewhere in the next few paragraphs you will find an approximation to your own goal, along with pointers to chapters which should help you along your way.

Most readers will find Parts 2, 3, and 4 useful: they cover I/O and concurrency, advanced AWT topics, and graphics-topics which are important for all kinds of Java programs. Also of general interest is Part 7, "Using Java Tools," which covers graphical development environments and other Java tools.

If you are interested in writing advanced applets that interact with the user and perform useful jobs, you can start at the beginning. Part I deals with advanced applet programming: inter-applet communication, using the MediaTracker to track asynchronous loading of images and other media objects, making good use of the network, and audio. Applet programmers can also make use of the general topics in Parts 2, 3, and 4. Even the I/O chapter will be useful in spite of applet security restrictions, because Java network communication is accomplished using some of the same mechanisms as are used for file I/O.

Readers who want to learn about some of the new Java libraries and frameworks which aren't a part of the 1.0 Java release should turn to the following chapters:

Finally, if you want to build full-fledged applications with Java, able to host applets or dynamically loadable extensions, you might find these sections especially helpful:


Acknowledgments

Any book which tries to cover this much territory requires contributions from a lot of people. All of the various authors and most of the production staff at Sams.net who contributed are listed by name in the book, but there are many contributors who are not mentioned by name. Colleagues and network acquaintances have cheerfully answered technical questions. I know that my family and friends have been patient while I was writing, and my wife read every page I wrote and suggested dozens of improvements, wisely placing the quality of the book ahead of my ego. I'm certain that the other authors received similar support and assistance from those close to them. With over a dozen authors, there is no way for us to individually acknowledge everyone who deserves our thanks, but we are appreciative nonetheless.