IBMVisualAgeforJava,Version3.0,EarlyAdopters Environment for the Java 2 platform, Standard Edition V1.2 IBM

Getting Started Note! Before using this information and the product it supports, be sure to read the general information under ″Notices″ on page vii.

Edition notice This edition applies to Version 3.0 of IBM VisualAge for Java and to all subsequent releases and modifications until otherwise indicated in new editions. © Copyright International Business Machines Corporation 1997, 1999. All rights reserved. US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp. Contents

Notices ...... v Versions and editions ...... 63 Programming Interface Information ...... vi Versioning an edition of your code .....65 Trademarks and Service Marks ...... vii Exploring the repository ...... 65 Getting samples from the repository .....67 Chapter 1. Introduction ...... 1 Importing and exporting code ...... 68 What’s new in this release ...... 2 Printing online help topics...... 3 Chapter 6. Advanced features .....71 Introduction to data access beans ...... 71 Chapter 2. Getting started ...... 5 Setting up access to a DB2 database .....71 Using Select, Modify and ProcedureCall beans. . 72 What is VisualAge for Java? ...... 5 Accessing data with the Select bean .....73 Starting VisualAge for Java ...... 6 Data output beans ...... 74 The and the Repository ...... 8 Using SQLJ ...... 74 The Workbench ...... 9 Writing code manually ...... 76 Pages in the Workbench ...... 10 Creating beans without the VCE ...... 78 Customizing your workspace ...... 12 Code Assist for types, methods, and fields . . . 79 IDE customization options ...... 13 Internationalization support ...... 82 Workbench customization ...... 14 The Distributed Debugger ...... 83 Navigating ...... 15 Tool Integrator API ...... 85 Searching ...... 16 External software configuration management (SCM) Browsing ...... 19 tools...... 85 Debugging ...... 22 Printing program elements ...... 86 The Quick Start window ...... 24 Finding out more about VisualAge for Java....87 TheLog...... 26 The Scrapbook ...... 27 The Console ...... 27 Chapter 7. The To-Do List tutorial . . . 89 The Visual Composition Editor ...... 29 Building your first applet...... 89 Exploring the repository ...... 32 Constructing the To-Do List applet .....89 Using Quick Start and a SmartGuide to create Chapter 3. Beans ...... 35 your applet ...... 90 Adding labels and text boxes ...... 91 Support for JavaBeans components ...... 36 Adding a scrolling list ...... 92 The BeanInfo page ...... 37 Adding the Add and Remove buttons ....93 Manipulating beans ...... 38 Sizing and aligning visual beans in the To-Do Sizing, aligning, and positioning beans ....40 List ...... 93 Copying and deleting beans ...... 42 Correcting mistakes in the Visual Composition Changing bean properties ...... 43 Editor ...... 95 Changing bean colors and fonts ...... 44 Connecting beans in the To-Do List ...... 95 Connecting beans ...... 46 Adding a list model and connecting it to the Add ...... 95 Chapter 4. Connections ...... 49 The Event-to-code connection in the To-Do List 97 Changing the properties of connections .....49 Saving and testing the To-Do List applet....99 Event connections ...... 50 Enhancing the To-Do List applet ...... 100 Event-to-code connections ...... 51 How the enhanced to the To-Do List applet will Event-to-Method Connections ...... 51 work ...... 100 Event-to-property connections ...... 52 Finding your To-Do List applet in the Parameter connections...... 53 Workbench ...... 101 Parameter-from-code connections ...... 53 Versioning an edition of your applet.....102 Parameter-from-method connections .....54 Adding state checking to your applet ....103 Properties as parameters ...... 55 Setting up state checking for the Remove button 104 Constants as parameters ...... 56 Creating a new version of an edition ....106 Connection parameters ...... 57 Adding the Open and Save buttons to the Property-to-property connections ...... 59 To-Do List ...... 106 Adding a method for reading files .....108 Chapter 5. Code storage and version Adding a method for writing files .....109 control...... 63 Using the Scrapbook to test code ...... 110

© Copyright IBM Corp. 1997, 1999 iii Setting a breakpoing in the writeToDoFile class 111 Chapter 8. The Staff List tutorial . . . 121 Using the Debugger browser ...... 112 Data access beans in action ...... 121 Additional integrated debugger features . . . 114 Building the StaffList user interface ...... 121 Connecting the Open To-Do File button . . . 115 Traversing result sets with the DBNavigator Testing the Open To-Do File button .....115 Bean ...... 122 Connecting the Save To-Do File button ....116 Adding and setting the Select bean .....123 Saving and testing the completed To-Do List Connecting the Select Bean ...... 126 program ...... 117 Testing the StaffList Application ...... 127 Adding a counter to the ToDoList .....118 Returning to a previous edition ...... 120

iv Getting Started Notices

Note to U.S. Government Users Restricted Rights -- use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.

This information was developed for products and services offered in the U.S.A. IBM may not offer the products, services, or features discussed in this document in other countries. Consult your local IBM representative for information on the products and services currently available in your area. Any reference to an IBM product, program, or service is not intended to state or imply that only that IBM product, program, or service may be used. Any functionally equivalent product, program, or service that does not infringe any IBM intellectual property right may be used instead. However, it is the user’s responsibility to evaluate and verify the operation of any non-IBM product, program, or service.

IBM may have patents or pending patent applications covering subject matter described in this document. The furnishing of this document does not give you any license to these patents. You can send license inquiries, in writing, to: IBM Director of Licensing IBM Corporation North Castle Drive Armonk, NY 10504-1785 U.S.A.

For license inquiries regarding double-byte (DBCS) information, contact the IBM Intellectual Property Department in your country or send inquiries, in writing, to: IBM World Trade Asia Corporation Licensing 2-31 Roppongi 3-chome, Minato-ku Tokyo 106, Japan

The following paragraph does not apply to the United Kingdom or any other country where such provisions are inconsistent with local law: INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES THIS PUBLICATION ″AS IS″ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Some states do not allow disclaimer of express or implied warranties in certain transactions, therefore, this statement may not apply to you.

This information could include technical inaccuracies or typographical errors. Changes are periodically made to the information herein; these changes will be incorporated in new editions of the publication. IBM may make improvements and/or changes in the product(s) and/or the program(s) described in this publication at any time without notice.

Any references in this information to non-IBM Web sites are provided for convenience only and do not in any manner serve as an endorsement of those Web sites. The materials at those Web sites are not part of the materials for this IBM product and use of those Web sites is at your own risk.

IBM may use or distribute any of the information you supply in any way it believes appropriate without incurring any obligation to you.

© Copyright IBM Corp. 1997, 1999 v Licensees of this program who wish to have information about it for the purpose of enabling: (i) the exchange of information between independently created programs and other programs (including this one) and (ii) the mutual use of the information which has been exchanged, should contact: Lab Director IBM Canada Ltd. 1150 Eglinton Avenue East Toronto, Ontario M3C 1H7 Canada

Such information may be available, subject to appropriate terms and conditions, including in some cases, payment of a fee.

The licensed program described in this document and all licensed material available for it are provided by IBM under terms of the IBM Customer Agreement, IBM International Program License Agreement or any equivalent agreement between us.

Information concerning non-IBM products was obtained from the suppliers of those products, their published announcements or other publicly available sources. IBM has not tested those products and cannot confirm the accuracy of performance, compatibility or any other claims related to non-IBM products. Questions on the capabilities of non-IBM products should be addressed to the suppliers of those products.

This information contains examples of data and reports used in daily business operations. To illustrate them as completely as possible, the examples include the names of individuals, companies, brands, and products. All of these names are fictitious and any similarity to the names and addresses used by an actual business enterprise is entirely coincidental.

COPYRIGHT LICENSE:

This information contains sample application programs in source language, which illustrates programming techniques on various operating platforms. You may copy, modify, and distribute these sample programs in any form without payment to IBM, for the purposes of developing, using, marketing or distributing application programs conforming to the application programming interface for the operating platform for which the sample programs are written. These examples have not been thoroughly tested under all conditions. IBM, therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. You may copy, modify, and distribute these sample programs in any form without payment to IBM for the purposes of developing, using, marketing, or distributing application programs conforming to IBM’s application programming interfaces.

Each copy or any portion of these sample programs or any derivative work, must include a copyright notice as follows:

® (your company name) (year). Portions of this code are derived from IBM Corp. Sample Programs. ® Copyright IBM Corp. 1997, 1999. All rights reserved.

Programming Interface Information

Programming interface information is intended to help you create application software using this program. vi Getting Started General-use programming interface allow the customer to write application software that obtain the services of this program’s tools.

However, this information may also contain diagnosis, modification, and tuning information. Diagnosis, modification, and tuning information is provided to help you debug your application software.

Warning: Do not use this diagnosis, modification, and tuning information as a programming interface because it is subject to change.

Trademarks and Service Marks

The following terms are trademarks of the International Business Machines Corporation in the United States, or other countries, or both:

AIX AS/400 DB2 CICS IBM Network Station OS/2 OS/390 OS/400 Operating System/400 S/390 VisualAge WebSphere

Lotus, Lotus Notes, and Domino are trademarks or registered trademarks of the Lotus Development Corporation in the United States, or other countries, or both.

Tivoli Management Environment, TME 10, and Tivoli Module Designer are trademarks of Tivoli Systems Inc. in the United States, or other countries, or both.

Encina and DCE Encina Lightweight Client are trademarks of Transarc Corporation in the United States, or other countries, or both.

Microsoft, Windows, Windows NT, and the Windows logo are trademarks or registered trademarks of Microsoft Corporation in the United States, or other countries, or both.

Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.

UNIX is a registered trademark in the U.S. and other countries licensed exclusively through X/Open Company Limited.

ActionMedia, LANDesk, MMX, Pentium and ProShare are trademarks or registered trademarks of Intel Corporation in the United States, or other countries, or both.

Other company, product, and service names, which may be denoted by a double asterisk(**), may be trademarks or service marks of others.

Notices vii viii Getting Started Chapter 1. Introduction

The purpose of the Getting Started guide is to introduce you to the basic VisualAge for Java concepts and terms that you need to understand to use a visual programming tool, and the fundamentals required to create a Java application with VisualAge for Java.

The primary focus of this document is to help you start programming in Java — quickly and easily — with the VisualAge for Java visual development environment. To achieve this goal, this document is divided into two sections: v An introductory section that discusses the basic operation of VisualAge for Java. v A guided tutorial section that provides how-to instructions for creating simple applets and applications.

The introductory section is designed to provide a high-level view of VisualAge for Java’s capabilities. This portion of the Getting Started guide can be read anywhere. You do not need to have VisualAge for Java installed and running.

The tutorial section is designed to help you put the conceptual information to use. Once you are aware of what you can do with VisualAge for Java, you can use the samples to acquire a hands-on introduction to the program and begin developing your own projects. These samples are relatively simple applications and are not intended to provide an in-depth analysis of the Java language or the advanced aspects of the VisualAge for Java program. The primary focus of the tutorial is to get you started with VisualAge for Java and develop a foundation from which you can proceed to the detailed information included in the online documentation that comes with the program.

Who this document is for

This document is written for programmers who want to become familiar with VisualAge for Java and develop Java applications visually. It introduces you to the basic concepts behind building programs in a visual development environment, explains the general process of visual programming with VisualAge for Java, and walks you through development of two sample programs. To get the most out of this document, you should already be familiar with the basics of the Java language.

How to use this guide

To bring the two halves of the Getting Started guide together, we have included cross-references between introductory material and tasks in the tutorial section. In the online version of the tutorial section, arrows in the bottom right corner of each topic will move you step-by-step through the tutorial. If you are using the tutorial in book format, the topics are laid out in consecutive order. Depending upon your preferred method of learning, you may want to refer back to the related concepts section of the guide when trying the steps in the tutorial; or you may simply read one section, then another.

Sample programs in this document

By doing the exercises in this document, starting with “Building your first applet”, you can create a sample program called “To-Do List”. A completed version of this applet, called “com.ibm.ivj.examples.vc.todolist”, is included with the IBM Java

© Copyright IBM Corp. 1997, 1999 1 Examples project shipped with VisualAge for Java. See “Getting samples from the repository” for details on how to view the completed version of this example.

In “Data access beans in action”, you can use the sample database shipped with DB2 Universal Database to build a simple query program called StaffList.

Conventions used in this document

The following typographical conventions are used in the text:

Highlight style Used for Boldface Items you can select, such as buttons and choices Italics Special emphasis Examples of Java code Monospace font Text that you can enter, method names in code samples

What’s new in this release

Finding out more about VisualAge for Java

Getting the latest VisualAge for Java information

What is VisualAge for Java

What’s new in this release

Version 3.0 of VisualAge for Java includes the following changes.

Professional and Enterprise Editions v The Stored Procedure Builder, for creating stored procedures that run on remote relational databases v Additional data access beans for creating, reading, updating, and deleting data and for accessing stored procedures v Support for SQLJ v Customizable browsing and enhanced code assist features in the IDE, including macro support v Contextual help for Java keywords and program elements v Distributed debugger for Java applications that run across different environments v Enhanced integrated debugger v Performance improvements to code generated by the Visual Composition Editor v Other enhancements to the Visual Composition Editor, including improved property editor support and Null-to-GridBag layout converter v JDK updated to version 1.2 v JFC updated to version 1.0.3 v Extensions to the Tool Integrator API, allowing for remote access, so that tools can now run outside the IDE v Quick forms, a quick and easy way to lay out a GUI panel that corresponds to the properties of a nonvisual bean.

2 Getting Started For more information about enhancements to VisualAge for Java, refer to the product Web site at http://www.ibm.com/software/ad/vajava

What is VisualAge for Java

Finding our more about VisualAge for Java

Getting the latest VisualAge for Java information

Printing online help topics

You can print any topic in the comprehensive online help that is included with the VisualAge for Java program.

To print a topic, do the following: 1. Display the help topic you want to print. 2. Select the content (the bottom-right frame) by clicking mouse button 1 on the frame. 3. Select Print Frame from the .

To print all information about a topic, use the files found in the PDF Index.

To change the default printer: 1. Select the File menu in any window. 2. Select Print Setup.

Modify the settings in the Print Setup as required.

Printing program elements

Finding out more about VisualAge for Java

Getting the latest VisualAge for Java information

Chapter 1. Introduction 3 4 Getting Started Chapter 2. Getting started

What is VisualAge for Java?

VisualAge for Java is an integrated visual environment that supports the complete cycle of Java program development. In particular, VisualAge for Java gives you everything you need to visually develop Java programs.

Rapid application development

You can use VisualAge for Java’s visual programming features to quickly develop Java applets and applications. In the Visual Composition Editor, you point and click to: v Design the user interface for your program v Specify the behavior of the user interface elements v Define the relationship between the user interface and the rest of your program

VisualAge for Java generates the Java code to implement what you visually specify in the Visual Composition Editor. In many cases you can design and run complete programs without writing any Java code.

In addition to its visual programming features, VisualAge for Java gives you SmartGuides to lead you quickly through many development tasks, including: v Creating new applets. v Creating new program elements. In VisualAge for Java, a program element is one of the following: – Project: the top-level program element in VisualAge for Java. A project contains packages. – Package: the Java language construct. Packages contain classes and interfaces. – Class: the Java language construct. Classes contain methods and fields. – Interface: the Java language construct. Interfaces contain methods and fields. The fields in interfaces must be static final fields. – Method: the Java language construct. v Creating features for JavaBeans. v Importing code from the file system and exporting code to the file system.

Create industrial-strength Java programs

VisualAge for Java gives you the programming tools that you need to develop industrial-strength code. Specifically, you can: v Use the completely integrated visual debugger to examine and update code while it is running v Build, modify, and use JavaBeans v Browse your code at the level of project, package, class, or method

Maintain multiple editions of programs

© Copyright IBM Corp. 1997, 1999 5 VisualAge for Java has a sophisticated code management system that makes it easy for you to maintain multiple editions of programs. When you want to freeze the state of your code at any point, you can version an edition and apply a name or number that specifically identifies it.

What’s new in this release

Finding out more about VisualAge for Java

Getting the latest VisualAge for Java information Starting VisualAge for Java

You can start VisualAge for Java by doing one of the following:

From the Start menu, select Programs, the IBM VisualAge for Java folder, and then IBM VisualAge for Java .

In the VisualAge for Java folder on the desktop, click the IBM VisualAge for Java icon.

When you first start VisualAge for Java, Enterprise Edition, you will be prompted to choose an owner for your workspace and a network name for the user called Administrator. For the purposes of these exercises, you can select Administrator as your workspace owner. For a network name, use the name that identifies your computer to your network. For more information on the team programming environment, see the Getting Started document for VisualAge for Java, Enterprise Edition.

After you start VisualAge for Java, the Workbench opens.

6 Getting Started Next, the Welcome to VisualAge dialog box appears:

The Welcome to VisualAge dialog box provides a fast path to creating applets, classes, and interfaces.

Click the Go to the Workbench and click OK.

Chapter 2. Getting started 7 Tip: Another useful window that helps you accomplish common tasks quickly and easily in the IDE is the Quick Start window. It includes tasks for creating program elements, learning to use the Scrapbook, managing the repository, and adding samples and useful beans to your workspace. You can launch it any time by pressing F2 or selecting QuickStart from the File menu in any IDE browser. For more information, see The Quick Start window.

The Workspace and the Repository

The Workspace and the Repository

VisualAge for Java is a complete, integrated environment for creating Java applications and applets. The interactive visual programming tools and a set of JavaBeans available in the Workbench represent common interface components. You create programs by assembling and connecting beans on the free form surface. In many cases, you may not even have to write code. When you do need to write code, VisualAge for Java provides a state-of-the-art, integrated development environment in which to do your coding.

Development with a repository

Within the VisualAge for Java environment, you do not manipulate Java code files. Instead, VisualAge for Java manages your code in a database of structured objects, called a repository. VisualAge for Java shows code to you as a hierarchy of program elements:

project

package

class or interface

public, default, protected, private methods

Because you are manipulating program elements rather than files, you can concentrate on the logical organization of the code without having to worry about file names or directory structures.

Comparing the workspace to the repository

All activity in VisualAge for Java is organized around a single workspace, which contains the source code for the Java programs that you are currently working on. The workspace also contains all the packages, classes, and interfaces that are found in the standard Java class libraries and other class libraries that you may need.

All code that you write and save in the workspace is also stored in a repository. Code generated by VisualAge for Java is automatically stored in the repository. In addition to storing all the code that is in the workspace, the repository contains other packages that you can add to the workspace if you need to use them.

8 Getting Started In VisualAge for Java, you can manage the changes that you make to a program element by creating editions, or versions, of the program element. The workspace contains, at most, one edition of any program element. The repository, on the other hand, contains all editions of all program elements.

The Workbench

Exploring the Repository The Workbench

The Workbench window provides menu and access to commands, and displays different views of your workspace in pages. All page views in the Workbench are divided into two sections: a Browse pane and a Source pane. The Browse pane of a page displays a hierarchical tree structure of the current view. The Source pane displays the code content of the currently selected component in the Browse pane.

In the Enterprise Edition, the current user of the Workbench is listed on the title bar.

The default orientation of the panes is horizontal. To change the orientation of the panes within the Workbench windows, select Flip Orientation from the Window menu.

There are five page views available in the Workbench: v Projects v Packages v Classes v Interfaces v All Problems

Chapter 2. Getting started 9 To access a view in the Workbench, click the page that corresponds to the view of your choice.

Menus and in the Workbench

The menu and toolbar selections available to you are determined by the currently selected Workbench . You can access a menu by: v right-clicking with your mouse on any part of a Workbench view tab v pointing to and clicking a menu item on the

The Workbench Tool bar

The Workbench tool bar, located below the menu bar, gives you easy access to the tasks you perform most frequently in the Workbench. These tasks include: v standard editing operations v running an application or applet v debugging v searching for code v manipulating program elements

To identify any tool in a tool bar, place the mouse pointer over the tool. A yellow tool will appear that identifies the tool.

The Workspace and the Repository

Pages in the Workbench window Pages in the Workbench window

Each page in the Workbench provides a specific viewpoint on the code in the workspace.

The Projects page

The Projects tab displays the list of projects in your workspace. VisualAge for Java uses projects to organize code in a hierarchical tree format similar to a file manager. You can expand projects to see the program elements inside them. When you create an applet or application with VisualAge for Java, you must select or create a project to which the applet/application will belong.

In addition to any projects you create, the Projects Tab also displays five default projects that are added to the workspace when you install VisualAge for Java: v IBM Java Implementation v Java Class Libraries v JFC Class Libraries v Sun Class Libraries PM Win32

All of these projects contain packages which are necessary for the correct functioning of VisualAge for Java. You cannot delete or modify the code in any of the default packages.

10 Getting Started The Packages tab

The Packages tab contains three browse panes which display: v All Packages: all packages in the currently selected project v Types: classes in the currently selected package v Methods: methods in the currently selected class and a Browse pane which displays the source code related to the currently selected package, class, or method. You can expand packages to see the program elements inside them. You can also customize your view of your packages by selecting Layout from the Packages menu.

The Classes tab

The Classes page displays all classes in the workspace in three panes: v Class Hierarchy: the hierarchy of classes in the currently selected package or class v Methods: methods in the currently selected class v Source: the code in the currently selected class or method

You can display the hierarchy as a list or as a graphical view and expand a class to see what classes inherit from it. To quickly find a class, you can select Go Tofrom the Classesmenu and type as many letters of the class name required to display the class in the list.

The Interface tab

The Interfaces page displays interfaces in the workspace. The Interfaces page is indentical to the Classes page except that it displays interfaces in an interface pane rather than classes. Methods and source code are displayed in separate panes.

The All Problems tab

The All Problems page displays all the classes and methods in the workspace that contain unresolved problems and incorrect code. When a problem is found within your code, the method containing the error is flagged with a red X. The method’s class is marked with a grey X. If the errors are within a class or interface, the class or interface is also marked with a red X.

If it can, VisualAge for Java will suggest solutions to any errors it finds. When you save your code, VisualAge for Java compiles it automatically and, if errors are found for which it may have a solution, suggestions are provided in a Warning dialog box. You will have the option of selecting an appropriate correction to the error, saving the code with the error in it, or cancelling the save altogether to edit your errors on your own.

The Workbench

Navigating

Browsing

Chapter 2. Getting started 11 Customizing your workspace

You can customize the of VisualAge for Java to suit your tastes and needs. By modifying things like program operation options and window orientation, the appearance and behaviour of your Workbench can be changed to reflect your development requirements.

Customization of your workspace in VisualAge for Java includes the following: v IDE customization options that can be used to change how the Integrated Development Environment looks and operates. v Workbench customization that indicate how the Workbench displays information.

Changing customizable options

To change a customizable option: 1. Select Options from the Window menu. The options dialog box will open displaying a list of customizable options in a tree structure. You can click the plus sign (+) beside an option to expand the option. 2. Click the option you want to change. 3. Change any of the displayed program characteristics by using any of the elements provided: check boxes, radio buttons, text boxes, or list boxes. 4. Click Apply to put your changes into effect. If you change your mind about a change you have made and want to return all options to the default settings, click the Default button. 5. Click OK to save your changes and exit (or click Cancelto discard all changes and exit).

IDE customization options

Workbench customization

The Workbench

Pages in the Workbench window

12 Getting Started IDE customization options

You can customize the IDE by changing the settings in the Options window.

The following table describes the options that you can customize. For more information on any of these options, open the Options window and press F1 to display the context sensitive help.

Option Use this to set options for ... General miscellaneous IDE behaviour. memory management. Cache shortcut key sequences enabled throughout the product. Key Bindings Appearance lists, source code, dialogs, banners, and printer output appear, including color, size, and font. Coding tab space settings and program operation when saving code.

Chapter 2. Getting started 13 how VisualAge for reports compiler errors. Compiler enabling and defining the behaviour of Code Assist. Code Assist how the integrated debugger operates. Debugging the automatic code formatter’s method of displaying code in Formatter Source panes. automatic indentation of new lines of code that you create. Indentation automatic completion of Java syntax in source code. Keyword completions Code Assist macros currently defined for the IDE. Macros how standard Javadoc comments will be generated for each new Method Javadoc method and type. Type Javadoc Help which web browser is used to display online help information and the tips and warning that will be displayed. Resources class paths (used by programs running in the workspace to find the resource files and classes they need). associate a resource type with an external program or Java class. Resource Associations remote method invocation (RMI) operation. RMI Registry Visual Composition BeanInfo support and design time class path information for the Visual Composition Editor. generating event handling code and metadata for visually Code generation composed beans. registering Quick Forms for use in the Visual Composition Editor. Quick Form Manager Remote Access to Tool setting up remote access to the Tool API API

Workbench customization Workbench customization

You can customize the Workbench while you are working to display windows and panes in different ways. Because the Workbench simultaneously displays a variety of information in different locations, you may want to modify how that information is displayed to focus on a specific area. Note that your workspace will be saved when you exit VisualAge for Java. The next time you start the program, the Workbench will display with all of the customizations that were in effect when you exited the program.

To customize the Workbench display to ... From the Window menu ...

display a vertical pane instead of a select Flip Orientation horizontal pane

14 Getting Started create a second instance of the Workbench select Clone

move between multiple instances of the select Switch To Workbench

select and view only one pane in a select Maximize Pane multi-pane window

return to multiple panes from a single-pane select Restore Pane view

display the version number beside each select Show Edition Names component

IDE customization options Navigating

VisualAge for Java provides many different ways to look at your code. To switch between the available views, you just move from one window to another. Moving between windows

Every window in VisualAge for Java has a Window menu that provides v a Go Tooption v an Open Tooption v a Cloneoption v a Switch Tooption.

You can move between windows and views of your code by selecting any of these options from the Window menu.

If you select an Open To, Go To,orCloneoption for a window that is already open, the selected window becomes the active window. Select Switch To in the Window menu provides access to any of the windows that are currently open.

Recently-used windows are stored in a list in the File menu. If you want to open a recently closed window, select it from the list in the File menu.

Some windows are automatically opened by VisualAge for Java as you perform your development tasks. For example, if you run a program that contains an active breakpoint, the Debugger window will open when the breakpoint is reached.

You can open the following windows from the Window menu: v Console v Log v Scrapbook v Repository Explorer v Debugger

Chapter 2. Getting started 15 The Window menu also allows you to: v Clone: open a duplicate of the current window. You can then browse the two windows independently. Changes made to program elements are reflected in both windows. v Lock: lock the current window to keep it open. If you try to close the window, a message box informs you that the window is locked. You must unlock the window before you can close it. v Maximize: resize the current window so that it covers the desktop. v Orientation: change the general layout of the panes in the window. The images in this information, for example, show the horizontal orientation, which, in the IDE, you can optionally change to a vertical orientation. v Show Edition Names: enable or disable edition name labels for program elements. v Workbench: open (or brings into focus) the Workbench browser.

Pages in the Workbench window

Exploring the repository

Browsing

Searching Searching

VisualAge for Java makes it easy for you to find program elements and to move around within the integrated development environment. This section tells you how to take advantage of the search features in the IDE. Searching for a program element

The IDE gives you several choices when searching for program elements. In the Projects page, you can move from one package to another, one project to another, by entering the first letter of the package or project name. For example, if the currently selected project is called Java Class Libraries, and the next project is called Sun BDK Examples, enter S on your keyboard to move to the Sun BDK Examples project. Alternatively, you could press the down arrow to move the same distance.

Searching with the Search dialog

You can use the Search dialog to perform powerful searches in the workspace. To open the Search dialog, use any one of the following methods: v Select Search from the Workspace menu of any window. v Select text in a Source pane, and then Search from the .

v Select the Search button from any window’s tool bar.

This opens the Search dialog. If you selected text or a program element before launching the search, the Search string field will contain that text or the name of the program element when the Search dialog opens.

16 Getting Started Select the type of program element you want to search for, the scope of the search, and the usage of the element, by enabling the appropriate radio buttons. Click Start. When the search is complete, and if a match is found for the criteria you selected, the Search Results window will open.

In the Search Results window, you can browse and modify the contained program elements, and rerun your search. Searching for references and declarations

The pop-up menu for types and methods contains access to searches specific to those types and methods. For example, if you right click a method and select Workspacefrom the References Tomenu, VisualAge for Java will search for all references to that method in the workspace. If you right click an interface and select This Typefrom the References Tomenu, you can search for references to the

Chapter 2. Getting started 17 interface within the workspace. The Declarations Of search options search for declarations of the selected program element. Results of the search are displayed in the Search Results window. Searching from the Workspace menu

You can search for a program element by selecting one of the Open options from the Workspace menu (Open Project Browser, Open Package Browser, Open Type Browser). For example, if you select Open Type Browser from the Workspace menu, the Open Type dialog opens.

If you enter string in the Pattern field, the Type Names list refreshes to show only the classes and interfaces that match the text you have entered. Select String from the Type Names list and select OK to open a browser displaying the String class. For type names that exist in more than one package, you must select both the type name and the package name from the Package Names list at the bottom of the Open Type dialog box. Searching for a program element within a browser page

If you want to find a program element that you know is contained in the current browser page, select Go To (for example, Go To Class)fromthe pop-up menu. You can also click Selected on the main menu and select Go To to choose a Project, Package or Type to go to. For example, if you are in the Projects page of the workbench, and you want to find the java.lang.String class, Select Go To and then Type from the Selected menu. In the Go To Type dialog, enter string in the Pattern field; select String from the type list, and java.lang from the package list. When you click OK, the IDE will go to and select the java.lang.String class in the All Projects pane in the Workbench.

Navigating

18 Getting Started Browsing

Pages in the Workbench window Browsing

VisualAge for Java provides extensive facilities for browsing program elements. To open a program element in VisualAge for Java: v Select the program element and select Open from the Selected menu or from the pop-up menu for the program element. v Select the appropriate browser in the Workspace menu (Open Type Browser, Open Package Browser,orOpen Project Browser) for the program element. A secondary window appears that lists all the classes and interfaces, packages, or projects in the workspace. Enter the name of your program element and select OK.

When you open a program element, a window opens that displays information about this program element.

Browsing a project

When you open a project, a window with five tabs is displayed.

v The Packages tab displays the hierarchy of packages contained in this project. v The Classes tab displays the hierarchy of classes contained in this project. v The Interfaces tab displays the interfaces contained in this project. v The Editions tab displays all the editions of this project. v The Problems tab lists all program elements in the project that contain errors.

Browsing a package

When you open a package, a window with four tabs is displayed.

Chapter 2. Getting started 19 v The Classes tab displays the hierarchy of classes contained in this package. v The Interfaces tab displays the interfaces contained in this package. v The Editions tab displays all the editions of this package. v The Problems tab lists all program elements in the package that contain errors.

Browsing a class

When you open a class, a window with five tabs is displayed.

v The Methods tab displays the methods contained in this class.

20 Getting Started v The Hierarchy tab displays the position of the class in the overall class hierarchy. v The Editions tab displays the editions of this class. v The Visual Composition tab displays the Visual Composition Editor. v The BeanInfo tab displays information about the JavaBeans-specific interface for this class.

Browsing an interface

When you open an interface, a window is displayed with two tabs.

v The Methods tab displays the methods contained in this interface. v The Editions tab displays the editions of this interface.

Browsing a method

When you open a method, a window with two tabs is displayed.

Chapter 2. Getting started 21 v The Source tab lists the source for the method. v The Editions tab displays the editions of this method.

Pages in the Workbench window

Navigating

Searching Debugging

VisualAge for Java includes an integrated visual debugger that displays running threads and the contents of their run-time stacks. In the Debugger you can suspend and resume execution of threads, inspect and modify variable values, and set, remove, and configure breakpoints.

22 Getting Started Opening the debugger

You can open the debugger manually by selecting Debug and then Debugger from the Window menu. If a program is running, you can suspend its thread and view its stack and variable values. Alternatively, the debugger will automatically open, with the current thread suspended, for any of the following reasons: v A breakpoint in the code is encountered. v A conditional breakpoint that evaluates to true is encountered. v An exception is thrown and not caught. v An exception selected in the Caught Exceptions dialog is thrown. v A breakpoint in an external class is encountered.

Setting breakpoints

When a program is running in the IDE and encounters a breakpoint, the running thread is suspended and the Debugger browser opens so that you can work with the method stack and inspect variable values. In the IDE, you can set breakpoints in any text pane that is displaying source code. To set a breakpoint in a method: 1. select the method in the Workbench 2. double click mouse button 1 margin of the Source pane beside the line at which you want the break to occur

Chapter 2. Getting started 23 A breakpoint indicator appears in the margin of the Source pane beside this line:

Alternatively, you can move the cursor to the line and click mouse button 2. Select Breakpoint from the pop-up menu.

Removing breakpoints

To remove a breakpoint in a source pane, double-click on the breakpoint indicator. You can also remove a breakpoint by following these steps: 1. Move the cursor to the line. 2. Click mouse button 2 and select Breakpoint from the pop-up menu.

Navigating

Searching

Browsing

The Distributed Debugger

Setting a breakpoint in the writeToDoFile class

Using the Scrapbook to test code The Quick Start window

Several of the most frequent tasks you will perform in the IDE are collected in an easy-to-access window called Quick Start. To open the Quick Start window, select Quick Start from any IDE window’s File menu, or press F2.

24 Getting Started The list on the left-hand side of the window displays Quick Start task categories. To see the tasks belonging to a category, click on the category. Related tasks will be listed on the right side of the window. To start a task, select it and click OK.

Basic tasks

Basic tasks create program elements. Selecting one of the basic tasks launches the appropriate SmartGuide that will help you create applets, classes, interfaces, projects, and packages.

The Experiment with Code task opens a page in the Scrapbook. The page provides introductory instructions that describe what the Scrapbook can do and guides you through the basic steps to evaluate code and variable values in the Scrapbook.

Team development tasks

The team development tasks provide you with easy access to projects in the repository. Also, a team administrator can administer users. The Management Query option lets you search for program elements based on status, owner, or developer.

Repository management tasks

The Compact Repository task lets you duplicate the current repository, leaving out purged and opened editions.

You can use the Change Repository option to connect your workspace to another repository (shared or local), or to recover if the server fails.

Features tasks

With the Add Feature and Remove Feature options, you can add projects to your workspace that are provided with VisualAge for Java, but are installed as part of

Chapter 2. Getting started 25 the repository. These projects include IDE samples and Data Access Beans. A secondary window provides a list of available projects (features) that you can add to or remove from your workspace.

Starting VisualAge for Java

Importing and exporting code

Using Quick Start and a SmartGuide to create your applet The Log

The Log window displays messages and warnings generated by VisualAge for Java.

You can use the Log window as part of your debugging process or as a general “mailbox” in which you can view messages sent to you by the IDE. For applications that carry out operations which are not visual (for example, if your applet connects to a database) you can use the Log window to look “behind-the-scenes” and determine whether the database connection was successful.

Log window output can be shared with other developers when searching for solutions to code problems. Information displayed in the Log window can be cut and/or copied to any application that accepts information from the Windows clipboard or sent directly to a printer.

The Scrapbook

Debugging

Navigating

The Console

26 Getting Started The Scrapbook

The Scrapbook provides a place for you to test small portions of code. You can enter and run code fragments without making them a part of any package, project, or class.

Navigating

Searching

Browsing

Debugging The Console

The Console window sets up communication between you and your code. With the Console, you can exchange information with the standard input/output of the operating system, sending data into your applications and receiving data from your applications. For example, the following code

System.out.println(“Hello, World!”);

prints the string “Hello, World!” to the standard output of the operating system. This output will be displayed in the Console window.

Chapter 2. Getting started 27 The following method allows you to enter a text string in the Standard In pane of the Console window. When you press Enter, the text string will be displayed in the Output window.

public TestSystemIn() { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String theLine = null; try { theLine = in.readLine(); } catch (IOException e) { e.printStackTrace(); } System.out.println(theLine); }

If there are multiple threads available for standard input, you can select the thread that you want to test and provide input using the Console.

The Console also displays errors, exceptions, and any of the problems that may be encountered when you attempt to run your applications or any code that you’ve

28 Getting Started entered into the Scrapbook. You can review the output from the Console to help you identify what went wrong and decide where to begin debugging your code.

The Log

Navigating

Searching

Browsing

Debugging The Visual Composition Editor

The Visual Composition Editor is the visual programming tool integrated with VisualAge for Java. You can develop programs by visually arranging and connecting software objects called JavaBeans (or simply beans). You can also link visual events, such as clicking a button, with any code that you create. This process of creating object-oriented programs by manipulating graphical representations of components is called “visual programming”.

The Visual Composition Editor is made up of several components: v the beans palette along the left side v the status area along the bottom v the tool bar along the top v the free-form surface where you lay out the beans you select from the beans palette.

In the diagram below, three beans are on the surface: a check box bean and two radio button beans.

Chapter 2. Getting started 29 You use the Visual Composition Editor to construct new beans. These new beans can contain other beans as well as connections between beans. You can think of the beans you construct in the Visual Composition Editor as composite beans because they contain other beans. The composite beans you build make up your program.

Beans palette

The beans palette, located on the left side of the Visual Composition Editor, contains a set of common, ready-made beans. These beans are organized into four categories: v v AWT v Available v Other

30 Getting Started The status area at the bottom left of the Visual Composition Editor indicates the currently selected bean and the category it belongs to. You can also identify a bean by placing the mouse pointer over the bean. A yellow label will appear identifying the bean.

The Visual Composition Editor tool bar

The tool bar, located below the menu bar of the Visual Composition Editor, provides easy access to the tools commonly used while manipulating beans. These tools help with such tasks as positioning beans, sizing beans, showing and hiding connections between beans, and testing your program. Most of the tools on the tool bar act on the beans that are currently selected in the free-form surface. If no beans are selected for a tool to act on, the tool is unavailable. Note that all tools represented on the tool bar can also be accessed using the Tools menu.

The free-form surface

The free-form surface, which is located on the right side of the Visual Composition Editor, is the area where you construct your program. To add beans to the free-form surface, you select a bean from the palette and click on the free-form surface to “drop” the bean. Note that you cannot drop nonvisual beans on top of visual beans.

Chapter 2. Getting started 31 Regardless of the type of bean, every bean has a pop-up menu that contains options you can use to modify or work with that bean.

Beans

Connections

Using Quick Start and a SmartGuide to create your applet

Exploring the repository

As part of its suite of tools, VisualAge for Java provides a Repository Explorer. The Repository Explorer adds a visual interface, similar to a file manager, to your repository, providing a graphical view of all editions of all of your program elements (including all the program elements that are currently in the workspace).

To view the Repository Explorer, select Window > Repository Explorer from the menu.

Within the Repository Explorer, you can open and/or compare program elements that are stored in the repository without swapping editions in and out of the workspace.

By comparing different editions, you can see the following: v Changes that have been made as a result of code generation. v The differences between an edition with errors and a bug-free edition.

To compare two editions of a package:

32 Getting Started 1. Select the Repository Packages page. 2. Select a package in which you have two or more editions from the Package Names list. 3. From the Editions list, hold down mouse button 1 and drag-select the top two editions. From the Editions menu, select Compare. The Comparing window appears.

4. Select a class or method name in the Element pane, and you’ll see two sets of corresponding code in the text panes below. Here, you can compare the two program elements. From the Differences pull-down menu, you can select Next

Difference and Previous Difference. You can also select the arrows in the upper right corner of the window to move back and forth in the list of differences.

All program elements that are in the workspace are indicated by an asterisk (*).

The Workbench

Versions and editions

Importing and exporting code

Getting samples from the repository

Chapter 2. Getting started 33 34 Getting Started Chapter 3. Beans

In VisualAge for Java, beans are the components that you manipulate when you program visually. These beans are Java classes that adhere to the JavaBeans specification. In the Visual Composition Editor, you select beans from a palette, specify their characteristics, and make connections between them. Beans can contain other beans and connections to beans. For more information on the role of beans in VisualAge for Java, see “ Support for JavaBeans components”.

You use two types of beans within the Visual Composition Editor: v A visual bean can be seen in your program at run time. Visual beans, such as windows, buttons, and text fields, make up the (GUI) of a program. v A nonvisual bean does not appear in your program at run time. A nonvisual bean typically represents an object that encapsulates data and implements behavior within a program.

A bean’s public interface determines how it can interact with other beans. The public interface of a bean consists of the following features: v Properties: data that can be accessed by other beans. This data can represent any logical property of a bean, such as the balance of an account, the size of a shipment, or the label of a button. v Events: signals that indicate something has happened. Opening a window or changing the value of a property, for example, will trigger an event. v Methods: operations that a bean can perform. Methods can be triggered by connections from other beans.

The Visual Composition Editor

Connections

Changing bean properties

Adding labels and text boxes

Adding the Add and Remove buttons

Adding the Open and Save buttons

Adding and Setting the Select bean

© Copyright IBM Corp. 1997, 1999 35 Support for JavaBeans components

VisualAge for Java includes support for JavaBeans components. This section gives you a very brief introduction to JavaBeans components and some details on how VisualAge for Java supports them.

What Are JavaBeans components?

JavaBeans components are Java objects that behave according to the JavaBeans specification. JavaBeans components (or, more simply, beans) are reusable software components that you can manipulate in a development environment like VisualAge for Java. The method signatures and class definition of a bean follow a pattern that permits environments like VisualAge for Java to determine their properties and behavior. This ability for a beans-aware environment to determine the characteristics of a bean is called introspection.

Bean features

A bean exposes a feature when it makes that feature available to other beans. Beans have three kinds of features:

v events

v methods

v properties.

Events are the events that the bean causes to occur. Other beans can register their interest in these events and be notified when they occur.

Methods are actions that a bean exposes for invocation by other beans. Bean methods are a subset of the public methods of the Java class that constitutes the bean.

Properties are the attributes exposed by a bean. Properties can be read, written, or both. Properties can have the following characteristics: v A bound property triggers the propertyChange event when its value is changed. v A constrained property allows other beans to determine whether the value of the property can be changed (triggers the vetoableChange event). v An indexed property is an array, so it exposes additional methods to address individual elements. v A hidden property is not visible to humans. It is for use by bean-aware tools only. v An expert property should only be manipulated by expert users. v A normal property is one that is neither hidden nor expert.

BeanInfo classes

Beans can have accompanying BeanInfo classes. These classes explicitly describe the events, methods, and properties that a bean exposes. VisualAge for Java can generate BeanInfo classes for your beans. The BeanInfo class has the same name as the bean with the suffix -BeanInfo.

36 Getting Started The BeanInfo class contains public methods that return information about the bean, including the class of the bean, the name of the class of the bean, and details about the events, methods, and properties of the bean.

The BeanInfo Page

The Visual Composition Editor

Manipulating beans The BeanInfo page

In VisualAge for Java, you manipulate the characteristics of a bean in the BeanInfo page of the class browser.

The top left pane lists the features of the bean. You can specify the kinds of features the BeanInfo page shows by selecting an entry under Show in the Features menu. The following groups of features are available:

All features in the bean, including features that were generated by All VisualAge for Java Normal Features you explicitly defined for the bean Property Properties Event Events Method Methods Hidden Hidden features

Chapter 3. Beans 37 Expert Expert features

When you select a feature, VisualAge for Java lists information in the top right pane depending on what kind of feature is selected:

Event Interface, listener methods, add listener method, remove listener method Property Type, read method, write method Method Signature

The top right pane lists the program elements that are associated with the selected feature. If you select one of the program elements, its source is displayed in the bottom pane.

If you do not select a program element in the upper right pane, the bottom pane lists the bean information for the selected feature, including its description, display name, and whether or not it is expert or hidden.

Using the BeanInfo page

How would you use the BeanInfo page to create and manipulate the features of a bean? The package com.ibm.ivj.examples.vc.customerinfo is an example that makes use of property features. For instance, the Address class has properties for street, city, state, and ZIP code. You can find this sample in the IBM Java Examples project.

For instructions on how to build this sample, go to the product documentation. Select Samples from the search bar. From the navigation pane, select Visual Composition and then CustomerInfo.

Beans

Support for JavaBeans components

Manipulating beans

Connecting beans

Getting samples from the repository Manipulating beans

As you develop an applet, you may want to move beans around the free-form surface to improve the appearance of your user interface. You can also align beans, change their size, or copy an existing bean to use it in the creation of a new bean. Selecting beans

To select a bean, click on it with mouse button 1.

38 Getting Started When you select a bean, small, solid boxes called selection handles appear in the corners of the bean to assist you in manipulating that bean.

Beans that cannot be sized do not have selection handles. Instead, these beans change their background color when they are selected. Beans with this behavior include nonvisual beans and menu beans.

If other beans are selected when you select a bean, they will be deselected automatically. This is referred to as “single selection”. The name of the bean currently selected is displayed in the status area at the bottom of the Visual Composition Editor. Selecting several beans

If several beans are selected, the last one selected has solid selection handles indicating that it is the anchor bean. The other selected beans have hollow selection handles.

The anchor bean is important when performing operations such as bean sizing and alignment. The other selected beans set their position or size to the position or size of the anchor bean. You can change the anchor bean by holding the shift key and selecting the bean you want to be the anchor.

To select several beans, do one of the following: v Click mouse button 1 on one of the beans you want to select, then hold down the Ctrl key and click mouse button 1 on each additional bean you want to select. Remember, the last bean selected becomes the anchor around which sizing and alignment operations take place. v On the UNIX and OS/2 platforms, you can instead click and hold mouse button 1 on a bean. Move the mouse pointer over each additional bean you want to select. After you have selected all the beans you want, release mouse button 1.

When multiple beans are selected, the status area displays the number of beans selected (for example, 3 beans selected). Deselecting beans

To deselect all the beans currently selected, click mouse button 1 on another bean or in an open area of the free-form surface.

To deselect one bean from a group of beans that have been selected, hold down the Ctrl key and click with mouse button 1 on the bean you want to deselect. If the bean you deselected was the anchor bean, the previously selected bean will become the anchor bean. Moving beans

To move beans, follow these steps: 1. Click and hold with the appropriate mouse button on the bean: v In OS/2, hold down mouse button 2.

Chapter 3. Beans 39 v In the UNIX platforms, hold down the middle mouse button. v In Windows, hold down mouse button 1. 2. Move the mouse pointer to the location at which you want to position the bean and release the mouse button.

You can move several beans at once by first selecting all of the beans you want to move. You can then grab any selected bean (by clicking on it with mouse button 1) and drag all the selected beans to their new location.

Beans

Sizing, aligning, and positioning beans

Adding labels and text boxes

Sizing and aligning visual beans in the To-Do List

Correcting mistakes Sizing, aligning, and positioning beans

Beans that are containers (such as a JApplet or a Frame) have a layout property. This property supports specific layout managers that control the positioning of beans within the container. Using a layout manager is the preferred way to create a complex user interface.

When creating simple user interfaces in the Visual Composition Editor, you can size, align, and position beans without a layout manager. If you use a layout, the Visual Composition Editor provides the tools described below for aligning and positioning beans. Note that after manually aligning beans as you wish, you can convert the layout to a layout manager (for example, GridBagLayout).

Sizing beans

To size a bean, follow these steps: 1. Select the bean you want to size. The selection handles display at each corner. 2. Drag any one of the selection handles using mouse button 1 to adjust the size of the bean.

Before you release the mouse button, an outline of the bean is displayed to show you the new size of the bean.

To size the bean in only one direction, hold down the Shift key while you drag a selection handle in a horizontal or vertical direction.

You can also use the constraints property in the bean’s Properties window to size the beans. For more information about Properties windows, see “Changing bean properties”.

40 Getting Started Aligning beans

To align beans with other beans in a layout, follow these steps: 1. Select the beans you want to align, ensuring that the last bean selected is the bean you want the others to align with. 2. Select one of the following alignment tools from the tool bar:

Align Left

Align Top

Align Center

Align Middle

Align Right

Align Bottom

Matching the dimensions of another bean

You can size beans to the same width or height as another bean. 1. Select the beans you want to match, ensuring that the last bean selected is the one you want the others to match. 2. Select one of the following sizing tools from the tool bar:

Match Width

Match Height

You can also match the dimensions of two or more beans by selecting them and then clicking mouse button 2. Select Layout and then Match Size from the pop-up menu that appears. You can select to match Width, Height,orBoth.

Distributing beans evenly

To distribute beans evenly within a composite bean that uses a layout, follow these steps: 1. Select the beans you want to distribute evenly. 2. Select one of the following distribution tools from the tool bar:

Distribute Horizontally

Distribute Vertically

To evenly distribute beans within an imaginary bounding box that surrounds the multiple-selected beans, follow these steps: 1. Multiple-select the beans you want to evenly distribute. A minimum of three beans must be selected.

Chapter 3. Beans 41 2. From the pop-up menu of one of the selected beans, select Layout and then Distribute. Then select one of the following: Horizontally In Bounding Box Evenly distribute the selected beans within the area bounded by the leftmost edge of the leftmost bean and the rightmost edge of the rightmost bean. Vertically In Bounding Box Evenly distribute the selected beans within the area bounded by the topmost edge of the topmost bean and bottommost edge of the bottommost bean.

There are two more selections in Distribute: Horizontally In Surface Distributes the selected beans in the same way as Distribute Horizontally from the tool bar. Vertically In Surface Distributes the selected beans in the same way as Distribute Vertically from the tool bar. Copying and deleting beans

After you add a bean, you can copy that bean instead of adding another one from the beans palette. Copying a bean is one method of adding multiple copies of the same bean. One obvious advantage to copying a bean is that you can make common modifications to one bean and simply duplicate it as often as needed. Copying a bean that has connections does not duplicate the connections.

To copy a bean, follow these steps: 1. Hold down the Ctrl key and select with the appropriate mouse button on the bean you want to copy. 2. Drag the mouse pointer to the position where you want the new bean and release the mouse button and the Ctrl key.

You can copy several beans at once by first selecting all the beans you want to copy. Then, hold the Ctrl key, grab any selected bean, and drag a copy of the beans to their new location.

Copying beans by using the clipboard

To copy beans by using the clipboard, follow these steps: 1. Select the bean or beans you want to copy. 2. From the Edit menu of the Visual Composition Editor, select Copy. 3. Then, from the Edit menu, select Paste. The mouse pointer becomes a cross-hair. 4. Move the mouse pointer to the location where you want to add the new bean or beans and click mouse button 1.

Deleting beans

To delete a bean, simply select it and press the Delete key, or select Delete from the bean’s pop-up menu.

42 Getting Started To delete several beans, multiple-select the beans you want to delete before performing the delete operation.

If you delete a bean that has connections to or from it, the bean and all of its connections are deleted. However, in this case, you are prompted to confirm whether you want to continue before the beans and connections are deleted. If you accidentally delete an item you wish to retain, simply select Undo from the Edit menu of the Visual Composition Editor.

Beans

Manipulating beans

Adding and setting the Select bean

Adding the Add and Remove buttons Changing bean properties

A Properties window provides a way to display and set the properties and other options associated with a bean or connection. In addition to bean-specific properties, you can set data validation and layout properties. Opening the properties window for a bean

To open the Properties window for a bean, do any of the following: v Double-click on the bean. v Select Properties from the pop-up menu for the bean.

v Select the bean and select Properties from the tool bar.

As long as the Properties window (shown below) is open, you can show the properties of another bean in the window by: v Selecting another bean v Selecting another embedded bean from the drop-down list at the top of the Properties window

Chapter 3. Beans 43 Bean property names and their values are displayed in a table format. How property values are changed depends on the property type itself. For a JTextField bean, for example, the value of the beanName property is a string and can be changed directly within a cell in the Properties window. Some property values can be changed by selecting from a drop-down list. Other bean property values (for example, color and font) can be changed through a dialog box displayed for that purpose.

To edit any bean property, open its Properties window and click on the value you want to change. If the value is a string or integer value, you can edit it directly. If the value is a color value, select the button in the value column to bring up the colors dialog box. If the value is a boolean, click on the cell in the value column of the table and select either True or False from the drop-down list.

After changing the properties of a bean, you can apply those changes in the following ways: v By selecting another entry in the Properties window v By closing the Properties window v By clicking on another bean or on the free-form surface

Beans

Manipulating beans

Changing bean colors and fonts

Adding a scrolling list Changing bean colors and fonts

You can customize your beans with the colors and fonts of your choice. If you are developing applets to be used on multiple platforms, you should carefully consider the effect of choosing colors and fonts that are different from the default system colors and fonts.

44 Getting Started If your applet will be used on multiple platforms, the colors and fonts of the beans must be available on all systems that will run your applet. When changing the colors of beans in your applet, it’s best to use only basic colors, since non-basic colors may appear differently on different platforms.

If you decide to change the font of a bean, ensure that the font you choose will be available on all the systems that will be running the finished program. For example, if you choose a particular font available in OS/2, the same font might not be available in Windows. You might also have problems with certain fonts if your applet will be run on systems that use code pages designed for languages other than English.

Changing the color of a bean 1. In the Visual Composition Editor, double-click on a JButton bean whose color you want to change. The Properties window appears. 2. To change the background color of a bean, select the value for the background property in the Properties window. Select the button that appears. The Backgound window opens:

The color scheme indicated depends on your workstation display settings. In this case, the RGB specification was used. 3. To alter the color, use the controls, or select Basic or System and choose a color. Then select OK.

Note: You cannot change the color of beans in menus.

Changing the font of a bean 1. In the Visual Composition Editor, double-click on the bean whose font you want to change. 2. In the Properties window that opens, select the value of the font property. Select the button that appears in the value column for font. The Font

Chapter 3. Beans 45 window opens:

3. From the Name drop-down list, select the font you want to use. 4. From the Style and Size lists, select the size and style you want to use. A sample of the font you have selected is displayed in the text area. You can type additional text in this area to see the appearance of various characters. 5. When you have finished specifying the font, select OK. The selected font is shown in the value column for font.

Note: Some beans, such as Menu beans, may not support the changing of fonts depending on the target platform.

Beans

Manipulating beans

Connecting beans Connecting beans

You use connections to make things happen in your applet or application. Connections can be used for both visual and non-visual beans, and the type of connection you need to use is determined by the type of action you want to produce. For example, if you create a connection between a button bean and a piece of code that does something when the button is clicked, the connection required would be an event-to-code connection.

There are six types of connections in VisualAge for Java: Property-to-property Property-to-property connections link two data values together so that if both source and target events are specified in the connection’s Property window, the two values stay in sync. Event-to-method Event-to-method connections call a method when an event occurs. Event-to-code Event-to-code connections run code when an event occurs.

46 Getting Started Parameter-from-property Parameter-from-property connections use the value of a property as the parameter for a connection. Parameter-from-code Parameter-from-code connections run code when a connection parameter is required. Parameter-from-method Parameter-from-method connections use the result of a method as a parameter to a connection.

Event-to-code and parameter-from-code connections enable you to connect to methods of the composite bean.

A connection has a source and a target. The point at which you start the connection is called the source. The point at which you end the connection is called the target.

Note: If a particular bean method, property, or event does not appear in the bean’s preferred feature list in its bean or connection pop-up menu, you can select Connect and then Connectable Features from the bean pop-up or connection pop-up menu to display a complete list. The list of methods, properties, and events displayed in a window opened by selecting Connectable Features represents a bean’s complete public interface.

Event connections

Parameter connections

Property-to-property connections

Changing the properties of connections

Connecting the Open To-Do File button

Connecting beans in the To-Do List

Connecting the Select bean

Chapter 3. Beans 47 48 Getting Started Chapter 4. Connections

In the Visual Composition Editor, connections define how beans interact with each other. You can make connections between beans and connections between other connections. Every connection is made up of a source and a target. The point at which you start the connection is called the source; the point at which you end the connection is called the target.

There are 3 basic types of connections: v event connections v parameter connections v property connections

The purpose of your connection will determine the connection that you choose.

Event connections

Parameter connections

Property-to-property connections

Connection parameters

Manipulating connections

Connecting beans in the To-Do List

Changing the properties of connections

Connections, like beans, have properties. To open the properties for a connection, select Properties from the connection’s pop-up menu. Or just double-click on the connection.

© Copyright IBM Corp. 1997, 1999 49 The following figure shows the Properties window for a property-to-property connection:

You can use a connection’s Properties window to change the source or target property of the connection. To do this, select a different source or target property from the appropriate list. To display the current source and target properties of the connection, select Reset.

If you want the source of a property-to-property connection to be the target (and the reverse), you can change the source and target properties by selecting Reverse in the connection’s Properties window.

When you have finished changing the connection’s properties, select OK.

Connections

Event connections

An event connection connects a specific event to a method, a property change, or non-visual code. You create event connections when you want the behaviour of one bean (an event) to trigger the behaviour of another bean.

There are three types of event connections: v Event-to-property connections v Event-to-code connections v Event-to-method connections

This type of connection is green.

Connections

Event-to-property connections

Event-to-code connections

50 Getting Started Event-to-method connections

Changing the properties of connections Event-to-code connections

Event-to-code connections run a given method when a certain event takes place. This type of connection provides a way to implement or alter applet behavior through the use of the Java language. The target of an event-to-code method can be any method in the class that you are manipulating in the Visual Composition Editor.

Note: An event-to-method connection is created between two beans. An event-to-code connection is made between a bean and a method in the composite bean. The method in the composite been does not have to be public.

The color of an event-to-code connection is green. To create an event-to-code connection: 1. Select the source bean (for example, a JButton). Click mouse button 2 to display the bean’s pop-up menu. Select Connect and then select an event, such as actionPerformed. The mouse pointer changes. 2. Move the mouse pointer to any open area of the free-form surface. It cannot be over any bean, including the default Applet bean. Click mouse button 1 and select Event to Code from the pop-up menu. 3. The resulting window allows you to pick from the list of available methods, or to create a new method. 4. Once you’ve selected a method, select OK to complete the connection.

The connection is drawn between the source bean and a movable that contains the name of the method.

Changing the properties of connections

Parameter connections

Connection parameters

Event connections Event-to-Method Connections

Event-to-method connections cause a method to be called when a certain event takes place. This type of connection is green.

For event-to-method connections, the event is always the source and the method is always the target. A simple example of an event-to-method connection is

Chapter 4. Connections 51 demonstrated in the following example. This event-to-method connection causes a frame to be displayed (using the show method of the JFrame bean) when an Open Window button is clicked (the event) . 1. Place a JButton bean within the default JApplet bean in the Visual Composition Editor. Change the text of this button to Open Window. 2. Place a JFrame bean on the free-form surface of the Visual Composition Editor. 3. Connect the actionPerformed event of the JButton to the show method of the JFrame bean.

To test this connection, click the title bar of JFrame (not inside the box itself). The frame appears when the Button is selected. The free-form surface should look like the :

Properties can also be used to call a method, and events can be used to change the value of a property. This behavior is possible because VisualAge for Java can associate an event with a change in property value.

Connections

Connection parameters

Changing the properties of connections

Event connections

Property-to-property connections

Adding a list model and connecting it to the Add button Event-to-property connections

In addition to calling a method, an event can also be used to set a property value. In this case, a parameter must be used with the connection to supply the property value. A simple example of an event-to-property connection might be a button click (the event) which changes the title (the property) of a JFrame bean. The following steps cover the creation of an event-to-property event: 1. Place a JLabel bean within the default applet bean in the Visual Composition Editor and change its text property in the Properties window to the string This is a JFrame title. 2. Place a JButton bean within the applet bean in the Visual Composition Editor. 3. Place a JFrame bean on the free-form surface of the Visual Composition Editor.

52 Getting Started 4. Connect the actionPerformed event of the JButton to the show method of the JFrame bean. Remember to click the title bar of JFrame to see the show method. 5. Connect the componentShown event of the JFrame bean to the title property of the JFrame bean. 6. Now, to provide the parameter for the event-to-property connection you just created, connect the text property of the JLabel bean to the value property in the connection pop-up menu.

When you run the applet and select the button, the title text of the frame is set to This is a JFrame title.

Connections

Connection parameters

Event connections

Changing the properties of connections

Property-to-property connections

Parameter connections

Parameter connections supply a parameter to a connection from various sources. There are three types of parameter connections: v Parameter-from-property v Parameter-from-code v Parameter-from-method

Parameter connections are purple.

Connections

Event connections

Parameter connections

Properties as parameters Parameter-from-code connections

Parameter-from-code connections run a method whenever a parameter to a connection is required. This connection is much the same as a parameter-from-property connection, except that the value supplied to the connection is returned from a Java method instead of a bean property value.

For the sake of illustration, assume that we have created a simple method called stringFromCode in the applet class that returns the text this is a string.An example of a parameter-from-code connection follows. Unlike other connection

Chapter 4. Connections 53 types, a parameter-from-code connection is initiated from the parameter name in the connection’s pop-up menu and is terminated as follows: 1. Place a JLabel bean and a JButton bean within the default JApplet bean in the Visual Composition Editor. 2. Connect the actionPerformed event of the JButton to the text property of the JLabel bean. 3. Now, create the parameter-from-code connection by connecting the value property in the connection pop-up menu to the method as follows: v Click mouse button 2 on the connection; select Connect and then value from the pop-up menu. The mouse pointer changes. v Click mouse button 1 on any open area of the free-form surface and select Parameter from Code from the pop-up menu. v The resulting window allows you to pick from the list of available methods. In our case, the method stringFromCode() appears (this is the method that we created in the applet class). v Once you’ve selected a method, select OK to complete the connection.

Event connections

Parameter connections

Changing the properties of connections Parameter-from-method connections

Parameter-from-method connections use the result of a method as a parameter to a connection. An example of how to use a parameter-from-method connection follows: 1. Place a JButton bean and a JTextField bean within the default applet bean in the Visual Composition Editor. 2. Connect the actionPerformed event of the JButton bean to the text property of the JButton bean. (Yes, connecting an event to a property for the same bean does make sense in the right situation.) 3. Then, make the parameter-from-method connection by connecting the getText() method of the JTextField bean to the value property in the connection’s pop-up menu. This provides the needed connection parameter and causes the connection line to become solid in color.

When you test the applet, type a string into the text field and then select the Button. The string becomes the label for the Button.

Event connections

54 Getting Started Parameter connections

Changing the properties of connections

Parameter-from-property connections

Parameter-from-property connections use the value of a property as the parameter to a connection. As with other connection types, a parameter-from-property connection is initiated from the source bean’s Connect choice in the pop-up menu and is terminated by clicking mouse button 1 over the target connection line requiring the parameter. You then select the appropriate property from the pop-up menu for the connection.

A parameter-from-property connection was used in building the To-Do List sample. When we connected the JTextField bean’s text property to the connection between the JButton bean and the DefaultListModel bean, we were making a parameter-from-property connection. Refer to Connecting beans for the specific connection details for the To-Do List sample. The following example also illustrates the use of the parameter-from-property connection: 1. Place a JLabel bean, a JTextField bean, and a JButton bean within the applet bean in the Visual Composition Editor. 2. Connect the actionPerformed(awt.java.event.ActionEvent) event of the JButton bean to the text property of the JLabel bean. 3. Now, make the parameter-from-property connection by connecting the text property of the JTextField bean to the value property of the connection pop-up menu.

The free-form surface should look like this:

When you run the applet and type text into the text field and select the button, the label text is set to match the text in the text field.

Event connections

Parameter connections

Changing the properties of connections Properties as parameters

Most of the time, the parameters you need are properties of other beans you are working with in the Visual Composition Editor. To use a bean’s property as a parameter: 1. Make a new connection using the bean’s property as the source.

Chapter 4. Connections 55 2. For the target, click mouse button 1 on the connection line that requires the parameter. From the connection menu, select the particular parameter property you are specifying. While making a connection to a connection line, you will see a small visual cue in the middle of the connection line when the mouse pointer is directly over

the connection line, indicating the pointer is positioned correctly.

In the To-Do List applet, the text entered in the JTextField bean is used as the parameter of the event-to-method connection between the Add Button and the DefaultListModel bean.

In this example, you provided the parameter of the event-to-method connection by making a property-to-property connection between the JTextField bean’s text property and the event-to-method connection’s obj property. The connection’s obj property is the name of the first and only parameter of the addElement(java.lang.Object) method.

Event connections

Parameter connections

Constants as parameters

Connection parameters Constants as parameters

Parameters can be constants as well as properties. You specify a constant value for a parameter in the Properties window for the connection. For example, to specify a constant value for the parameter for an event-to-method connection:

56 Getting Started 1. Double-click on the event-to-method connection. The Properties window for an event-to-method connection opens:

2. In this window, select Set parameters. The Constant Parameter Value Settings window opens:

3. In the Constant Parameter Value Settings window, type the constant values for the parameters you want to add. 4. When you finish, select OK, and then select OK in the Properties window for the event-to-method connection.

Connections

Changing the properties of connections

Event connections

Parameter connections

Properties as parameters

Parameter connections

Connection parameters Connection parameters

When you create an event-to-method connection or an event-to-code connection, the parameters of the code or method become available as properties of that

Chapter 4. Connections 57 connection. You can then pass these properties as parameters (or arguments) to wherever they may be needed. Note that the properties can be passed as connection parameters or connection constants.

How do you know when a connection requires parameters that have not been specified? Connections that need to have one or more parameters passed to them appear as a dashed line, indicating that the connection is not complete. To pass a parameter property from one method or code fragment to another, you create a connection between the connection itself and the object or code that needs to receive the parameter.

In the To-Do List applet that you will create in the Tutorial section of this guide, you will create a simple applet which has a text box, a , and an Add button. The user should be able to enter text into the box, press Add, and then see the text they have entered displayed in the list. Behind the scenes, the text that the user has entered is stored in a List Model bean (which operates like a file cabinet) and displayed when needed in the list. The process of sending the user text from the text box to the List Model bean provides an example of how connection parameters are passed from one method to another.

The To-Do List scenario requires that the Add button’s actionPerformed event be connected to the List Model bean’s addElement(java.langObject) method (an event-to-method connection).

All that is accomplished with this step is that the Add button knows that it is supposed to send something to the List Model bean for storage. What, exactly, is going to be sent when the user clicks Add has not yet been established. This missing piece of the process is represented by the dashed line that results from the initial connection.

To get the data from the text box to the List Model bean, you would create a parameter-from-property connection between the event-to-method connection shown above and the text box in which the user enters text. The property of the text box which receives the user input would become the parameter that is passed to the event-to-method connection. This connection to a connection is shown below.

58 Getting Started When you have specified all of the necessary parameters, the dashed connection line becomes a solid line, indicating that the connection is complete. If you do not supply enough parameters for a connection, the connection continues to appear as a dashed line.

Connections

Event connections

Parameter connections

Properties as parameters

Constants as parameters

Property-to-property connections

Adding a list model and connecting it to the Add button

Property-to-property connections

Property-to-property connections tie two data values together. When one data value changes, the other changes along with it. This type of connection is blue. To experiment with property-to-property connections, you could add a text box and a label bean in the Visual Composition Editor and connect the text property of the text box with the text property of the label. For example: 1. Create a new applet using the Create Applet SmartGuide:

v Select Create Applet from the Workbench tool bar. v In the Create Applet SmartGuide, enter a name for the applet and specify a project and package for the applet. For Superclass, use Browse and enter JApplet as the pattern to get javax.swing.JApplet. v Ensure that Compose the class visually is selected and select Finish.

Chapter 4. Connections 59 2. When the Visual Composition Editor opens on your new applet, place a JTextField bean and a JLabel bean within the default Applet bean. 3. Connect the text property of the JTextField bean to the text property of the JLabel bean: v Select the JTextField bean and click mouse button 2. Select Connect and then text from the pop-up menu that appears. v Click mouse button 1 on the JLabel bean and select text from the pop-up menu that appears. 4. Select the new connection you just created and click mouse button 2. Select Properties in the pop-up menu that appears. The connection’s Properties window appears:

5. In the Properties window, select actionEvents for the Source event and select OK. The free-form surface should look like this:

6. Set the text property of the JTextField bean to Initial contents.

When you run the applet that contains these beans, the JLabel text becomes Initial contents.

For property-to-property connections, either endpoint can serve as the source or target. The only time it matters which property is the source and which is the target for a connection is at initialization. During initialization, the value of the target is updated to match the value of the source.

A property-to-property connection is initiated from the source bean’s Connect choice in the pop-up menu and is finished by selecting the appropriate target bean’s feature.

Connections

60 Getting Started Changing the properties of connections

Event connections

Parameter connections

Properties as parameters

Constants as parameters

Connection parameters

Chapter 4. Connections 61 62 Getting Started Chapter 5. Code storage and version control

Versions and editions

As you save your program elements, VisualAge for Java keeps track of your code, saving it in an edition. An edition is a “cut” or “snapshot” of a particular program element. To see more information on the edition you are working on, use the

Workbench window’s tool bar to select the Show Edition Names icon.

Each editioned program element includes either an alphanumeric name or a time stamp beside it; this is the edition information of the element. Edition information is also displayed in the Source pane. For example, if you select an editioned class

and move the mouse over the class icon in the Source pane’s title bar, the hover-help window displays the edition information of that class. Edition information is also displayed in the status area below the Source pane.

An edition of a program element keeps track of all code within the program element, including program elements within it. For example, an edition of a package includes classes and interfaces and the methods within those classes and interfaces.

At any time, the workspace only contains one edition of a given program element: the edition that you are currently working on. To help manage your program elements, VisualAge for Java also includes a source code repository, which can contain many editions of the same program element. The repository is not a development environment, but you can browse and retrieve its contents as needed and save as many editions of a program element as you wish. All editions are stored and are accessible from the repository.

You can replace an edition that is in the workspace with another edition from the repository. Note that the current edition is always marked by an asterisk (by default) to the left of the edition name when you browse an edition list in the

© Copyright IBM Corp. 1997, 1999 63 repository.

There are two fundamental types of editions: v Open edition An open edition of a program element can be modified. You can bring this edition into the workspace, making it the current edition, and change it as required. In the screen image above, the open editions are marked by timestamps. For example, (13/06/97 10:25:34 AM) is an open edition. v Versioned edition A versioned edition of a program element cannot be changed. When you version an edition, you establish a frozen (read-only) code base to which you can revert any time. In the screen image above, versioned editions are designated by alphanumeric names (for example, Beta 2 or 1.1 ). The edition that is in the workspace may be a versioned edition, although any changes you make and save automatically create a new open edition.

When you save a program element, not only is your code incrementally compiled behind the scenes, the open edition is updated in both the workspace and the repository.

Editions are managed by a team of developers. Packages and projects can only be versioned by their owners; classes can only be versioned by their developers. Versioning an edition is often followed by releasing. For information on the team development environment, see the Getting Started document for VisualAge for Java, Enterprise Edition.

The Workbench

64 Getting Started Versioning an edition of your applet Versioning an edition of your code

When you want to explore a different (perhaps more efficient) implementation of a method that already works, but you are not sure if changes or additions will introduce new problems, it’s a good time to create a versioned edition of your code.

To create a versioned edition of a package or project: 1. Select the package or project. From the Selected menu, click Manage and then Version. The Versioning Selected Items SmartGuide appears.

2. Ensure the Automatic radio button is selected and then select OK.

In the Workbench hierarchy, notice that the time stamp beside the package name has been replaced with the new version number. This versioned edition is now permanently stored in the repository, regardless of what happens to your editions in the workspace. You can create open editions based on this versioned edition, and the versioned edition will always be available, in the state at which it was originally versioned, from the repository.

Versions and editions

Editioning the To-Do List after adding a counter

Returning to a previous edition

Exploring the repository

As part of its suite of tools, VisualAge for Java provides a Repository Explorer. The Repository Explorer adds a visual interface, similar to a file manager, to your repository, providing a graphical view of all editions of all of your program elements (including all the program elements that are currently in the workspace).

To view the Repository Explorer, select Window > Repository Explorer from the menu.

Chapter 5. Code storage and version control 65 Within the Repository Explorer, you can open and/or compare program elements that are stored in the repository without swapping editions in and out of the workspace.

By comparing different editions, you can see the following: v Changes that have been made as a result of code generation. v The differences between an edition with errors and a bug-free edition.

To compare two editions of a package: 1. Select the Repository Packages page. 2. Select a package in which you have two or more editions from the Package Names list. 3. From the Editions list, hold down mouse button 1 and drag-select the top two editions. From the Editions menu, select Compare. The Comparing window

66 Getting Started appears.

4. Select a class or method name in the Element pane, and you’ll see two sets of corresponding code in the text panes below. Here, you can compare the two program elements. From the Differences pull-down menu, you can select Next

Difference and Previous Difference. You can also select the arrows in the upper right corner of the window to move back and forth in the list of differences.

All program elements that are in the workspace are indicated by an asterisk (*).

The Workbench

Versions and editions

Importing and exporting code

Getting samples from the repository Getting samples from the repository

VisualAge for Java comes with a wide variety of sample code. Use the Repository Explorer window to examine these examples. For example, you will create a To-Do List program in the Tutorial section of this guide. To examine the completed version of To-Do List program in the Repository Explorer, do the following: 1. Select the Repository Projects page. Select IBM Java Examples from the Project Names list. 2. Select an edition from the Editions list and select com.ibm.ivj.examples.vc.todolist from the Packages list. The class in this package appears in the Types list. To examine this class, select it and click mouse button 2. Select Open from the pop-up menu that appears.

Chapter 5. Code storage and version control 67 If you want to run these completed samples, or make your own updates to them, you must import them into the workspace. The following steps are required to bring a completed version of the To-Do List program into the workspace. 1. In the Workbench, select the project into which you want to add the To-Do List program. Select Add > Selected > Package from the menu. The Add Package SmartGuide appears. 2. Select Add packages from the repository. 3. Select com.ibm.ivj.examples.vc.todolist from the Available package names list. Select an edition from the Editions list and click Finish.

The package for the To-Do List program is added to your workspace.

Exploring the Repository

Importing and exporting code

The Quick Start window

Importing and exporting code

You can easily move your code between your file system and VisualAge for Java by selecting Importor Exportfrom the Filemenu in the Workbench.

If you want to bring existing Java code into VisualAge for Java, you can use the Import SmartGuide to specify files (or whole directory structures) that you want to import. You can import: v a directory v a Jar file v a repository

and then specify the projects, packages, and/or types of files (.java, .class, and/or resource files) that you wish to include in your import. VisualAge for Java compiles the code, indicates whether there are any errors, and adds the appropriate program elements to the workspace.

When you want to run your program outside of VisualAge for Java, you can export it using the Export SmartGuide. The Export SmartGuide provides you with three export destination options: v export to a directory v export to a Jar file v export to a repository

Depending on which destination you choose to export to, you can export v .java files v .class files v resource files v beans

68 Getting Started If you are exporting to a Jar file, you also have the option of creating .html files to launch your applets. VisualAge for Java creates a Java source (*.java) file or compiled (*.class) file for each class that you export.

Importing and exporting from the Repository

You can also import or export projects to and from your workspace by adding or removing features. These features are are projects containing code that isn’t mandatory for the successful operation of VisualAge for Java, but which can provide valuable tools or useful samples to your workspace. You can use the QuickStartoption from the Filemenu (or F2 on your keyboard) and select Add Feature to add a project that was installed in the repository when you installed VisualAge for Java. Or you can remove a VisualAge for Java feature from your workspace by selecting Remove Feature from the QuickStart window.

The features in the repository include IDE samples and Data Access Beans. A secondary window provides a list of available projects (features) that you can add to or remove from your workspace.

The QuickStart window

Exploring the Repository

Using Quick Start and a SmartGuide to create your applet

Chapter 5. Code storage and version control 69 70 Getting Started Chapter 6. Advanced features

Introduction to data access beans

VisualAge for Java supports access to relational databases through JDBC. You can access relational data in an applet or application by selecting any of the Data Access beans from the Choose Bean in the Visual Composition Editor beans palette. There are three beans which provide the main functions required for accessing relational data: v Select bean v Modify bean v ProcedureCall bean

Select bean

The Select bean enables you to run a query and access the result set returned by the query. You can insert, update, and delete rows in the result set without writing seperate SQL INSERT, UPDATE and DELETE statements.

Modify bean

The Modify bean enables you to run SQL INSERT, UPDATE, or DELETE statements without first running a query and retrieving its result set.

ProcedureCall bean

The ProcedureCall bean enables you to run a stored procedure passing values for input parameters and receiving values for output parameters. If the stored procedure returns one or more result sets, the ProcedureCall bean gives you access to them, and you can insert, update, or delete rows within the result sets without writing separate SQL INSERT, UPDATE, and DELETE statements.

Setting up access to DB2 from VisualAge for Java

Using Select, Modify, and ProcedureCall beans

Data output beans

Data access beans in action Setting up access to a DB2 database

Before building the application, make sure that you can access the SAMPLE database in DB2 from VisualAge for Java. For this example, we used DB2 Universal Database for Windows NT, Version 5.2.

Checking for the SAMPLE database

© Copyright IBM Corp. 1997, 1999 71 1. From the desktop, select Start and then DB2 for Windows NT. 2. Select Administration Tools and then Control Center. The Control Center window appears. 3. Expand the items in the Systems tree until you see Databases. Expand the Databases folder to verify that the SAMPLE database exists.

If the SAMPLE database does not exist on your workstation, consult the documentation for the level of DB2 installed on your workstation.

Setting up access to DB2 from VisualAge for Java 1. From the menu bar of the Workbench, select Window and then Options. 2. From the left pane, select Resources. 3. To the right of the Workspace class path field, select Edit. A dialog appears. 4. From the dialog, select Add Jar/Zip. A standard file selection window appears. 5. Within the file selection window, find the sqllib directory created as part of the DB2 installation. 6. Double-click on the java folder and select db2java.zip. 7. Select Open. 8. Select OK to close the dialog. 9. Select Apply to add the directory to the class path. 10. Select OK to close the Options window.

Working with relational data Using Select, Modify and ProcedureCall beans

To connect to a database and access data using a Select, Modify, or ProcedureCall bean, you specify values for the following properties: v Select bean - specify a query property v Modify bean - specify an action property v ProcedureCall bean - specify a procedure property

Each of the properties has the following: v Connection Alias - the database connection characteristics such as the URL for the connection and the user ID and password passed with the connection request. v SQL Specification - an SQL statement and meta-data about the statement.

VisualAge for Java provides the SQL Assist SmartGuide to help you visually compose an SQL specification or you can use the SQL editor to manually compose an SQL statement. If you manaully compose the SQL statement you may also need to manually add meta-data about it to the generated SQL specifictaion.

To add the functionality to your user interface that will invoke methods on the core beans and help display output from the database, you need the beans which allow data access and output.

72 Getting Started Data output beans Accessing data with the Select bean

To access relational data using the Select bean: 1. Add the Select bean to the Visual Composition Editor surface. 2. Edit the Select bean properties. The query property allows you to define the following things: v Connection alias. This identifies the characteristics of the database connection for the Select bean. These include characteristics such as the URL for the connection, and the user ID and password to be passed with the connection request. v SQL specification. This specifies the SQL statement for the Select bean. You can use the SQL editor that is provided to enter the SQL statement manually, or you can use the SQL Assist SmartGuide to compose the SQL statement visually. You can select one or more tables, join tables, specify search conditions, identify columns for display, sort the results, map the data types of the result columns into Java classes, and view the resulting SQL statement. You can even do a test run of the query.

3. Connect the Select bean to a visual component of your applet or application, such as a button bean. When a user uses the application or applet, and selects the visual component, for example clicks the button, the SQL statement for the Select bean retrieves a result set.

You can also use the Select bean to apply changes that users make to a result row, even deletion of a row, and commit the changes to the database. In these cases, you use update and delete methods provided by the Select bean.

Chapter 6. Advanced features 73 Setting up access to DB2 from VisualAge for Java

Data output beans

Additional beans provide user interfaces to invoke methods on the core beans and to help display output from the database: v DBNavigator Bean v CellSellector Bean: a single-value view v RowSelector Bean: a row view v ColumnSelector Bean: a column view v CellRangeSellector Bean: a two-dimensional view

All of the beans except DBNavigator are non-visual. The DBNavigator bean is a visual bean can be used with a Select bean or ProcedureCall bean and provides a set of buttons that: v run the SQL statement for the associated nonvisual bean v navigate rows in the result set, or v perform other relational database operations, such as commit updates to the database.

Before you can use these Data Access beans, you must first use the Quick Start window to add the Data Access beans feature to VisualAge for Java, and you must change the class path. Data access beans are covered in extensive detail in the online help and the PDF documents included with the VisualAge for Java software. Search for Data Access Beans (DAB) in the Concepts and Tasks sections of the in the online help for more information.

Setting up access to a DB2 database

The Quick Start window

Using Select, Modify, and ProcedureCall beans Using SQLJ

You can use SQLJ to include SQL statements in your Java applications. The SQLJ standard is made up of three components: v Embedded SQLJ v An SQLJ translator v An SQLJ runtime environment

Embedded SQLJ

Embedded SQL statements are static and do not change at run time. An embedded SQL statement uses the following syntax:

#sql

74 Getting Started For example, an SQL statement that retrieves a list of names from a database would be written as follows:

#sql SELECT names

An SQLJ program is an SQLJ file with the extension .sqlj. It mixes Java code with #sql statements and must be created in a text editor. To use the SQLJ file in a Source pane in VisualAge for Java, you must import the file created in the text editor and translate it.

SQLJ translator

The SQLJ translator replaces your SQLJ statements with calls to the SQLJ runtime environment, creating Java source code files and profiles. The translated source code can then be imported into a project.

SQLJ Java proviles include information about embedded SQL operations in the SQLJ code, including types and modes of data being accessed. Typically, one profile is generated per types connection context class, with a connection context class corresponding to a single database schema. Note that you must customize profiles to make use of vendor-specific features. Profiles are binary files with an .ser extension and are created in the project resources directory.

SQLJ runtime environment

You must add the SQLJ runtime environment to your workspace before you can successfully compile and execute translated SQLJ code. The SQLJ runtime environment runs SQLJ operations by referring to the Java profiles generated by the translator.

Setting up and using SQLJ

To set up the SQLJ tool for a project, you must carry out the following steps: v Add the SQLJ Runtime Library feature to your workspace. v Add the SQLJ Runtime Library project to your project’s Class Path

You can also enable online semantics checking if you wish.

After SQLJ is set up, you can do the following: v Create an SQLJ file v Import, edit, and translate SQLJ files v Create an SQLJ debug class file v Customize an SQLJ profile

To find out more about these procedure topics, see the VisualAge for Java online help.

Working with relational data

The Quick Start window

Chapter 6. Advanced features 75 Data access beans in action

Writing code manually

VisualAge for Java is designed to help you develop code by having the Visual Composition Editor (VCE) and the SmartGuides generate Java code for you. When you create your own applications, you will likely need to write sections of code on your own in the Source panes of the IDE browsers. VisualAge for Java provides several tools to help you write correct, neat code without the VCE.

Code Assist

Source panes and other dialogs and browsers (for example, the Configure Breakpoints and Scrapbook windows) contain Code Assist, a tool that helps you find the classes, methods, and fields you are looking for without having to refer to class library reference information. Code assist is accessed by typing Ctrl+Spacebar.

When you type Ctrl+Spacebar, classes, methods, and types that could be inserted in the code at the point at which the cursor is located are displayed in a pop-up list. You can select the class, method, or type of your choice. If the Code Assist mechanism cannot find a member that fits the current location of the cursor, the information line at the bottom of the pane will indicate that no Code Assist is available for the current context.

Customizing Code Assist

You can customize Code Assist behavior using the Options window. For additional information about these options, see the online help. v To change the key sequence used to trigger Code Assist from Ctrl+Spacebar to a key sequence of your choice, select General > Key Bindings and edit the entry for Code Assist. v To adjust the key used to trigger keyword completion, select Coding > Code Assist. v To adjust the templates used in keyword completion, select Coding > Keyword completions. You can also add your own templates. v To define named Code Assist macros, select Coding > Macros.

Code Assist Tips

The following is a short list of tips and information that you should be aware of when using Code Assist. v Code Assist is not available in a class definition. v Code Assist is case-sensitive. For example, if you are looking for a program element that starts with uppercase C, you must type in an uppercase letter C before you invoke Code Assist. The same is true in reverse: as you narrow down the pop-up list, use the proper case. v When accessing Code Assist for names that start with Java keywords such as for, while,orif, type Ctrl+Spacebar at least one letter before or after the end of the keyword. Otherwise, the information bar will indicate that no Code Assist is available in the current context. v If typing Ctrl+Spacebar does not launch Code Assist on your system, try using Ctrl+L.

76 Getting Started Code clues

If you try to save code that contains an error, the IDE warns you that the code has an error. If it can determine the type of error, it will present a list of possible solutions. You can select one and correct the error, or you can save the code with the error (it will be added to the list of problems on the Problem page of the IDE browsers that contain the program element).

For example, if you added System.out.pritn(i); and saved the method (note the misspelling of the keyword print) , the following dialog box would appear, suggesting alternative code that will fix the problem.

Select the suggested correction print(Object) void and click Correct. The method will be saved with the replacement code. If you click Save, the method will be saved with the error. If you click Cancel, the method will not be saved and the error will remain in the code.

Code formatting

To promote neat, easy-to-read coding, the IDE provides an automatic code formatter that controls how your code appears when you write it in a Source pane. To set code formatter options, including indentation and new-line controls: 1. Open the Options dialog by selecting Options from the Window menu. 2. In the list on the left of the Options dialog, expand the Coding item. 3. Select the Formatter item. On the Formatter page you can enable options that tell the Source panes to start a new line for each statement in a compound statement, or to use and opening brace. 4. Select the Indentation item. On the Indentation page, you can select an indentation style.

Chapter 6. Advanced features 77 These specifications are applied automatically to all new code. If you have imported code from the file system, or if you change the formatting options, you can apply the options to code in a particular source pane by selecting Format Code from the pane’s pop-up menu.

Creating beans without the VCE

Code Assist for types, methods, and fields

Debugging

Building your first applet Creating beans without the VCE

Visually composing beans in the Visual Composition Editor (VCE) is often faster than writing them manually, you can create beans without the VCE. The steps below show you how to write a very simple “Hello, World” applet without the VCE. You can compare this process with the process of composing beans visually described in the Tutorial, starting with the topic “Building your first applet”.

From the Workbench File menu, select Quick Start. Then from the Quick Start window, follow these steps: 1. Select Basic and then Create Class. 2. Select OK. The Create Class SmartGuide opens.

In the Create Class SmartGuide, follow these steps to create your applet: 1. In the Project field, type a project name. 2. In the Package field, type a package name. 3. In the Applet name field, type a name. (For this example, we will use “HelloWorld”.) 4. In the Superclass field, select JApplet. 5. Make sure that Browse class when finished has been selected. 6. Select Finish.

The class browser for HelloWorld appears, displaying the following in the Source pane: /*** This type was created in VisualAge. */ public class HelloWorld extends javax.swing.JApplet { }

Add import statements for your class above the generated comment as follows: import javax.swing.*; import java.awt.event.*; import java.awt.*; /*** This type was created in VisualAge. */ public class HelloWorld extends javax.swing.JApplet { }

78 Getting Started Save the new code by pressing Ctrl+S.

From the Methods pane, create an init() method to complete thie applet as follows: 1. Click mouse button 2; select Add and then Method. The Create Method SmartGuide appears. 2. Change the highlighted text to void init() 3. Select Finish. The generated stub for init() appears in the Source pane of the class browser.

Write code for the new method. For this example, add code into the stub so that it looks like this:

public void init() { JButton button = new JButton(“Hello World!”); setBackground(Color.lightGray); getContentPane().add(button, “Center”); }

Save the new code by pressing Ctrl+S.

If you were to run HelloWorld at this point, the applet viewer would not be able to initialize the applet. The last step is to set the correct class path: 1. From the Class menu, select Properties. A properties window opens. 2. From the Class Path page, select Compute Now and then OK.

Now run the class. It is simple, but it works!

Writing code manually

Code assist for types, methods, and fields

Adding the Add and Remove buttons Code Assist for types, methods, and fields

To insert the name of a class or interface in your code, enter the first one or more letters of the type name, and then type Ctrl+Spacebar. A pop-up list appears, containing types that start with what you have entered. Enter more letters to narrow down the list. Select an item to insert it into your code at the cursor. If the type needs to be qualified, the qualification is also automatically inserted.

Example: Create a test project and package. In the test package, create a class called AssistTest. In the AssistTest class, create a method called assistMethod. Suppose you want to declare a local Integer variable, i. In the body of the assistMethod source, type the following letters: In

Chapter 6. Advanced features 79 Type Ctrl+Spacebar. The pop-up list of options appears.

The list of available types is long. To find Integer, enter the letters te. Now, Integer is near the top of the list.

Select it using the arrow keys and press Enter.

Now finish the declaration so that the method looks like this:

public void assistMethod() { Integer i; }

Save the method by typing Ctrl+S. You will use this test method in the next example.

Code Assist for methods and fields

Code Assist can also list the methods and fields available for an object or class. Enter the name of the object, a period (.), and a few letters from the start of the method or field name; then type Ctrl+Spacebar. The list of methods and fields for the object will pop-up. Select one to insert it in the code.

Example: In the assistMethod method you created in the previous example, below the line that declares i , enter the following code (the period is important):

i = Integer.

80 Getting Started Type Ctrl+Spacebar. A list of methods and fields for the Integer class pops up.

Enter the letters val until you find valueOf(String) Integer. The parameter types (in this case, String) and return type (Integer) are shown.

Select valueOf(String) Integer and press Enter; it is inserted into your code. Enter a string such as “35” between the parentheses and end the line with a semicolon. The method source will now look like this: public void assistMethod() { Integer i; i = Integer.valueOf(“35”); }

If you request Code Assist for a method or field from a class that requires qualification, the class must be qualified before you type Ctrl+Spacebar. Otherwise, no Code Assist will be available. Generally, the code that appears before the cursor must be compilable before you request Code Assist.

Example: Suppose java.util.* is not in your class import statement. This means that the class ResourceBundle must be qualified when you use it in your class. If you type the following code, and then type Ctrl+Spacebar to get the list of methods available, no list will be available: public String newMethod ( ) { ResourceBundle a = ResourceBundle. // place cursor after period // and type Ctrl+Spacebar

However, if you type the following code, where the class qualification is provided, Code Assist is available:

Chapter 6. Advanced features 81 public String newMethod ( ) { ResourceBundle a = java.util.ResourceBundle // place cursor after period // and type Ctrl+Spacebar

An easier way to produce a qualified name in this case (assuming you do not want to add this class or package to the import list) is to place the cursor before the period and type Ctrl+Spacebar. Select the class name from the list and it will be fully qualified for you automatically. Then type the period and Ctrl+Spacebar. The list of methods in ResourceBundle will now pop-up.

Code Assist for method parameters

Code Assist includes pop-up help for method parameters. For example, when you select valueOf(String) Integer from the pop-up list in an example, above, the following text is inserted at the cursor:

valueOf()

The cursor is automatically placed between the parentheses, and the pop-up label String appears to let you know what type of parameter to add.

Writing code manually

Creating beans without the VCE Internationalization support

If you want to deploy your applications and applets anywhere in the world, you can make your Java programs international so that they can be used in many languages. Internationalization can be built into your programs using the Java Internationalization Framework. This framework has two main components: locales and resource bundles.

Locales

Locales are a specific geographical or political region. The java.util.Locale class contains information about supported geographic or political regions. Classes that provide support for different locales are “locale-sensitive” classes. These classes use either a default or specific locale to determine which locale to support. You can create a Locale object by specifying a language, a country (optional), and a variant (optional) as follows:

Locale myLocale = new Locale (“en”, “US”, “”);

82 Getting Started This object specifies the language “English” and the country “United States”.

Resources

Resource bundle classes, derived from java.util.ResourceBundle, are collections of resources that can be used to gather together those resources needed for a specific language. This allows you to separate your program code from the locale-specific data in your programs.

Resource bundle classes store and retrieve information using identifiers and keys. There are two resource bundle types: List and Property. The following methods in each type provide access to resource values: v the getContents method v the getKeys method v the getObject method v the getString method v the getStringArray method

A list bundle is a persistent form of java.util.ListResourceBundle. A property file is a persistent form of java.util.PropertyResourceBundle.

Both the List and Property types of resource bundle contain key-value pairs, but handle storage differently. For list resource bundles, key-value pairs are stored within a bundle class in the repository — ListResourceBundle.getContents() returns an array of key-value pairs. The key-value pairs in a property resource bundle are stored in the file system.

Each resource bundle contains values for one (or a default) locale. The name of the bundle can be keyed by locale so that the virtual machine loads the appropriate resources for the current locale setting. Multiple resource sources can be referenced within a single bean. VisualAge for Java generates the appropriate code the next time you save the bean.

VisualAge for Java allows you to create, edit, and use resource bundles for all text found in a class. You can separate String property values one by one as you set them from the Visual Composition Editor, or you can separate all text in a batch after they have been set up in the Workbench. For more information on internationalization in VisualAge for Java, see the online help.

Writing code manually

The Distributed Debugger

The IBM Distributed Debugger is an external application (different from the Integrated Debugger within VisualAge for Java) that enables you to detect and diagnose errors in your programs. The debugger server, also known as a debug engine, runs on the same system as the program you want to debug. This system can be your workstation or a system accessible through a network. If you debug a program running on your workstation, you are performing local debugging. If you debug a program running on a system accessible through a network connection, you are performing remote debugging.

Chapter 6. Advanced features 83 The Distibuted Debugger can be used to debug Java programs that meet the following criteria: v The program has been compiled into platform-specific executables or DLLs v The program has been exported from VisualAge for Java to the file system.

Because the Distributed Debugger is a program separate from the VisualAge for Java package, it can also be used to debug a a Java program without interrupting your development time. You can export your Java program and set up the Distributed Debugger to debug your program while you continue your work in VisualAge for Java. Note that in order for an external debugger to work with your code, you must export source code and bytecode, and you must select the Include debug attributes in .class files option in the Export SmartGuide.

Note: The Java source, bytecode, and debug information for the program must be available to the Distributed Debugger. Accelerators that optimize Java programs can generate debug information. The IDE can export debug information when it exports classes to the file system.

While the Java2 platform is not officially supported by the Distributed Debugger, the debugger does appear to handle debugging with the Java2 platform. To debug using the Java2 platform, you must point to LIBTOOLS.JAR and LIBDT.JAR with your CLASSPATH environment variable.

How the Distributed Debugger works

The debug engine can either start the program you want to debug or attach to an already running program. Once started, the debug engine controls the execution of your program. The debugger client is a graphical user interface where you can issue commands used by debug engine to control the execution of your program. For example, you can set breakpoints, step through your code and examine the contents of variables.

The debugger user interface lets you debug multiple applications written in different languages from a single debugger session. Each program you debug is shown on a separate page with a tab on each page displaying program identification information such as the name of the program being debugged. The type of information displayed depends on the debugger server that you are connected to.

For more information about the Distributed Debugger, see the online help for VisualAge for Java.

Debugging

Writing code manually

Customizing your workspace

84 Getting Started Tool Integrator API

VisualAge for Java’s Tool Integrator API is for advanced VisualAge for Java users who want to customize the integrated development environment (IDE) by adding their own tools. Using the Tools API, you can create specialized tools that are useful to your development work, and then launch them when needed from the Tools menu in the Workbench.

The scope of your tools is determined by the methods included in the Tools API. You can implement the following standard VisualAge for Java tasks in any tool that you create: v workspace and repository browsing v object queries v loading of editions of code from the repository into the workspace v importing and exporting of source, class, and repository files v use of class and interface source code

To view a complete list of the API methods, you must include the IBM IDE Utility class libraries project in your workspace. This project includes two packages: v com.ibm.ivj.util.base v com.ibm.ivj.util.builders

These packages contain the classes and interfaces that you need to build your tools and interact with the VisualAge for Java IDE. To find out more about including the IBM IDE Utility class libraries project in your workspace, see “Features tasks” in “The Quick Start window”.

What kind of tools can you create with Tool API?

You can use the Tool Integrator API to create tools that automate processes that you repeat often. For example, if you need to repeatedly export the code that you develop from the IDE to the file system, you can use the Export SmartGuide provided by VisualAge for Java. This would require several user interface steps. Using the Tool Integrator API, you could create a tool that encapsulates all of the user interface steps into a single step, in the same way that you would combine several commands for a command interpreter into a batch file. You could then invoke the tool with a single mouse click on a menu.

The Quick Start window

Importing and exporting code

External software configuration management (SCM) tools

If you need to check your code into and out of an SCM system, VisualAge for Java provides an interface for the following SCM tools: v ClearCase for Windows NT v PVCS Version Manager v VisualAge Team Connection v Visual SourceSafe

Chapter 6. Advanced features 85 With the VisualAge for Java SCM tool, you only need to select Checkin or Checkout from a menu in the IDE when checking code in or out of the external SCM tool. The most recently checked-in versions of classes are automatically available to you.

Warning: The VisualAge for Java interface to external SCM tools does not provide any automatic synchronization of version names between the VisualAge for Java repository and the external SCM tool. VisualAge for Java will not prevent you from changing a program element in your workspace if you have not checked it out from the external SCM tool. To take full advantage or the VisualAge for Java SCM tool, you must correlate the functions of the external SCM tool and the VisualAge for Java SCM interface.

Before you can use the VisualAge for Java interface to an external SCM, you must meet the prerequisites listed in the topic “Preparing to use an external SCM tool” in the online help. To find out more about setting up and configuring the SCM tool in VisualAge for Java, see the VisualAge for Java online help.

Exploring the Repository

The Workbench

Printing program elements

VisualAge for Java gives you several options for printing program elements. You can print projects, packages, classes, interfaces, or methods. When you print a program element that is composed of other program elements, you have the option of printing these other program elements. For example, when you print a package, you can also print the classes in the package.

To print a program element: 1. Select the program element. Select Document and then Print from its pop-up menu. The Print dialog box opens.

2. The items that you can select to print depend on what kind of program element you are printing:

86 Getting Started v Selections under Projects are available if you are printing a project. v Selections under Packages are available if you are printing a project or a package. v Selections under Types are available if you are printing a project, package, class, or interface. v Selections under Methods are always available. 3. By default, all the items under Projects, Packages, and Types are selected, and Entire Method is selected under Methods. Change these selections if you want and select OK to start printing. 4. If no default printer has been selected, a message appears asking you to select one.

Printing a graph of a class hierarchy

You can print a graph view of a class hierarchy for a project or a package. The output goes to the default printer.

To print a class hierarchy graph: 1. In the Workbench or another browser, select the project or package for which you want to print the graph. 2. From the element’s pop-up menu, select Open To and then Classes. This opens the Classes page of a browser on the project or package.

3. In the Class Hierarchy pane title bar, click the Graph Layout button. 4. From the Class Hierarchy pane’s pop-up menu, select Document and then Print Graph. The graph showing the inheritance of each class is output to the default printer.

Printing online help topics

Finding out more about VisualAge for Java

This Getting Started document provides only a brief overview of what you can do with VisualAge for Java. For more complete information, see the online help that is available from the Help menu of any window in VisualAge for Java.

The online help is organized into several categories: v Concepts provide definitions and an overall grounding in the concepts that you need to know to use VisualAge for Java. v References provide API documentation and additional reference information. v Tasks provide step-by-step guidelines for accomplishing specific goals. v PDF Index lists printable documentation. v Samples describes the samples that come with the product and how to get them. Some samples also include directions on how to build the sample in the Visual Composition Editor. v Glossary defines terms used frequently in VisualAge for Java.

Chapter 6. Advanced features 87 Getting the latest VisualAge for Java information

88 Getting Started Chapter 7. The To-Do List tutorial

Building your first applet

This section guides you through building your first applet in VisualAge for Java: a to-do list.

If you have not already installed VisualAge for Java, refer to the readme.txt file on the product CD for information on how to install the software. The VisualAge for Java installation program installs all of the files that are necessary for your development environment.

You will create a To-Do List applet, which consists of a bean (a composite bean) that is made up of many other beans. The applet has a JTextField bean for entering a To-Do item and a JList bean for displaying the To-Do items. There are also two JButton beans for adding and removing items from the list. The user interface for the completed To-Do List applet looks like this:

In the completed applet, you type an item into the To-Do Item field and select Add. This adds the item to the To-Do List. If you select an item from the To-Do List and select Remove, the item is removed from the To-Do List. Constructing the To-Do List applet

When the Visual Composition Editor opens, you can begin visually constructing your To-Do List applet. The To-Do List applet consists of a bean containing several visual beans.

When the Visual Composition Editor opens for the new ToDoList applet, the default JApplet bean is represented as a gray rectangle on the free-form surface. To build the rest of the user interface, you must add several other visual beans. When you have finished creating the user interface for the To-Do List applet, the

© Copyright IBM Corp. 1997, 1999 89 free-form surface of the Visual Composition Editor should look like this:

To make a user interface that looks like this, you need to add, size, and align the remaining beans.

Note: As you add beans to the applet, you may find that the default JApplet bean is too small to accommodate all the other beans. If this happens, you can resize the JApplet bean by selecting it and dragging one of the selection handles using mouse button 1.

Although this bean uses a layout manager, it could be built using one of the layout managers, such as GridBagLayout. For an example of creating the user interface for this bean in GridBagLayout, see the online help. You can also convert from to any other supported layout manager. Using Quick Start and a SmartGuide to create your applet

For the To-Do List applet, you create an applet as well as a project and a package to contain your work. You create these using a SmartGuide that you access from the VisualAge for Java Quick Start window.

When you manipulate your new applet in the Visual Composition Editor, you are visually manipulating JavaBeans. These JavaBeans (or, simply, beans) are represented as classes when you examine your applet in the Workbench.

VisualAge for Java suggests that you give your applets (and all other classes) names that begin with a capital letter. Class names are case-sensitive, and cannot contain spaces. If a class name consists of multiple words, do not type spaces between the words, but instead capitalize the first letter of each word (for example, ToDoList).

Creating an applet, a project, and a package

To open the SmartGuide, from the Workbench File menu, select Quick Start. Then from the Quick Start window: 1. Select Basic and then Create Applet.

90 Getting Started 2. Select OK. The Create Applet SmartGuide opens:

In the Create Applet SmartGuide, follow these steps to create your applet: 1. In the Project field, type a project name, such as “My ToDoList Project”. 2. In the Package field, type a package name, such as “todolist”. 3. In the Applet name field, type a name, such as “ToDoList”. 4. In the Superclass section, select the JApplet radio button. 5. Make sure that the Compose the class visually check box is selected. 6. Select Finish.

VisualAge for Java creates a project, a package, and an applet in the Workbench window and then opens the Visual Composition Editor, displaying the applet.

Although using the Visual Composition Editor is usually the fastest way to create a program element like this one, you can develop the To Do List code on your own if you wish. For more information on developing code without the visual composition editor, see “Creating beans without the VCE”. Adding labels and text boxes

In this stage of the applet creation, you add a JTextField bean that is used to enter the To-Do items, and a JLabel bean to identify the field. These beans are in the Swing category of the beans palette.

Tip: As you work with the palette, you may find the icons too small for your preference. To make them larger, right-click on any gray area on the palette and select Show Large Icons from the pop-up pane.

To add the text box

Chapter 7. The To-Do List tutorial 91 1. From the beans palette, select the JTextField bean. The information area at the bottom of the Visual Composition Editor displays Category: Swing Bean: JTextField, reflecting the current selection in the beans palette. 2. Move the mouse pointer over the JApplet bean (the rectangle on the free-form surface). The pointer changes to a crosshair, indicating that it is now loaded with the bean you selected. Click mouse button 1 where you want to add the JTextField. If you accidentally picked the wrong bean and have not dropped the bean into

the JApplet yet, select the correct bean, or select the Selection tool from the beans palette to unload the mouse pointer. After you have added the JTextField bean to the JApplet, you can move it to a new location by dragging it with the mouse, as follows: v In OS/2, click on the bean and hold down mouse button 2. v In the UNIX platforms, click on the bean and hold down the middle mouse button. v In Windows, click and hold down mouse button 1.

You can also resize the bean by dragging a side of the rectangle using mouse button 1.

3. Select the JLabel bean and add it just above the JTextField. Do not worry about their exact positions. Later you’ll learn how to use the tools from the tool bar to match sizes and align beans. Changing the text labels

Change the text of JLabel to To-Do Item by editing the text as follows:

1. Select the JLabel bean. Select Properties from the tool bar. 2. In the Properties window, click text field, and type To-Do Item (instead of JLabel1). The label now contains the text To-Do Item. You may need to stretch the label to see it. 3. You can add another label below the JTextField by copying JLabel1. To copy a bean: a. Select the bean. b. From the Edit menu, select Copy. c. From the Edit menu, select Paste. The pointer changes to a crosshair, indicating that it is now loaded with the bean you selected. d. Click mouse button 1 below the JTextField to add the new label. 4. Change the text for the new label to To-Do List by editing it as you did for JLabel1.

Tip: You can also copy a bean using the Ctrl key. Position the mouse pointer over the JLabel bean, hold down the Ctrl key, and drag the copy of the bean to below the JTextField bean. Adding a scrolling list

Add a scroll pane so that your list of items can be scrolled.

92 Getting Started 1. Select the JScrollPane bean. (Notice it comes from another group on the palette; the group of container beans.) 2. Add JScrollPane below the text field. Adding a list

To create the list in which the To-Do items are displayed, you need to add a JList:

1. Select the JList bean and place it inside the scroll pane. The JList bean adjusts to fill the JScrollPane. 2. In the Properties window, change the selectionMode property to SINGLE_SELECTION. This simplifies the code needed to handle selection within the list. 3. It is good practice to save your work periodically. To save your work, from the Bean menu select Save Bean.

Adding the Add and Remove buttons

To add and remove items from the To-Do list, you need to add two buttons: 1. To add more than one instance of a bean at a time, press and hold the Ctrl key before selecting the bean.

2. Select the JButton bean and add a button to the right of the text field. Notice that the mouse pointer remains a crosshair, indicating that it is still loaded with the JButton bean. To add another JButton, click mouse button 1 below JButton1.

3. Select the Selection tool from the beans palette to unload the mouse pointer. 4. As you did with the Label beans, change the text on JButton1 to Add. Also in the property sheet, name the bean AddButton. 5. Change the text on JButton2 to Remove. Also in the property sheet, name the bean RemoveButton. 6. Save your work using Save Bean from the Bean menu.

Congratulations! You have just created your first user interface using VisualAge for Java. Next, you need to size and align the beans within the To-Do List applet. Sizing and aligning visual beans in the To-Do List

Since your applet does not use a layout manager, you need to clean up the appearance of your user interface by using the sizing and aligning tools from the tool bar on the Visual Composition Editor. The tool bar provides several different tools for sizing and aligning beans. You’ll learn a great deal about how to use them by experimenting with the different tools.

The order in which you size, align, and distribute the beans is not always important. Usually, you start with the upper left corner and work your way through all the beans in the window.

To size the list in your applet so it matches the width of the text field:

Chapter 7. The To-Do List tutorial 93 1. Select the Beans List from the tool bar. 2. From the list, select JScrollPane1. Remember, you want to size the container for the list, which is the scroll pane. You are using the Beans List to do this because the JList bean almost completely overlays the JScrollPane bean, which makes it difficult to select from the free-form surface. 3. Hold down the Ctrl key to select multiple items and from the free-form surface select the text field using mouse button 1.

4. Select the Match Width tool from the tool bar. Because the text field was selected last, it becomes the anchor bean for the match width operation. The width of the list is changed to match the width of the text field.

Note: The anchor bean has solid selection handles. The other selected items have outlined selection handles.

To size and align the Add button and the Remove buttons: 1. Resize the Remove button to an appropriate size for the applet. 2. Select the Add button, hold down the Ctrl key and select the Remove button

using mouse button 1. Then, select the Match Width tool from the tool bar. 3. Because the buttons remain selected, you can now align their left edges by

selecting the Align Left tool from the tool bar.

To align the left side of your beans: 1. Move the label for the text field (the one that says To-Do Item) to the position you want it in the applet. 2. Select the scroll pane (making certain it is the scroll pane, not the list), the text field and their associated labels, making sure to select the label of the text field last. By selecting the text field label last, you make it the anchor bean for the alignment operation.

3. Select the Align Left tool from the tool bar. 4. Because the text field, list, and labels are still selected, you can evenly distribute

them in the window by selecting the Distribute Vertically tool from the tool bar. 5. Save your work.

You have now completely finished the user interface of your To-Do List applet.

Note: The entire applet that you are creating is a bean. When you select Bean and then Save Bean from the menu, you are saving the entire applet.

94 Getting Started Correcting mistakes in the Visual Composition Editor

If you make a change in the Visual Composition Editor and then decide that you should have left things as they were, select Undo from the Edit menu to restore your work to its previous state. You can undo as many operations as you want, all the way back to when you opened the Visual Composition Editor for the current bean.

If you undo an operation and then decide that you did the right thing in the first place, select Redo from the Edit menu. Redo will restore the view to the state it was in before the last Undo. As soon as you close the Visual Composition Editor for your bean, you lose any ability to undo or redo changes.

Connecting beans in the To-Do List

Now that you have added the visual beans to create the user interface, the next step is to connect them.

The To-Do List applet is supposed to add the text entered in the text field to the list when the Add button is selected. In this example, you will extend your list to include a model called DefaultListModel. The Java Foundation Classes, also known as Swing, separate data from the view of the data. The actual list items are stored in the list model; an event-to-method connection sends the model’s data to the list in the applet.

Because selecting a button signals an actionPerformed(java.awt.event.ActionEvent) event and adding an item to the list model is performed by the addElement(java.lang.Object) method, the event-to-method connection for adding an item to the list model is between AddButton’s actionPerformed(java.awt.event.ActionEvent) event and the DefaultListModel’s addElement(java.lang.Object) method.

Simply adding this event-to-method connection does not actually cause anything to be added to the list model because its addElement(java.lang.Object) method requires a parameter that specifies what object is to be added to the list. You specify the parameter by creating a parameter-from-property connection. The contents of the text field is provided as the parameter to the addElement(java.lang.Object) method of the list model. Adding a list model and connecting it to the Add button

Because the Swing classes separate data from the view of the data and store the data in the list model we need to drop a DefaultListModel bean onto the free-form surface and create an event-to-method connection that will send the model’s data to the list in the applet.

1. Select the Choose Bean tool from the palette.

Chapter 7. The To-Do List tutorial 95 2. Select Class as the Bean Type from the Choose Bean window. Using Browse with a pattern of de, select the DefaultListModel class:

Click OK and place the DefaultListModel bean on the free-form surface, below the applet (the gray area). By default, the new bean is named DefaultListModel1. 3. Now you can begin your connections to move items into your list. Select AddButton and click mouse button 2. In the pop-up menu that appears, select Connect and then actionPerformed. The mouse pointer changes, indicating that you are in the process of making a connection. If you accidentally started the wrong connection, press the Esc key to cancel. 4. To complete the connection, click mouse button 1 on DefaultListModel1 and then select Connectable Features. Click addElement(java.lang.Object) from the pop-up menu that appears. A dashed line appears, which means that more information is necessary. In this case, the value of the parameter for the addElement(java.lang.Object) method is missing.

5. To make the parameter-from-property connection that specifies what to add to the list, follow these steps: v Move the mouse pointer on top of the dashed event-to-method connection line. v Click mouse button 2. Select Connect and then obj from the pop-up menu that appears.

96 Getting Started v Click mouse button 1 on the text field, and then select text from the pop-up menu that appears.

6. Finally, you must get the To-Do items from DefaultListModel1 to the list in your applet, so that users can see them in the applet. This is a connection that sends data from a source (the model) to a view (the list). Click mouse button 2 on DefaultListModel1. Select Connect and then this from the pop-up window. Click mouse button 1 on the list and select model from the pop-up window. A blue line appears indicating a property-to-property connection, as follows:

7. Save your work. The Event-to-code connection in the To-Do List

Event-to-code programming enables you to associate a handwritten method with an event. So far, you have not needed to write any methods because VisualAge for Java generated them based on your visual elements and connections. To make the Remove button work as we would like it to however, requires some additional logic.

We will use an event-to-code connection to activate the Remove button. An event-to-code connection enables us to specify several behaviors in one method. We could accomplish this without writing code by hand, but in this case, writing the code by hand is more efficient.

Chapter 7. The To-Do List tutorial 97 1. Click mouse button 2 on the RemoveButton bean. In the pop-up menu that appears, select Connect and then actionPerformed. 2. Click mouse button 2 on an empty area of the free-form surface. In the pop-up menu that appears, select Event to Code. The Event-to-Code Connection window appears. By default, VisualAge for Java creates a new method stub called removeButton_ActionPerformed (we renamed the button beans so we could know at a glance which methods belong to which button). This method is scoped to the composite bean class (ToDoList). 3. Enter the following code over the method stub (or copy and paste this section from the Getting Started section of the online help): public void removeButton_ActionPerformed(java.awt.event.ActionEvent actionEvent) { // Grab selected item Object itemToBeRemoved = getJList1().getSelectedValue(); // Remove item from model getDefaultListModel1().removeElement(itemToBeRemoved); // Echo item to text field getJTextField1().setText(itemToBeRemoved.toString()); // Refresh list from model getJList1().setModel(getDefaultListModel1()); return; } This method calls get methods generated by VisualAge for Java to access the beans embedded in ToDoList. For an introduction to some features of the VisualAge for Java IDE that help you write manual code quickly and neatly, see “Writing code by hand”. 4. Select OK to close the window and save the new method.

Your connections should now look like this:

With the user interface complete and the behavior of the applet defined by the connections between the visual beans, you are now ready to test your work.

98 Getting Started Saving and testing the To-Do List applet

You have already saved parts of your applet as you have been working. When you save changes to a bean, you are replacing the old specification of the bean with a new one. When you do this, VisualAge for Java will be using the new specification of the bean for all new uses of it. It is good practice to save your changes to a bean periodically as you are working with it and when you have finished editing it.

Saving your visual bean

In the Visual Composition Editor, do the following: v To save your bean, from the Bean menu select Save bean. A message box appears saying that your bean is being saved and that run-time code is being generated. This generated run-time code is what is used to create your bean when you run your application.

Testing the applet

Now that your work is saved, you can test your To-Do List applet. 1. To begin testing your applet from within the Visual Composition Editor, select

Run from the tool bar. The Applet Viewer starts with your applet in it. 2. When the To-Do List applet appears, experiment with it to ensure that it behaves the way you expect it to. For the To-Do List applet, you need to ensure you can add typed items to the list and remove selected items from the list.

Note: As you design your applet, the Swing beans are presented with Sun’s Metal look. For example, a JButton will look like a Metal JButton as opposed to a Windows JButton. You can add your own code to have your beans rendered in a different system’s look and feel at run time. For example, you could add code to have your beans have a Windows look and feel. Adding this user code is not covered in this document.

Be sure to close the applet window when you have completed your testing.

At any time, you may return to the Visual Composition Editor and make changes, save the changes, then test the applet again.

Congratulations! The first phase of your To-Do List applet is complete.

Saving your workspace

Before you continue, save your workspace. When you save your workspace, you are saving the current state of all the code that you are working on and the state of any windows that you currently have open. To save your workspace, select Save Workspace from the File menu. Your next step in the learning process will be to search for your applet if you are starting VisualAge for Java and returning to a work in progress.

Chapter 7. The To-Do List tutorial 99 Enhancing the To-Do List applet

In the previous section, you used the Visual Composition Editor to do the following: v Add visual beans to the free-from surface to create a simple user interface v Modify visual beans v Add a non-visual bean to store user input v Create event code v Connect events to beans

This section leads you through the steps required to modify and enhance your simple To-Do List applet so that it can save To-Do lists to named files and open files containing To-Do lists.

As you modify your applet, you will learn about: v Adding state checking to your applet v Creating new methods v Adding business logic code in the Visual Composition Editor v Updating the user interface v Running code as an applet or an application

To begin enhancing your applet, you will have to open the Workbench and search for your applet. Let’s look at how the enhanced To-Do List applet will work first.

Note: This section assumes that you have completed the first half of this sample, beginning with the topic “Building your first applet”. If you have not done so already, please complete the steps to add state checking to your To-Do List applet.

How the enhanced to the To-Do List applet will work

Before jumping into the modifications that you will be making to your applet to create the updated To-Do List program, let’s review how the finished program will work.

Here is what the To-Do List program will look like:

100 Getting Started Like your existing applet, the updated To-Do List program adds the text in the To-Do Item field to To-Do List when you select the Add button. When you select the Remove button, the program removes the selected item from the To-Do list.

What about the new buttons? Here is an overview of their behavior: v When you select Open To-Do File, the program loads the contents of a list file into the To-Do List program. v When you select Save To-Do File, the contents of the To-Do List are copied into the list file.

In addition to the differences in interface and behavior, there is one other important difference between the To-Do List applet and the To-Do List program. Because it needs access to the file system to read and write files, the To-Do List program must be run as an application rather than an applet. Java applets are not allowed to access the file system.

You will follow these steps to create the enhanced To-Do List program: 1. Create the new methods. 2. Add the two new buttons. 3. Add a connection from the Open To-Do File button. 4. Test the program to verify your work so far. 5. Add a connection from the Save To-Do File button. 6. Test the completed program.

The following sections describe these steps in detail. We will begin by searching for your applet in the Workbench. Finding your To-Do List applet in the Workbench

When you created your applet in the Visual Composition Editor, you may not have kept track of where VisualAge for Java was putting the code it generated to implement the applet. Before you can continue with the next part of the tutorial, you may need to find your To-Do List applet.

VisualAge for Java provides powerful search capabilities to help you find program elements. To find your applet quickly, do the following: 1. In the Workbench window, select the Projects page.

Chapter 7. The To-Do List tutorial 101 2. From the Selected menu, select Go To and then Type. The GoTo Type window appears:

3. Enter the name of your To-Do List applet (for example, ToDoList)inthePattern field. As you enter the name, the Type Names list refreshes to include only those types (that is, the classes and interfaces) that match what you have entered so far. 4. Select the name of your To-Do List applet from the Type Names list. If packages are listed in Package Names, it means that more than one package has a class with the type name you specified. Select the package in which you created the To-Do List applet and select OK. 5. The list of projects is updated. The project and package that contain your applet are expanded, and the class for your applet is selected.

Now that you have found the class for your applet, you are ready to move on to the next step: creating a version of your applet. Versioning an edition of your applet

When you version an edition of a program element, you give it a name and explicitly save its current state. When you make more changes to the code and save these changes, a new edition is created based on the versioned edition. If you decide you want to undo your changes or try a different set of changes, you can simply return to the versioned edition.

Before you add any enhancement to your To-Do List applet class, version it so you can return to it if necessary. To version the class for your applet: 1. Ensure that the class for your applet is selected. From the Selected menu, select Manage and then Version. The Versioning Selected Items SmartGuide appears.

2. Ensure that Automatic is selected and click OK.If Show Edition Names is selected in the tool bar, a version name appears next to the class.

102 Getting Started The next time you modify this class and save it, VisualAge for Java creates a new edition based on the code in this versioned edition. If you run into problems while you are making updates to your applet, you can return to the working edition of the To-Do List applet that you just created.

Editions are managed by a team of developers in the Enterprise edition. Only owners of editions can version them. Also, versioning is often followed by releasing. For more information on the team development environment, see the online help or the Getting Started document for VisualAge for Java, Enterprise Edition. Adding state checking to your applet

To keep the applet as simple as possible in the first part of the tutorial, we did not include any kind of state checking to the applet. The Add and Remove buttons are always available to the user while the applet is running. This is not ideal behavior for an applet. For example, a user should only be able to select the Remove button if there is an item selected in the To-Do List.

Here is how the Remove button should work: v When the applet starts, the Remove button should be disabled. v When an item is selected in the To-Do List, the Remove button should be enabled. v When a selected item in the To-Do List has been deleted, the Remove button should be disabled.

While this section only deals with the Remove button, you may want to experiment and try to add the same kind of state checking for the Add button.

To get the desired behavior for the Remove button, you need to: v Open the To-Do List applet in the Visual Composition Editor v Set the properties of the Remove button so it is disabled when the applet first starts v Add an event-to-code connection to enable the button when an item is selected in the To-Do List

To begin adding state checking to the Remove button, open your To-Do List applet in the Visual Composition Editor. When the free-form surface appears, it should

Chapter 7. The To-Do List tutorial 103 look like the image below.

Setting up state checking for the Remove button

To set the properties of the Remove button so that it is disabled when the applet starts: 1. Select RemoveButton and click mouse button 2. Select Properties from the pop-up menu that appears. The Properties window appears.

2. Select the field to the right of enabled. Select False from the drop-down list in this field and close the Properties window. The Remove button should now appear disabled:

To add the connection that enables the Remove button when an item is selected in the To-Do List: 1. From the Visual Composition page, select the JList bean and click mouse button 2. 2. From the pop-up menu that appears, select Connect and then Connectable Features. A connection window opens. 3. From the Event list, select listSelectionEvents. The mouse pointer changes to indicate that you are in the process of making a connection.

104 Getting Started 4. Complete the connection by clicking mouse button 1 on the free-form surface and selecting Event to Code. The Event-to-Code Connection window appears. By default, VisualAge for Java creates a new method stub called jList1_ListSelectionEvents(). 5. Enter (or copy) the following code over the method stub: public void jList1_ListSelectionEvents() { if (getJList1().getSelectedIndex() < 0) getRemoveButton().setEnabled(false); else getRemoveButton().setEnabled(true); return; } This method calls the getSelectedIndex() method of JList1. If the method returns -1, no items are selected in the list, and the enabled property of RemoveButton is set to false. Otherwise, enabled is set to true. 6. Select OK to close the window. Your To-Do List should now look like this:

Before you continue, save your work and test it.

To save and test the current state of your work in the Visual Composition Editor: 1. Select Save Bean from the Bean menu.

2. Select Run from the tool bar. 3. The Applet Viewer displays your applet. 4. Experiment with it to ensure that the behavior of the Remove button is correct. Ensure that the Remove button is disabled when the applet starts and then becomes enabled as soon as an item is selected in the To-Do List. Ensure that the Remove button becomes disabled again when nothing is selected in the To-Do List.

Congratulations! You have successfully added state checking to your To-Do List applet.

Now that you have a new level of your code working, you should create another versioned edition of it.

Chapter 7. The To-Do List tutorial 105 Creating a new version of an edition

Because a versioned edition cannot be modified, you will need to create a new open edition from the versioned edition before you can continue changing program elements. For example, if you have already versioned the To-Do List (version 1.0) and then made some changes to it that you want to save in a new version (version 1.1), you would: 1. Select your ToDoList class in the Workbench, and type a new comment in the Source pane. 2. From the pop-up menu in the Source pane, select Save.

Notice that the edition name (in the hierarchy pane) changes from the versioned edition name (for example, 1.1) to a time stamp. Because the workspace can only hold one edition of a program element at any given time, the new edition replaces the versioned edition in your workspace. A copy of the versioned edition can always be retrieved from the repository.) Adding the Open and Save buttons to the To-Do List

You have completed all of the steps that added logic to the ToDoList class. Now you are ready to make modifications to the user interface of the To-Do List applet. Your current To-Do List applet should look like this:

You need to add two new buttons to this user interface: v An Open To-Do File button to trigger opening a file to read into the To-Do list v A Save To-Do File button to trigger saving the contents of the To-Do list to a file

To add these two buttons: 1. In the Workbench, select the ToDoList class for your To-Do List applet. 2. From the Selected menu, select Open To and then Visual Composition.

106 Getting Started 3. The free-form surface appears. It should look like this:

4. Select a JButton bean and add a button under the existing Remove button. Name it ReadButton. You may need to move your Add and Remove buttons or lengthen the free-form surface to make space for your new button. 5. Select the button you just added and change its text to Open To-Do File.To change the text: v Open Properties for ReadButton. v Change the value of text to Open To-Do File 6. Follow the same procedure to add another button below ReadButton. Name it SaveButton. Change the text of this button to Save To-Do File 7. Size the new buttons to match the width of the existing buttons: v Select AddButton. Hold down the Ctrl key and select the remaining buttons so that all four buttons are selected. The last bean selected has solid selection handles, indicating that it is the anchor bean. The anchor bean is the bean that acts as the guide for resizing or the bean that the other selected beans match.

v Select Match Width from the tool bar. 8. Align the two new buttons with the existing buttons: v Select SaveButton. Hold down the Ctrl key and select ReadButton, RemoveButton, and AddButton so that all four buttons are selected. AddButton becomes the anchor bean.

v Select Align Left from the tool bar. 9. Distribute evenly all four buttons:

v Because you have all buttons already selected, click Distribute Vertically on the tool bar.

You have added the two new buttons for the To-Do List program. Now you are ready to associate them with some action.

Chapter 7. The To-Do List tutorial 107 Adding a method for reading files

This section guides you through creating a method called readToDoFile(). This method reads the contents of a list file line by line and adds each line to the DefaultListModel1 instance. 1. Select the ToDoList class. 2. Select Add and then Method from the Selected menu. When the Create Method SmartGuide appears, enter the following method name: void readToDoFile() 3. Select Finish to generate the method. 4. Select the new method and add the code to implement it. If you are viewing this document in a browser, you can select the following code, copy it, and paste it into the Source pane. The finished method should look like this: public void readToDoFile() { FileReader fileInStream; BufferedReader dataInStream; String result; try { // read the file and fill the list fileInStream = new FileReader(FILE_NAME); dataInStream = new BufferedReader(fileInStream); // clear the existing entries from the list getDefaultListModel1().removeAllElements(); // for each line in the file create an item in the list while ((result = dataInStream.readLine()) != null) { if (result.length() != 0) getDefaultListModel1().addElement(result); } fileInStream.close(); dataInStream.close(); } catch (Throwable exc) { handleException(exc); } return; } 5. Select Save from the Edit menu to save your changes and recompile.

Before continuing with the next task, let’s review the code in this method: 1. At the beginning of the method, there are declarations of the fields that are used to manipulate the file and its contents. FileReader fileInStream; BufferedReader dataInStream; String result; 2. Next, statements associate the file with a FileReader and associate the FileReader with a BufferedReader. Using a BufferedReader makes it possible to read the file a line at a time. You defined the static FILE_NAME variable previously. try { // read the file and fill the list fileInStream = new FileReader(FILE_NAME); dataInStream = new BufferedReader(fileInStream); 3. Next, we clear the list. Then, a loop reads the file one line at a time into the String result.Ifresult is not a zero-length String, it adds the value of result to the list model.

108 Getting Started // clear the existing entries from the list getDefaultListModel1().removeAllElements(); // for each line in the file create an item in the list while ((result = dataInStream.readLine()) != null) { if (result.length() != 0) getDefaultListModel1().addElement(result); } 4. At the end of the try block, statements close the streams associated with the file. fileInStream.close(); dataInStream.close();} 5. The catch block passes any exceptions to handleException(). VisualAge for Java generates this method for all visually composed classes. The comment delimiters have been removed. catch (Throwable exc) { handleException(exc); } } ... handleException(Throwable exc) { /* Uncomment the following lines to print uncaught exceptions to stdout */ System.out.println(“————- UNCAUGHT EXCEPTION ————-”); exception.printStackTrace(System.out); } Adding a method for writing files

You have one more method to add to the ToDoList class, writeToDoFile(). This method writes the contents of the list model line by line into into a list file. 1. Select the ToDoList class. 2. From the Selected menu, select Add and then Method. When the Create Method SmartGuide appears, enter the following in the method name: void writeToDoFile() 3. Select Finish to generate the method. Select the new writeToDoFile() method and add the code to implement it. If you are viewing this document in a browser, you can select the following code, copy it, and paste it into the Source pane. The finished method should look like this: public void writeToDoFile() { FileWriter fileOutStream; PrintWriter dataOutStream; // carriage return and line feed constant String crlf = System.getProperties().getProperty(“line.separator”); // write the file from the list try { fileOutStream = new FileWriter(FILE_NAME); dataOutStream = new PrintWriter(fileOutStream); // for every item in the list, write a line to the output file for(inti=0;i

Chapter 7. The To-Do List tutorial 109 { handleException(exc); } return; } 4. Select Save from the Edit menu to save your changes and recompile.

This code is similar to that for readToDoFile(). Before continuing with the next step, let’s review the loop that actually writes lines to the file:

// for every item in the list, write a line to the output file for(inti=0;i

This loop goes through each item in the list model. Each item is appended with crlf (a String consisting of the line separator characters) and written to the file. The line separator characters force each item to be written on a separate line in the file.

Now that we have written some code, lets use the integrated debugger to step through the code and make sure it works the way we want it to. Using the Scrapbook to test code

Before continuing, pause and consider the line separator from the writeToDoFile() method for a moment. Suppose you have never seen this before and you want to see how it works. You can use the Scrapbook window to test out a code fragment that exercises this part of your class.

To test the line separator code: 1. Select Scrapbook from the Window menu. The Scrapbook window appears. 2. Enter the following code into a page in the Scrapbook window: String crlf = System.getProperties().getProperty(“line.separator”); System.out.println(“Here is one line.”+crlf+“And here's another line.”);

3. Select both lines of code and select Run from the Scrapbook window tool bar.

110 Getting Started 4. Select Console from the Window menu. The Console window should look like this:

Notice that the line separator splits the output so that it appears on separate lines. This simple example demonstrates how you can use the Scrapbook window to try out a piece of code quickly and conveniently. Before we begin running the enhanced applet, let’s look at using the integrated debugger to check on the behavior of the applet. The following section describes setting a breakpoint in the writeToDoFile() method in the ToDoList class. Setting a breakpoing in the writeToDoFile class

To set a breakpoint in the writeToDoFile() method in the ToDoList class from the To-Do List program, do the following: 1. Select the ToDoList class in the Workbench. Expand the class to show its methods. 2. Select the writeToDoFile() method. The source for the method is shown in the Source pane. 3. Double-click mouse button 1 in the left margin of the Source pane beside the following line (in the loop that writes items): dataOutStream.write(getDefaultListModel1().getElementAt(i) + crlf); 4. A breakpoint indicator appears in the margin of the Source pane beside this line:

You can also set a breakpoint on a line that does not already have a breakpoint by following these steps: 1. Move the cursor to the line. 2. Click mouse button 2 and select Breakpoint from the pop-up menu.

Chapter 7. The To-Do List tutorial 111 To remove the breakpoint double-click on the breakpoint indicator. You can also remove a breakpoint by moving the cursor to the line containing the breakpoint and, from the pop-up menu, selecting Breakpoint . Using the Debugger browser

The Debugger browser opens automatically when the program you are executing reaches an active breakpoint or has an unhandled exception.

Now that we have set a breakpoint, let’s run the To-Do List program to see what happens: 1. In the Workbench, make sure that breakpoints are enabled: v From the Window menu, select Debug and then Breakpoints.

v Ensure that the Global Enable Breakpoints tool bar button is in the down (enabled) position. If not, click it. v Close the Debugger window.

2. Back in the Workbench, select the ToDoList class. Select the Run toolbar button. 3. When the To-Do File program appears, add at least three items to the To-Do List and then select Save To-Do File. The Debugger browser appears. It should look like this:

The thread you are debugging is selected in the All Programs/Threads list. The list of methods below the thread is the current stack. When you select a method

112 Getting Started in the stack the Variable pane shows its visible variables. The Source pane shows the source where the breakpoint is set.

4. Select the Resume tool bar button to continue execution of the program. Because this breakpoint is inside a loop that writes each item to the file, the thread is suspended again and the Debugger window displays it. 5. Examine some of the variables in the Variable list. For example, to see the value of the loop counter variable i, select i from the Variable pane (it is at the bottom of the list). Its value appears in the Value pane:

This value of the loop counter is exactly what you would expect, because the loop has been run once. 6. Now disable this breakpoint: v Select Breakpoints tab in the Debugger browser. The Breakpoints page appears:

v The Breakpoints page lists all the breakpoints that you have set in the workspace. The Methods pane lists all the methods in which you have set breakpoints. The Source pane displays the source for the method that is selected in the Methods pane.

v To disable your breakpoints, click the Global Enable Breakpoints tool bar button so that it is in the up (disabled) position. The breakpoint indicator changes colors to show that it is disabled. Note that it is not removed, but it will be ignored when the program resumes.

Chapter 7. The To-Do List tutorial 113 v Select the Debug tab to return to the Debug page. 7. You can update and save code in the Source pane of the Debugger window. When you resume execution of the program, you see the changes you made to the code. For example, suppose that you wanted to change the writeToDoFile() method so that items were written to the file in reverse order. You could make this change by modifying the beginning of the for loop to look like this: for (int i = getDefaultListModel1().size(); i >= 0; i—)

Make this change in the Source pane of the Debugger page, and then select Save from the Edit menu. 8. Now select Resume from the tool bar to continue execution of the program. In the To-Do File program, add the following values to the To-Do List and then select Save To-Do File to save them to a file: item A item B item C last item 9. Now select Open To-Do File and open the file you just saved. The To-Do List should look like this: last item item C item B item A

Before you continue, return to the Breakpoints page and enable your breakpoints again by clicking the Global Enable Breakpoints button into the down position. Additional integrated debugger features

The debugger has many other features that you will find helpful for debugging your programs. To learn more about the following tasks, as well as others, see the online help for the integrated debugger.

Set Conditional Breakpoints

Sometimes you want a breakpoint to suspend the thread only under certain conditions. A breakpoint can be configured so that an expression is evaluated before the debugger decides to suspend execution. If the expression includes a boolean that evaluates to true, the breakpoint suspends execution as usual. If it evaluates to false, the breakpoint is ignored.

To configure a breakpoint, click mouse button 2 on its symbol in the margin of a source pane. Select Modify from the pop-up menu. Enter the expression in the field. See the online help for the integrated debugger for more details on configuring breakpoints.

Set External and Caught Exception Breakpoints

Besides setting breakpoints in code in the workspace, you can also set breakpoints on methods in external classes (classes that reside outside the workspace, in the file system, and that are loaded at run time). You can also specify exception types that will break execution if they are thrown, even if your code catches and handles them. See the online help for the integrated debugger for more details on external breakpoints and breakpoints on caught exceptions.

114 Getting Started Step through Code

When a running thread has been suspended, you can step through code line by line or method by method, in a variety of ways. This is a controlled way of checking variable values at each point in your program.

Using Inspectors to View and Modify Variables

You can open an to look closely at a particular variable in a suspended thread. The inspector lets you view and modify variable values and evaluate expressions. Connecting the Open To-Do File button

Now that you have added all the new beans to the free-form surface, you are ready to begin connecting them.

The To-Do List applet should call the readToDoFile() method when a user selects the Open To-Do File button. To implement this, you must connect ReadButton to the readToDoFile() method. 1. Select ReadButton and click mouse button 2. 2. Select Connect and then actionPerformed from the pop-up menu that appears. 3. Click mouse button 1 on the free-form surface and select Event to Code. 4. In the Event to Code window, select readToDoFile() from the Method list and then select OK. The free-form surface should look like this:

5. Save your current work in the Visual Composition Editor by selecting Save Bean from the Bean menu. VisualAge for Java generates code to implement the connections you just specified.

Congratulations! You have implemented the Open To-Do File button. Now you are ready to test the work you have done so far on the To-Do List program. Testing the Open To-Do File button

Now that you have made all the connections for the Open To-Do File button, you are ready to test the work you have done so far.

To test the current state of the To-Do List program:

Chapter 7. The To-Do List tutorial 115 1. Prepare a simple text file to use for testing. Use the Scrapbook window to create a file called todo.lst with the following lines in it: Get a mortgage Buy home Buy 2nd car Renovate home Ask for a raise

Save the file in the project_resources\My ToDoList Project directory. 2. Select Run and then Run main from the menu bar. The To-Do List program appears. 3. Select the Open To-Do File button. The To-Do List in your program should now be loaded with the items from the todo.lst file:

Now that you have tested your current progress on the To-Do List program, you are ready to complete the program by making the connections from the Save To-Do File button. Connecting the Save To-Do File button

You are now ready to make the final connection from the Save To-Do File button.

The To-Do List applet should call the writeToDoFile() method when a user selects the Save To-Do File button. To implement this, you must connect SaveButton to the writeToDoFile() method. 1. Select SaveButton and click mouse button 2. 2. Select Connect and then actionPerformed from the pop-up menu that appears. 3. Click mouse button 2 on the free-form surface. From the pop-up menu that appears, select Event to Code.

116 Getting Started 4. In the Event to Code window, select writeToDoFile(). The free-form surface should look like this:

Congratulations! You have completed the connection from the Save To-Do File button. Your To-Do File program is complete and you are ready to test it. Saving and testing the completed To-Do List program

Now that you have completed the enhanced To-Do List program, you are ready to save and test it.

To save and test your completed To-Do List program: 1. Select Save Bean from the Bean menu to save your changes. VisualAge for Java generates the code to implement all the work you have done in the Visual Composition Editor since the last time you saved. 2. Select Run and then Run main from the menu bar. 3. Try creating and saving a new To-Do file: v Add the following items to the To-Do List. For each item, enter the item in the To-Do Item field and select Add: Get paint Get wallpaper Spouse says OK? Start painting Start wallpapering v Select Save To-Do File. 4. Close the program and then rerun it. 5. Select Open To-Do File. The list that you entered previously should appear in the window.

Congratulations! You have completed a Java program that combines a user interface created in the Visual Composition Editor with nonvisual code that you created directly.

Before you continue, create a versioned edition of the ToDoList class. 1. Select the ToDoList class in the Workbench. 2. From the Selected menu, select Manage and then Version. The Versioning Selected Items SmartGuide appears. 3. Ensure that Automatic is selected and select Finish.

Chapter 7. The To-Do List tutorial 117 The last enhancement to the To-Do List will be to add a counter that counts the items in the To-Do List. Adding a counter to the ToDoList

To add a counter to the ToDoList that will reflect the number of items in the To-Do list at any given time, you need to change the applet as follows: 1. Add labels for the counter name and the counter itself. 2. Connect the Add, Remove, and Open To-Do File buttons to the counter label.

When modified, the running applet will look like this:

Adding the labels

Tip: To make it easier to create the new connections, hide the existing connections

by selecting Hide Connections from the tool bar.

To add the two Labels using the Visual Composition Editor: 1. Select the ToDoList class in the Workbench. 2. Select Open To then Visual Composition from the Selected menu. This opens the ToDoList class in the Visual Composition Editor. 3. Select a JLabel bean from the palette. 4. Click mouse button 1 beneath the list to add the label. You may wish to select the scroll pane, the text field and the labels and move them slightly up to make room for the new label. 5. Modify the text of the JLabel bean to Item Counter: 6. Add another JLabel bean to the right of the JLabel bean you just added. 7. Double-click on this new JLabel bean to open its Properties window. Select the value field to the right of the horizontalAlignment field. From its pull-down menu, select RIGHT, which right-justifies the value. In the text field, change the value to 0, which is the initial value of the counter. Close the Properties window. 8. Align the two new JLabel beans. v Select the counter name label and then the text field; select the Align Left tool. v Select the counter label and then the text field; select the Align Right tool from the tool bar.

118 Getting Started v Select the counter name label and then the counter label; select the Align Middle tool.

The visual beans have been added and aligned. The free-form surface should look like this:

Connecting the labels

To connect the Add button to the counter: 1. Select the Add button and click mouse button 2. From the pop-up menu select Connect and then actionPerformed. 2. Position the mouse over the counter label and click mouse button 1. 3. From the pop-up menu, select text. A dashed green line now appears, indicating an incomplete connection. 4. Select the connection and click mouse button 2. Select Connect and then value from the pop-up menu that appears. 5. Position the mouse over the DefaultListModel bean and click mouse button 1. 6. From the pop-up menu, select Connectable Features to bring up the End connection to (DefaultListModel1) window. 7. From the Property list, select size and then select OK. This provides the count of the list of items as input for setting the counter string. The connection is now complete. 8. Connect the Remove and Open To-Do File buttons in the same manner. You’re simply updating the count of items in the list whenever an action is taken that may modify the count. In this applet, any of the top three buttons have this potential.

Chapter 7. The To-Do List tutorial 119 Now the free-form surface should look like this:

From the Bean menu, select Save Bean. The changes you’ve made are reflected in this open edition, both in the workspace and in the repository. Select the Run tool from the tool bar to launch the applet viewer and see the counter in action. Returning to a previous edition

Your program now contains a counter. It works fine, but after thinking about it for a while, you decide that you want to keep the interface as clean as possible — no bells and whistles. So, now you want to take out the counter code. Of course, you could just delete the labels and connections you’ve added, but you might inadvertently delete one of the other program elements or connections? Do not worry: Remember, you versioned the previous edition!

Follow these steps to replace the current edition with a previous edition from the repository: 1. Select the ToDoList class in the Workbench and click mouse button 2. 2. From the pop-up menu, select Replace With and then select Another Edition. 3. From the Select replacement for ToDoList secondary window, select the edition that you previously versioned and select OK. (Because you want to replace the current edition with the previous edition, you could have also selected Replace With and then Previous Edition from the pop-up menu.)

The edition information beside the class name now indicates the version number, not the time stamp of the open edition you had been working on.

If you change your mind again and decide that the counter should stay, you can always add it back; the edition that contained the counter is still in the repository.

120 Getting Started Chapter 8. The Staff List tutorial

Data access beans in action

In this short example, you will build a simple application that displays employee data from the DB2 SAMPLE database. Note that you must have DB2 installed on your workstation to walk through all of the steps in this sample.

Building this data access application involves: v setting up access in VisualAge for Java to your DB2 database (if you have DB2 installed) v building a user interface called StaffList in the visual composition editor v adding and connecting the required data access beans v testing the finished application

The StaffList application retrieves a list of employees from the SAMPLE database shipped with DB2 and enables you to traverse the list. The finished employee application will look like the user interface shown below:

Building the StaffList user interface

After database access is set up properly (see “Setting up access to a DB2 database” for more information), you are ready to build the user interface for the StaffList application.

Because the basics required for creating projects and adding beans in the Visual Composition Editor have already been covered in the To-Do List sample, the following how-to instructions will not repeat detailed instructions. If you have forgotten the steps required for standard operations, you should review the To-DoList sample. See “Building your first applet” for more information.

Setting up the composite 1. Create a new project named “Data Access Example”. 2. Create a new package named “DAStaffList”. 3. Create a new class as follows: v In the Class name field, type StaffList v In the Superclass field, type javax.swing.JFrame v Click the Browse the class when finished and Compose the class visually check boxes.

© Copyright IBM Corp. 1997, 1999 121 Dropping and setting beans in the Visual Composition Editor 1. Add a title to the JFrame bean by editing its title property. In this example, change the title to Staff List. 2. Drop two JLabel beans. Edit their properties as follows: v Change the text property for the first one to Name v Change the text property for the second one to Position v Resize the labels as necessary so that the entire labels are displayed. 1. Drop two JTextField beans. Change their names to NameTF and PositionTF, respectively.

Your next step is to add the DBNavigator bean to the free-form surface.

1. Click Choose Bean from the beans palette. 2. In the Choose Bean dialog box, click the Browse button. 3. Enter the first few letters of the word “DBNavigator” in the Pattern text box until DBNavigator appears in the Class list. Click DBNavigator in the list and click OK. 4. Click on the free-form surface to drop the DBNavigator bean in the JFrame bean. 5. Align and move components around until they look something like the image below.

6. Save your work. Traversing result sets with the DBNavigator Bean

The DBNavigator bean gives you an easy way of adding to your program element a set of buttons that navigate the rows of a result set and perform various relational database operations.

For example, one of the buttons makes the next row in the result set the current row, and another button commits changes to the database.

The DBNavigator bean is used with a Select bean. The Select bean is used to retrieve a result set from a relational database. The DBNavigator bean operates on the result set.

To use the DBNavigator bean: 1. Add the DBNavigator bean to the Visual Composition Editor surface. 2. Edit DBNavigator bean properties. Among the properties that you edit are properties that specify which buttons will be displayed.

122 Getting Started 3. Connect the DBNavigator bean to a Select bean.

Setting up access to a DB2 database

Building the Staff List user interface

Accessing data with the Select bean Adding and setting the Select bean

Layout of the StaffList user interface is finished. To create a database query, you need to add the Select bean. Adding the Select bean

1. Click Choose Bean from the beans palette. 2. In the Choose Bean dialog box, click the Browse button. 3. Enter the first few letters of the word “Select” in the Pattern text box until Select appears in the Class list. 4. Click on Select. If more than one package is listed in the Package list, click on com.ibm.ivj.db.uibeansto get the correct Select bean. Click OK. 5. Drop the Select bean on the free-form surface, beneath the JFrame containing the DBNavigator bean. VisualAge for Java automatically assigns the name Select1 to the newly dropped bean. Setting up the database connection for the query 1. Open the properties window for Select1. 2. Click the value field for the query property. A small button appears. 3. Select the small button. The Query window appears. 4. On the Connection page, select the New button to the right of the Database Access Class field. A prompter window appears. 5. VisualAge for Java will eventually generate data access code into a separate class that you specify at this point. Enter information about the new data access class as follows: v In the Package field, type DAStaffList v In the Class name field, type Staffers v Select OK to close the prompter window.

The Database Access Class field should now contain the value DAStaffList.Staffers. 6. Select the Add button to the right of the Connections field. The Connections Alias Definitions window appears. 7. In the Connection name field, type staffnames 8. To make sure the connection will be sound, select Test Connection.If everything is set up correctly, the Message window returns The connection is successful. 9. Select OK to close the window.

Chapter 8. The Staff List tutorial 123 VisualAge for Java generates code for the connection into the data access class you specified. The Query window should now look like this:

Assembling the SQL statement 1. Still in the Query window, select the SQL page. The first field, Database Access Class, is already filled in. 2. Select the Add button to the right of the SQL field. The New SQL Specification window appears. 3. Enter information as follows: v In the SQL Name field, type NamesTitles v Verify that Use SQL Assist SmartGuide (recommended) is selected. v Select OK to close the window. At this point, VisualAge for Java starts the SQL Assist SmartGuide and establishes a connection with the SAMPLE database. 4. In the Tables page of the SmartGuide, select the xxx.STAFF table, where xxx is the default user ID established when you installed DB2. 5. In the Columns page, select the columns that you want included in the query, as follows: v From the Columns list, select NAME and then Add. v Select JOB and then Add.

124 Getting Started At this point, the Columns page should look something like this:

6. In the Sort page, specify the primary sort key. From the Columns list, select NAME and then Add. 7. To see your query, select the SQL page. It should look something like this:

8. Select Finish.

VisualAge for Java closes the SmartGuide window, generates code for the SQL query, and returns you to the Query window. At this point, the SQL page of the

Chapter 8. The Staff List tutorial 125 Query window should look something like this:

Select OK to close the Query window and return to the properties window for the Select bean:

Close the properties window and save your work. Connecting the Select Bean

The database query has been set up. The last step is to connect the visual and nonvisual components of the StaffList composite.

126 Getting Started 1. Connect the this property of Select1 to the model property of the DBNavigator bean:

2. Connect the STAFF.NAME_String property of Select1 to the text property of NameTF. Two features by the name of STAFF.NAME_String exist; be sure to select the property. 3. Connect the STAFF.JOB_String property of Select1 to the text property of PositionTF. Two features by the name of STAFF.JOB_String exist; be sure to select the property.

The finished connections should look like this:

Once you have saved your work, you are ready to test your application. Testing the StaffList Application

Test the completed StaffList application as you did ToDoList. Select Run from the tool bar:

Initially, the Staff List window opens with no employee data displayed; the query

has not yet been run. To submit the query to DB2, select .

Linger on some of the buttons on the tool bar. Hover help should be active.

Chapter 8. The Staff List tutorial 127 To traverse the employee list, select or .

Congratulations! You have built a working data access application!

128 Getting Started