Web Programming
      with
Visual J++™

by Mike Cohn, Jay Rutten, and James Jory


CONTENTS

Introduction

Chapter 1   Web Programming and Visual J++

Chapter 2   Creating Your First Applet with Applet Wizard

Chapter 3   Using the Developer Studio

Chapter 4   Applet Programming Fundamentals

Chapter 5   Java's User Interface Components

Chapter 6   Working with Frames, Dialogs, and Menus

Chapter 7   Saving Time with the Resource Wizard

Chapter 8   Debugging with the Visual J++ Debugger

Chapter 9   Documenting Your Visual J++ Code

Chapter 10   Working with Java Strings

Chapter 11   The Java Utility Classes

Chapter 12   Moving Up to Multithreading

Chapter 13   Using Java Streams

Chapter 14   Incorporating Graphics

Chapter 15   Multimedia Programming with Java

Chapter 16   Sprucing Things Up with Colors and Fonts

Chapter 17   Accessing URLs

Chapter 18   Networking with Datagrams and Sockets

Chapter 19   Client/Server Programming

Chapter 20   Keeping Out the Riff-Raff: Java Security

Chapter 21   Using ActiveX Controls with Java

Chapter 22   Using the Data Access Objects

Chapter 23   Software Cost Estimator

Chapter 24   Development Request Online

Appendix A   A Whirlwind Tour of the Java Language

Appendix B   Pointers and Memory Management


Credits


Copyright© 1997 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 Publishing, 201 W. 103rd St., Indianapolis, IN 46290.

International Standard Book Number: 1-57521-174-2


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


Publisher and PresidentRichard K. Swadley Publishing ManagerGreg Wiegand
Director of Editorial Services Cindy MorrowAssistant Marketing Managers Kristina Perry, Rachel Wolfe
Acquisitions EditorChristopher Denny Development EditorRichard W. Alvey, Jr.
Software Development Specialist Brad MyersProduction Editor Mary Inderstrodt
Copy EditorsHeather Butler, Keith Davenport IndexerCheryl Dietsch
Technical ReviewersChris Stone, Matt Stone Editorial CoordinatorKatie Wise
Technical Edit CoordinatorLynette Quinn Resource CoordinatorDeborah Frisby
Editorial AssistantsCarol Ackerman, Andi Richter, Rhonda Tinch-Mize Cover DesignerTim Amrhein
Book DesignerAlyssa Yesh Copy WriterPeter Fuller
Production Team SupervisorsBrad Chinn, Charlotte Clapp
ProductionRick Bond, Carol Bowers, Jenaffer Brandt, Paula Lowell, Timothy Osborn


About the Authors

Mike Cohn is the Director of Information Technology at Access Health, Inc., the leading provider of personal health management services. Before that he was with Andersen Consulting and the Adler Consulting Group in New York. He holds a Masters degree in Computer Science from the University of Idaho and has been programming for 16 years. Mike lives in Cameron Park, California, with his wife Laura and their daughter Savannah. Mike was the lead author of Database Developer's Guide with Borland C++ 5.0 and Java Developer's Reference. When not programming, Mike is usually thinking about programming, reading about programming, or writing about programming.

Jay Rutten is a Software Engineer at Access Health, Inc., where his fire-fighting skills range from database replication to writing C++, Delphi, and Java code. He is involved in designing the company's next generation database and Internet products. Jay lives in Rocklin, California, with his wife Paula and their son Christopher. When not chained to his desk, he can be found on the volleyball court, on his bike, or just spending time with his family.

James Jory is a Lead Programmer/Analyst with the Information Technology Group at Access Health, Inc. He has been programming for seven years and has experience on several platforms ranging from personal computers to mainframes. Before joining Access Health, James was a Systems Engineer at Electronic Data Systems where he specialized in network programming and GUI development and was an intranet Webmaster. He has also been an independent consultant to Dentisoft Inc., a supplier of Windows-based dental office management software.

Tell Us What You Think!

As a reader, you are the most important critic and commentator of 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 publishing manager 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:programming_mgr@sams.mcp.com
Mail:Greg Wiegand
Sams Publishing
201 W. 103rd Street
Indianapolis, IN 46290


Introduction

By now there is little doubt that the Java language will profoundly impact both how we write programs and the programs we write. Java influences how we write programs because it achieves a new level of power combined with simplicity. Java influences the programs we write because Java is an enabling technology. With Java you can write programs you could not write without it. There are, of course, the simple things that Java enables, such as adding animation to Web pages. However, with Java so much more is possible. With Java you can write a single program that will run on Windows NT, Windows 95, a Macintosh, or UNIX. With Java you can write a distributed program that can access resources on any machine on the Internet. In less than 10 lines of Java code, you can write a program to display an image retrieved from a computer 5,000 miles away. And even better, your 10-line program can be run from almost any computer in use today or in the future.

When a powerful language like Java is combined with a powerful development environment, you have an unbeatable combination. In this book you will learn how Java and Visual J++ work together to be this unbeatable combination. While there are now many Java development environments available, Visual J++ is unique in extending Java with the ability to use ActiveX controls from within Java. This opens an entire world of existing components to your Java programs.

Who Should Buy This Book?

This is an advanced book. We assume that you are already familiar with Java, or at least with object-oriented programming in general. Unlike most other Java books, this one does not include 300 pages teaching you the basics of the language. Starting right with the first chapter we assume you know the basics of Java syntax. Appendix A provides a whirlwind tour of the Java language in case you need a refresher before getting started with Chapter 1

You should buy this book if you are looking for a book that goes into more detail than do other books. This book does not "scratch the surface" of any topics. If a topic was worth covering, this book covers it in detail. You should also buy this book if you are looking for lots of examples. Almost every concept discussed in this book is accompanied by one or more examples.

This book is not an API reference. Although there should be room on every Java programmer's bookshelf for a good API reference, there should also be room for a book, like this one, that tells how to use the language to solve problems.

You should buy this book if you're a practicing programmer with a job to do or a deadline to meet. If you're a manager trying to understand Java or figure out if it has a place in your organization, this isn't the book for you. This book is intended for programmers who are either starting to use Java on the job or who are learning it in their spare time.

We do encourage you to e-mail us at the following addresses:

mcohn@spider.innercite.com
pjrutten@pacbell.net
jjory@ibm.net

What's in This Book?

Chapter 1 "Web Programming and Visual J++," presents some of the reasons why Web programming with Java, and with Visual J++ in particular, will be an important part of the World Wide Web's future. If you're not fully convinced of the benefits of Java programming this chapter finishes the job. You'll also get an overview of some of the Visual J++ features that make Java development easier. Among these are the Developer Studio, the Applet Wizard, the Dialog, Menu, and Graphic Editors, the Resource Wizard, and the debugger.

Chapter 2 "Creating Your First Applet with Applet Wizard," introduces the Java Applet Wizard. This is the first of a handful of wizards you'll encounter when using Visual J++. In this chapter you'll learn how to use the Applet Wizard to generate an initial applet. By the end of this chapter you'll have created a powerful applet that makes use of multithreading and animation.

Chapter 3 "Using the Developer Studio," describes the Visual J++ integrated development environment. The Developer Studio is a proven productivity aide from its use in Microsoft's Visual C++. In this chapter you'll see how the Developer Studio can speed your Java programming tasks. You'll learn about project workspaces and how to manage multiple projects and configurations within a single workspace. You'll discover the Project Workspace window and its FileView, ClassView, and InfoView windows. Using the ClassView, you'll learn how to let Visual J++ help you create new classes and add methods and variables to existing classes.

Chapter 4 "Applet Programming Fundamentals," covers a lot of ground. You'll see how an applet's init, start, stop, and destroy methods are executed over the life of the applet. Handling events such as keypresses and mouse clicks are an important part of Java programming, so this chapter presents numerous examples of how to handle events. You'll learn about generic event handling with the handleEvent method, as well as how to handle events with mouse- and keyboard-specific methods. This chapter also demonstrates how to customize the behavior of an applet by using applet parameters embedded in the host HTML file. Finally, this chapter also gives a quick preview of loading a graphics resource from a URL and displaying it in an applet.

Chapter 5 "Java's User Interface Components," describes the Component class and all of its subclasses. These include Button, TextField, TextArea, Label, Checkbox, List, Choice, and Scrollbar. This chapter includes examples of how to create and use each of these classes. This chapter also describes the layout classes and shows how they can be used to control the placement of components in the user interface.

Chapter 6 "Working with Frames, Dialogs, and Menus," describes Java's container classes: Container, Panel, Frame, Dialog, and FileDialog. Here you will learn how to create and place panels on other containers in order to group components. You'll also learn how to use the Frame and Dialog classes to create windows that are not part of the browser's window. This chapter also demonstrates how to control the appearance of the mouse pointer. Finally, you will learn about Java's menu classes: MenuBar, Menu, MenuItem, and CheckboxMenuItem.

Chapter 7 "Saving Time with the Resource Wizard," describes the Resource Wizard and how it can free you from some of the difficulties of hand-coding your user interface. You'll learn how to visually design dialogs, frames, and menus, and then convert these designs into Java classes that can be used in your projects.

Chapter 8 "Debugging with the Visual J++ Debugger," explores the usefulness of the integrated debugger. Control of the executing program is handled by the ability to set a breakpoint on any source line of a successfully complied program. Once the breakpoints are set, you can run to the next breakpoint, step through the source line by line, or execute until the current line is reached. Data can be inspected in a number of ways including DataTips, QuickWindow, the Watch window, or the Variable window, which the debugger automatically populates. Additionally, the debugger has support for catching exceptions and specifying the thread to be debugged.

Chapter 9 "Documenting Your Visual J++ Code," describes how to acquire and use the JavaDoc program to automatically create documentation for your Java classes. Here you'll learn how to embed special tags into your code to document the parameters, return values, and exceptions of each method. You'll also see how HTML commands can be embedded directly in your code to control the appearance of the documentation.

Chapter 10, "Working with Java Strings," describes the String and StringBuffer classes, two of the most commonly used classes in Java programming. Included are many examples of using the member methods of the String class, including changing the case of a string, trimming whitespace, and accessing substrings. This chapter also shows how to convert variables of other types into strings and how to search and compare strings. The StringBuffer class is described, and reasons are presented about why it is a more useful class for strings that change size or content.

Chapter 11, "The Java Utility Classes," gives you a thorough overview of the classes in the java.util package. You will learn how to use the BitSet class to store large amounts of Boolean data, how to manipulate dates and times with the Date class, how to generate random numbers, and how to tokenize strings. You'll learn how the Observable class works in conjunction with the Observer interface to allow you to decouple your code. The Hashtable class is described, and you'll see how the Properties class can be used in applications to stream data to and from files. This chapter also teaches you how the Vector class can be used as a resizable array and how the Stack class extends Vector.

Chapter 12, "Moving Up to Multithreading," shows how to take advantage of one of Java's most useful language featuresóthreads. Creating a usable thread is as easy as creating a class that implements the Runnable interface. This interface has a single run method, which is called after the thread is started. Synchronization of multiple threads writing to common variables is covered on a block level or a method level. Additional capabilities that allow threads to be started and stopped are discussed. This chapter describes how to use the ThreadGroup class to group-related threads and assign a priority to the group.

Chapter 13, "Using Java Streams," covers the java.io package in detail. Streams provide an effective abstraction for data flow between two sources, and this package includes classes for streaming between buffers, files, and processes. This chapter also describes the input/output stream filter classes that can be attached to streams to add buffering, formatting, and handlers for streaming primitive data types. The examples in this chapter also establish a foundation that is built upon in Part IV, "Networking with Java."

Chapter 14, "Incorporating Graphics," presents an in-depth look at the Graphics class and how you can use the methods of this class to enhance the appearance of your Java programs. In this chapter you will learn how to draw outlined and filled shapes such as lines, arcs, ovals, rectangles, and polygons. You will also learn about the Image class and how to filter, crop, and modify images prior to display. You will also see how the ImageObserver interface allows you to monitor the progress of an image that is being retrieved.

Chapter 15, "Multimedia Programming with Java," covers two popular topics: animation and sounds. The MediaTracker class is used to load multiple images and then notify the application that it has completed. Once you have multiple images loaded, basic animation can be accomplished by displaying closely related images in quick succession. A couple of additional techniques to improve the appearance of the animation are also discussed. An alternate approach to loading and displaying multiple images is manipulating a single image, displaying only parts of it. Supporting sounds is simple with Java by using the play method of the Applet class.

Chapter 16, "Sprucing Things Up with Colors and Fonts," illustrates how to set colors and fonts. A sample dialog is created that allows you to set the color by either selecting a predefined color or creating a unique color by setting the components of the color. A similar dialog is created for selecting the font.

Chapter 17, "Accessing URLs," focuses on tapping the power of the Uniform Resource Locator (URL) collection of classes to access resources on the Internet. This chapter begins by exploring the syntax of URLs and will show you how to implement your own URL handlers by creating support for the mailto URL. This chapter will also show you how to interact with common gateway interface (CGI) scripts from your applets.

Chapter 18, "Networking with Datagrams and Sockets," gets into the low-level details of network programming with Java. The datagram example implements a live national debt server that broadcasts datagram packets to one or more datagram client applets. A socket example implements a post office protocol (POP) client that can be run as an applet or application to retrieve electronic mail from a POP server on the Internet. By the end of this chapter, you will understand the strengths and weaknesses of the datagram and socket methods of communication and how they can be used in your programs.

Chapter 19, "Client/Server Programming," takes socket programming one step further by describing how robust and efficient server programs can be written in Java. The primary example implements an Internet dictionary that is capable of handling multiple simultaneous requests from 1client applets and applications over a network. This chapter also discusses Java's contribution to client/server development and the emerging technologies that will make Java an even more serious player in the future.

Chapter 20, "Keeping Out the Riff-Raff: Java Security," lays out the security scheme implemented by the Java development and runtime environments. Without a doubt, the security challenges of Internet development should not be taken lightly and certainly no language or platform is inviolable. However, by the end of this chapter you will have a clear understanding of Java's multilayer security model and see how it provides a nearly impenetrable barrier against both intentional and unintentional security violations.

Chapter 21, "Using ActiveX Controls with Java," covers some of the basics of ActiveX controls, commonly referred to as COM objects in the Java world. First, creation of the Java interface to any ActiveX control is accomplished through the use of the Java Type Library Wizard. Once you have an interface, communication channels are discussed so that the COM object can be controlled by an applet, or the applet can be used as an event handler of the COM object events. To show the versatility of the Java language, a COM object is created using Java and the COM object is then securely packaged in a signed .CAB file.

Chapter 22, "Using the Data Access Objects," introduces you to the Data Access Objects (DAO) and shows how to use them in your Java programs. You'll learn about Database, Recordset, and Field objects and how to combine these objects to perform useful tasks. You'll see examples of using DAO to browse a database, add new records, update existing records, delete records, search for records, and execute SQL.

Chapter 23, "Software Cost Estimator," presents a complete Java applet example that combines much of what you learned in prior chapters. The applet created in this chapter is a software cost estimation calculator based on the Constructive Cost Model. It demonstrates in-depth user interface programming, including the use of an imagemap to control the appearance of the applet.

Chapter 24, "Development Request Online," is a complete applet that shows the use of Database Access Objects to implement a request tracking system. The chapter contains a complete project overview including a class overview and database schema. The key classes are described in detail, including the database access classes, common user interface classes, and the classes used to implement the specific panels used in the applet.

Appendix A, "A Whirlwind Tour of the Java Language," is a quick overview of the Java language. If you are already familiar with Java, this appendix can serve as a handy reference. On the other hand, if you are not familiar with Java but are experienced in another object-oriented language, this appendix might be all you need to read to get started with Java.

Appendix B, "Pointers and Memory Management," offers a reminder of how Java simplifies programming by eliminating pointers and using garbage collection to automatically reclaim unused memory