
Developing Javabeans Using VisualAge for Java, Version 2 with Cdrom
by Dale R. Nilsson, Peter M. Jakab, Bill Sarantakos, Russell A. StinehourCreate JavaBeans and JFC components using one of the hottest tools available
This valuable guide was written by two IBM insiders who have successfully taught VisualAge for Java to programmers around the world for IBM's certification courses. It gives programmers the inside track on preparing for IBM's certification and explains how to debug Java programs
Overview
Create JavaBeans and JFC components using one of the hottest tools available
This valuable guide was written by two IBM insiders who have successfully taught VisualAge for Java to programmers around the world for IBM's certification courses. It gives programmers the inside track on preparing for IBM's certification and explains how to debug Java programs interactively. Programmers and developers will find helpful coverage of VisualAge for Java's IDE and Visual Builder along with techniques for applying Visual Design Patterns. They'll also learn how to deploy Java applications and applets and create JFC components with version 2.0.
CD-ROM includes VisualAge for Java Enterprise Edition, Sun JDK 1.2 and BDK 1.2, and all of the code examples found in the book.
Editorial Reviews
Product Details
- ISBN-13:
- 9780471345343
- Publisher:
- Wiley
- Publication date:
- 03/28/1999
- Edition description:
- Older Edition
- Pages:
- 448
- Product dimensions:
- 7.40(w) x 9.55(h) x 1.00(d)
Read an Excerpt
Note: The Figures and/or Tables mentioned in this sample chapter do not appear on the Web.
Chapter 2 Building the Hello World Applet
What's in Chapter 2
Now that you have installed all the necessary software and have tested VisualAge for Java by bringing up the Workbench and studying its various views and components, you are ready to start visual programming. In this chapter, you build your first VisualAge for Java application, which is a simple Hello World window. Building this application covers the basic elements of visual programming that you will continue to use throughout this book. First you learn to use AWT controls, then later in the book you will learn how to use the JFC controls.
In this chapter, you will learn how to:
- Set Workbench options
- Create projects and packages
- Work in the Visual Composition Editor
- Use simple Abstract Windowing Toolkit (AWT) beans to design an applet
- Make a visual connection
- Generate Java code
- Build and run a program
If you have closed VisualAge for Java, you need to restart it. The simplest way to start VisualAge for Java is to double-click its icon. To make it easier to access VisualAge for Java, you may want to create a shortcut of its icon. For convenience, you can place the shortcut icon directly on the desktop.
As you remember, when you start VisualAge for Java, the workspace is loaded, and any open windows or views that were opened when you last saved the workspace are reopened. Restoring the workspace to the last saved state can take quite a while, especially if there were many opened windows that need to be reconstructed. One way to avoid this slow startup is to close any unnecessary windows and browsers before you close the Workbench.
Workbench Options
There are a number of options you can set in the Workbench to make it work to your liking. VisualAge for Java Version 2 has a lot of new options that were not available in Version 1. Many of the settings will be unfamiliar to you, and you will probably not change them until you become more familiar with VisualAge for Java. For example, there are a number of warnings that you may want to disable as you become more familiar with Java and VisualAge for Java. Some options change many settings that are familiar to you; for example, the fonts that are used in the different browsers and editor windows.
All customizable options are grouped together in the Options window. Display the options by selecting Window, then Options. . . from the menu bar. The window appears as shown in Figure 2.1. The options are displayed in a tree view for editing. The following sections cover some of the options in the Workbench that you will probably want to change.
First select the General item in the Options list on the left. You will probably want to deselect the Show welcome dialog on startup checkbox, as shown in Figure 2.1. This saves a little time when you start VisualAge for Java by eliminating the startup dialog.
You may also want to deselect the Lock log window open checkbox. The Log window displays messages from VisualAge for Java as you work on Java classes like some versioning messages and messages when classes throw exceptions. Locking the window prevents you from closing or killing it. If you close it and VisualAge for Java has one of these development time messages, the Log window is automatically constructed and displayed. This can be annoying and it is a good practice to keep the Log window around but minimized.
Also on this page, the default behavior is that double-clicking opens a browser for the selected item. This is a change from Version 1 and is what most users expect, so you do not need to change this setting, as shown in Figure 2.1.
Next select the Cache item in the Options list on the left, and they appear as seen in Figure 2.2. This is a new feature in Version 2 and the default settings should be increased to improve performance. After you make a change to any option, it is a good idea to press the Apply button to save the changes.
Next select the Appearance item in the Options list on the left, and these options appear as seen in Figure 2.3. The option to include the type in the field label is selected by default. It is a good idea to select the checkbox to include return type in method label. Even though this may cause some scrolling during development, there are so many methods in Java that it is helpful to have the method return type.
If you prefer the windows in the Workbench that show the Projects and Unresolved Problems views split vertically instead of split horizontally, you need to change that setting from the Workbench. You can set this option by selecting the Window, Orientation, then Vertical or Horizontal. You can then adjust the panes in the Workbench and browsers by dragging them to be larger or smaller. The window sizes and positions are saved as part of the workspace, so when you restart VisualAge for Java you will get the same user interface layout. All the labs in this book assume that you have used the default horizontal orientation.
Changing fonts in the Workbench requires you to set fonts for the different kinds of panes. The font used for the editor and the various colors used for syntax highlighting is set on the Text Editing page shown in Figure 2.4.
To change the way lists appear in the IDE, such as their font and colors, select the Source item in the Options list on the left. VisualAge for Java Version 2 does not let you set bold fonts; this was good for demoing but impractical for cross-platform support. The default font size is 8; you may want to increase it for legibility, or decrease it to display more code.
Next select the Tips item in the Options list on the left, and these options are shown in Figure 2.5. These tips are displayed in dialogs during development and require you to close them as you work. The tips can be helpful for new users, but they can become a nuisance for more experienced users. You may want to deselect the tips as shown in Figure 2.5. The Enterprise Edition has more tips; they are all annoying, so you should turn them all off.
It is a good idea to leave the warnings on. These dialogs appear when VisualAge for Java detects a problem or error, so they can be very helpful.
Other options enable you to set Enterprise Edition features and only appear if you have these features installed. If you have the Enterprise Edition installed and are developing applets that implement Remote Method Invocation (RMI), you can choose whether or not to start the RMI registry and what port to use. If you installed either the Enterprise or the Professional Editions, you can customize which browser to use for displaying the on-line help.
Select the Apply button to save the changes, then the OK button to close the Options window.
The options you have changed are permanently saved only when you exit VisualAge for Java or when you select File and then Save Workspace from the main menu bar of the Workbench.
Your First Applet
Let's get started building your first applet with VisualAge for Java using the Visual Composition Editor.
The process for building this applet will use the iterative development method. You develop the applet user interface first, save your work, and test the Java code by running it in the IDE. You iterate by progressively adding more function and user interface elements, saving, and testing again. Every time you save your work while in the Visual Composition Editor, 100 percent pure Java code is generated and compiled. The program automatically runs if you press the Run button instead of selecting Bean and then Save Bean from the menu bar after compilation is completed. If your program is an applet, the built-in applet viewer starts and loads the applet. If you are developing an application, the main() method is run. This process enables you to see the results of your work a lot quicker than waiting until you have finished developing the program. Iterating also enables you to catch problems before you lose track of what caused them.
A lot of errors are caught directly in the IDE. Every time you save a class or method, the code is compiled and any errors are reported right then and there. This may seem annoying at first, especially if you are used to compiling an entire class or program at a time. VisualAge for Java uses an incremental compiler; it compiles only what is necessary. For example, when you change a method, that method is the only thing that gets recompiled. This actually saves a lot of time, enabling you to concentrate on the particular method that you are coding. Sometimes, especially when you are at the early stages of developing a class, this forced-compile-before-saving process can get in the way, reporting problems about unresolved names just because you haven't written that particular part of the class yet. In most cases though, you can save a method even though it has errors. As you continue developing the class, the errors are resolved. Always make sure that there are no unresolved errors in a class before running and testing your programs. VisualAge for Java gives you a visual cue for classes and methods that contain errors. Either a red or a gray X will mark these unresolved errors. Of course, you can also turn to the Unresolved Problems view in the Workbench to see all outstanding errors.
Creating Projects and Packages
By now, you have customized the Workbench, and you are ready to start building your first VisualAge for Java applet. Applet is a Java class in the java. applet package. In VisualAge for Java, all classes must be part of a package (or at least a default package), and all packages must be part of a project. Before you start designing your applet, you will need to set up a project and a package. You could use one of the existing projects, but it is not a good idea to mix your Java classes in with the projects shipped with VisualAge for Java.
Projects
VisualAge for Java uses projects to organize the packages and classes in the Workbench. Each project has a unique name in the workspace. A standard for naming projects is emerging: Project names are not Java names; they usually start in uppercase and can have multiple words separated by spaces. Before applets or applications can be built using the IDE, a project must be created to contain the package with the beans for the particular applet or application.
With each new project created in the IDE, a subdirectory of the same name as the package is created using the IBMVJava\ Ide\ project_ resources directory as the root. Any packages in the project also cause the creation of a subdirectory descending from the subdirectory with the name of the project. This subdirectory is where the IDE looks for resource files, like the .gif files needed to display graphics on some types of GUI beans. It also stores any resources it creates in that same directory. This is covered in a later chapter using the project_ resources directory. Note that this subdirectory is only created when you first create a project. It is not created when you import a project from another user or system. In that case, you must create the directory and place any resources there manually.
TIP
A resource subdirectory is not deleted when you delete a project from the Workbench. If you are tight on disk space you may want to go to the file system and delete old or obsolete subdirectories in the project_ resources path.
Now let's create a new project for your first application with the following steps:
In the Workbench, click the right mouse button on the upper pane. Select Add Project. You can also create a new project from the menu bar by selecting Selected and then Add Project or by pressing the New Project icon. A SmartGuide to aid you in creating a new project appears as shown in Figure 2.6. Enter My Project in the Create a new project named entry field. Press the Finish button to create the new project.
A new project called My Project was created in the IDE. The next thing to do is to create a package within this project, which will contain all classes of the HelloWorld applet.
Packages
With My Project selected, click the right mouse button on the top pane, and from the pop-up menu, select Add Package. You can also press the New Package icon from the toolbar.
A SmartGuide to aid you in creating a new package appears as shown in Figure 2.7. Enter helloWorld in the Create a new package named entry field. Press the Finish button to create the package.
Packages are Java language elements and represent a logical group of classes that provide related services. Package names make up the directory structure of the classes they contain. Naming conventions are still evolving. The current trend is that package names start in lower case. Usually, when developing commercial packages, the company's Universal Resource Locator (URL) is used to make up the package name. The URL is used backwards; for example, IBM's URL is xxx. ibm. com, and any package names originating from IBM start with com. ibm. xxx. Almost always there is an exception to the rule; that goes for naming conventions as well. You may see some old packages COM. ibm. xxx, with COM in upper case from VisualAge for Java Version 1. This is changed for new packages as a convention starting about October of 1997. If you want to use the latest IBM classes, you will need to reference the new lowercase package names.
When it comes time to deploy your program, packages can be exported out of the VisualAge for Java environment in a single step. There is more on importing and exporting in a later section of this book.
After you create the package, the Workbench should look like Figure 2.8.
Making a New GUI Bean
You might have skipped some of the introductory information at the beginning of this book because you already had the product installed. It is a good idea to follow these first few chapters very closely to begin understanding how the VisualAge for Java development environment works. These initial steps are somewhat detailed to help the novice user become familiar with the graphical user interface and the tightly integrated IDE of VisualAge for Java. As you progress through the book, the steps will become briefer.
Now you will construct a simple applet that is just a window with the words Hello World and the current date in it. It is probably the simplest program you can build, and it is a good way to familiarize yourself with the IDE. You will use the same steps when building more complex applications. In fact, you use these same steps throughout this book to build all the visual components of the exercises.
Because you have already defined the project and the package in the IDE, you can start defining the parts that will make up the applet. The project and package provide the structure for the IDE to contain and catalog your classes/ beans in the repository. First, you will build and run the helloWorld visual (or GUI) bean. Later, you will make a few changes to the user interface and add some function using connections, save your changes, and re-run the applet. Start building the Hello World applet by following these steps:
With the helloWorld package selected, click the right mouse button on the top pane and from the pop-up menu, select Add, Class. . . . You could instead select the New Class icon on the Workbench toolbar.
NOTE In VisualAge for Java Version 2 there is a separate SmartGuide for creating Interface classes. This was done to simplify the SmartGuides.
In the Create Class SmartGuide, seen in Figure 2.9, enter HelloWorld in the Class Name entry field.
Naming conventions for Java classes are well defined. Class names start in uppercase, the beginning of each new word is also in uppercase, and no spaces are allowed. The SmartGuide warns you if you don't follow this convention. If you made a mistake entering the class name, the SmartGuide can automatically correct it.
Initially, Hello World will be developed as an applet, which means it can only run inside a Web browser or an applet viewer. To make an applet, the superclass for the HelloWorld class must be Applet.
You indicate the superclass by either typing the fully qualified name of the parent class in the Superclass entry field (in this case, java. applet. Applet). If you are not sure of the complete name, you can press the Browse button opposite the Superclass entry field, which displays the Class Qualification window.
>As you start typing the word Applet in the Pattern entry field, the choices in the Class/ Interface Names list are narrowed down. See Figure 2.10.
After you have finished entering applet, the Applet class from the java. applet package should be selected. Once Applet is selected, press the OK button.
On the Create a Class window, make sure that the Browse the class when finished and the Compose the class visually items are selected, as shown in Figure 2.9. This option automatically opens the class browser to the Visual Composition Editor. Press the Finish button to complete creating the HelloWorld class.
The Visual Composition Editor opens as shown in Figure 2.11. This window enables you to place the visual components that make up the HelloWorld applet.
Getting Acquainted with the Visual Composition Editor
The Visual Composition Editor is also referred to as Visual Builder, because it is used to visually build your beans. It is the default view when you open a GUI bean, and it provides a lot of support for creating and modifying beans. You design the entire graphical user interface (GUI) for an application in the Visual Composition Editor.
The Visual Composition Editor is where you combine beans using visual connections to make composite beans and applications. The areas of the Visual Composition Editor are shown in Figure 2.12.
Categories and Beans
The Beans Palette is changed from Version 1; it is one column of icons on the left side of the Visual Composition Editor. The top of the column is a dropdown list of categories that can be selected. These categories hold beans grouped by common types like AWT, JFC, and so on. The column holds the beans contained in the currently selected category. Each category may contain many beans, so the arrows at the top and bottom of each column enable you to scroll through the category.
Hover help appears when you place the mouse pointer over a bean and hold it there for a short time. Hover help makes it a lot easier to find the bean you need. A complete list of the default categories and beans is shown in Figure 2.13. It is a good idea for you to copy it and have it handy as a reference until you become familiar with the available categories and beans.
The Free-Form Surface
The large blank area in the center of the panel is called the free-form surface (see Figure 2.12). This is where you construct the user interface for the application and where you add nonvisual beans or logic beans, those that represent business logic for your program. The free-form surface grows as you add more beans. You may have to scroll the free-form surface to reach beans that are not in the current work area.
The free-form surface shows GUI beans exactly as they appear at run time. If your main bean is a Frame, its startup position is the same as the position of the window in the free-form surface, unless you write code to change its position.
Using Toolbars
Just like many of the applications available today, the Visual Composition Editor has toolbars to make it easier for you to select functions. These are first-generation toolbars with very basic functions like showing a group of icons and enabling you to cause actions by pressing the icons. You can now choose to hide the toolbar by selecting Window, Options, and Appearance page. Unfortunately you can not add your own buttons and functions to the toolbar. Many applications have second-generation toolbars that support drag and drop, have multiple views, and can be modified by the user at run time. However, you can edit and change the categories and folders in the bean palette.
Visual Composition Palette Bar
The menu bar has equivalent items for all the icons on the toolbar, except the Run button that is located on the left end. If you need more screen real estate in the Visual Composition Editor, you can hide the Palette bar on the left of the window. You can do this by selecting the bar on the right side of the palette and directly narrow the palette. The size of the palette is not saved with the bean as in version 1, but it is part of the Workbench settings. The next time you open the bean, the Visual Composition Editor does not display the toolbar. This will magically become the default setting for all Visual Composition Editors. In the sample illustrations in this book, we show the toolbar.
Making an Applet
Because you are creating a new GUI bean and you selected Applet as the parent class (or superclass), the Workbench opened with an Applet object in the free-form surface, as shown in Figure 2.11.
Applet provides very rich default behavior. The Applet class is a subclass of Panel, as shown in Figure 2.14. It has all the display functions of a panel along with the ability to be loaded in a browser. Because the applet will run in a Web browser, it can't be resized and repositioned at run time.
Look at the Hierarchy view by selecting the Hierarchy tab on the HelloWorld window.
An AWT Applet acts like a canvas or panel; it is a Container of Components. You can place other AWT components like Buttons, Labels, TextFields, and many other types of GUI elements directly on an applet. Let's go back to the Visual Composition Editor and start adding components to the HelloWorld applet.
Select the Visual Composition tab on the HelloWorld applet.
Place the mouse pointer in the middle of the Applet and press the left mouse button to select the applet. The name of the selected Applet appears in the information area at the bottom of the Visual Composition Editor.
User interface beans are usually placed and positioned on canvases. AWT provides several layouts that are used with panels to control the spacing and alignment of GUI elements contained in the panel. Because the HelloWorld applet is your first project, it is very simple and uses a null layout manager, which is technically the same as not using a layout manager. With a null layout manager, you are free to place and size other components on the applet anywhere you wish. The use of a null layout manager is highly discouraged and considered poor design. Later, this book covers the standard layout managers by using them in other sample applications.
HelloWorld is basically an applet with text saying Hello World. Because the Applet class inherits from the Container class, it is capable of containing other GUI elements that can display text. The proper class to use for this purpose is the Label class. Add a label to the applet with the following steps:
From the AWT category, select the Label icon using the left mouse button.
You have now loaded the mouse pointer with a Label bean to drop on the applet. You can see that it is loaded because the mouse pointer appears as a cross hair as it is moved over the free-form surface. If you picked the wrong bean, just go to the correct icon on the palette and select that icon. You can unload the pointer by selecting the arrow icon (also called the Selection tool) on the toolbar.
Move the mouse to the applet and press the left mouse button to place the Label bean.
You now have a Label on the Applet; your Visual Composition Editor should look like Figure 2.15.
Naming Beans
You can select the various beans on the Visual Composition Editor by clicking the mouse pointer over them. Select the Label bean you have just added. Looking at the bottom of the screen, in the information area, you see the name of the bean currently selected, in your case, Label1. Beans are given default names as they are dropped on the applet. You should always name your beans using names that describe their function. This becomes very important as the components you build become more complex. The code generator uses the name you give a bean; using good names will help you in debugging and understanding the generated code. To change the name of a bean, you have two options:
- Select the bean and click it with the right mouse button. Select Change Bean Name from the pop-up menu. Enter a meaningful name in the window provided.
- Double-click on the bean. This brings up the bean property sheet. In this window, you can change many properties of the bean, one of which is beanName.
Using either of these methods, change the name of the Label1 bean to LBHello. The convention for bean names is that they start with uppercase and the first letter of all other words in the name is in uppercase. Bean names should reflect the type of the bean; that is why you named this bean LBHello.
Editing Text
The default text for the LBHello bean is Label1. For this applet, the text should be Hello World. To change the text for the label:
Double-click on the bean. This brings up the bean property sheet. In this window, you can change many properties of the bean, one of which is text. See Figure 2.16.
Enter Hello World in the text property and close the property editor. You can see the beanName in the property editor.
NOTE
Direct editing of the bean's text is not supported in VisualAge for Java Version 2. This is when you place the tip of the mouse pointer on a GUI bean, and press and hold the Alt key and the left mouse button. A small editing window allowed direct editing.
Changing Fonts
You probably need to stretch the LBHello Label to accommodate the full text. Now, that looks a little bit better, but it is still pretty plain. Let's change the font size and foreground color to make it look even better with the following:
Select LBHello by clicking once on the words Hello World.
Open the property sheet for LBHello by either pressing the right mouse button and selecting Properties, or by double-clicking the left mouse button. You can also press the Properties button on the toolbar.
Find the font property in the table. Click at the right end of the entry field for font. A small button appears; click it. This displays the Fonts window, as seen in Figure 2.17.
Select a font type, size, and style that looks good to you. For example, you could use a bold italic style and a size of 24 points.
Select OK on the Fonts window to close it; then close the property sheet to save your changes.
Your text should look like Figure 2.18. If the words Hello World appear clipped when the new font is applied, you have two choices:
- Select the Label bean and stretch the label by dragging one of the little black boxes or handles on the label bean until all of the text is displayed.
- Select the Label bean, bring up its property editor, and edit the width in the constraints properties to make it big enough to accommodate the text.
Generating Java Code
The next step is to save the applet and run it. As mentioned before, saving the bean also generates the Java code for all components in the Visual Composition Editor.
Select Bean and then Save Bean from the menu bar to save the applet. A new edition is created for the bean and stored in the repository; it also becomes the current edition in the workspace. The Java code for the HelloWorld class is generated and compiled.
To run the applet, press the Run icon on the toolbar.
Pressing the Run button causes the bean to be saved and recompiled. It is equivalent to performing the two steps with just one button. The HelloWorld applet runs in the applet viewer as seen in Figure 2.19. There is really nothing spectacular in Hello World, except that you just created your very first Java applet with VisualAge for Java. It compiled and ran without errors and you didn't have to write a single line of code! Real VisualAge for Java programs require that you write code, and you will have a chance to do this soon. You can rely on VisualAge for Java to generate most or all of the code for the user interface.
You are probably interested in seeing the generated code. It can be seen in either the Methods or the Hierarchy view for the HelloWorld class.
Select the Methods view for the HelloWorld window, as shown in Figure 2.20.
You see a number of methods, as shown in Figure 2.20. These methods are:
- HelloWorld()
- main()
- getAppletinfo()
- getLBHello()
- handleException()
- init()
The HelloWorld() default constructor is required for JavaBeans and needed for the Visual Composition Editor. It merely calls its superclass constructor.
Previously, we noted that one of the differences between Java applets and applications is that applets run within the confines of a Web browser and are governed by the security model for applets. Applications have their own frame, run stand-alone, and are not subject to the same security model as applets.
Applets start running when the Virtual Machine (VM) in the Web browser constructs the Applet instance and calls the init() and start() methods. Applications start running when a stand-alone VM is started with the name of the class that contains the main() method. After instantiating the object, the main() method is called and execution starts.
You might be wondering why there is a main() method in the generated code of an applet. VisualAge for Java generates this method for all visual components. It exists so components can be tested in a stand-alone environment. Many times, you will develop components, such as panels, that cannot be run on their own. In order to test them, you would have to wrap them in an Applet or a Frame. To save you that trouble, VisualAge for Java generates a main() method for them.
public static void main( java. lang. String[] args) {
try {
java. awt. Frame frame;
try {
Class aFrameClass = Class. forName
(" com. ibm. uvm. abt. edit. TestFrame");
frame = (java. awt. Frame)
aFrameClass. newInstance();
} catch (java. lang. Throwable ivjExc) {
frame = new java. awt. Frame();
}
HelloWorld aHelloWorld;
Class iiCls = Class. forName
(" helloworld. HelloWorld");
ClassLoader iiClsLoader =
iiCls. getClassLoader();
aHelloWorld = (HelloWorld)
java. beans. Beans. instantiate
(iiClsLoader," helloworld. HelloWorld");
frame. add(" Center", aHelloWorld);
frame. setSize( aHelloWorld. getSize());
frame. setVisible( true);
} catch (Throwable exception) {
System. err. println(" Exception occurred in main
() of java. applet. Applet");
exception. printStackTrace( System. out);
}
}
Let's examine the generated main() method for the aHelloWorld applet in more detail:
- The main() function starts the application.
- A specialized kind of Frame, a TestFrame, is instantiated to hold the Applet. This frame knows how to close itself.
- A new HelloWorld bean is allocated in memory by the java. beans. Beans. instantiate call to the class loader.
- The new aHelloWorld instance is added to the center of the frame object.
- The size of the frame is set to the size of the applet.
- The frame is set to be visible and, by doing so, given focus.
- When the frame is closed, the aHelloWorld instance is destroyed.
All of this is coded within the proper, and necessary, try and catch blocks to handle any exceptions that might occur. There will be more on exception handling in a later chapter.
The HelloWorld window can be repositioned on the screen by pointing to the title bar, holding down the left mouse button, and moving the window. You can also change the size of the HelloWorld window by selecting one of the window edges with the left mouse button and moving the mouse. As the window resizes the Hello World text stays in the same relative position in the window because the applet has no layout manager associated with it. In a later chapter you learn how to use layout managers to improve this behavior.
When you are done with the HelloWorld window, select the system icon in the upper left corner of the applet viewer and select Close to end this applet.
Adding More Function to Hello World
Now that you have built a very simple applet, you can add more function and iterate on the Hello World program. Return to the HelloWorld Visual Composition Editor.
You will add function to show the current date in the applet. You will add another Label and a Date class and make a visual connection to complete this function. This is accomplished, without writing any code, using the following steps:
1. Click on the Label icon using the left mouse button.
2. Move the mouse pointer to the applet below the Hello World text, and press the left mouse button to drop the Label bean onto the applet.
3. Name this bean LBDate. (See "Naming Beans" earlier in this chapter.)
This bean will hold the current date read from the system. Stretch this Label bean so that it accommodates all the characters for a time stamp. Next, you will add a Button bean that will set the Label to display the current date.
1. Click on the Button icon using the left mouse button.
2. Move the mouse pointer to the applet below the Hello World text, and press the left mouse button to drop the Button bean onto the applet.
Now the applet has a Button. To change the default text of Button1, directly edit the text on the bean:
1. Open the property editor for the Button1 bean by double-clicking the mouse over the bean.
2. Enter Set Date in the Label property.
3. Name this bean PBSetDate.
The HelloWorld bean should now look like Figure 2.21.
Selecting Beans
As you have seen, the left mouse button is used to select the beans. To select multiple beans, select the first bean; then press and hold the Ctrl key and click the left mouse button over any other beans you wish to select. The last bean selected is the one used as a reference when aligning all selected beans.
The beans on the applet need to be aligned so that they are centered. The default layout in the Visual Composition Editor is null.This means that no alignment or sizing is done within the applet at run time. This can create some serious problems when you run your applet at a different resolution. As mentioned previously, this book covers layouts in a later chapter.
Using the Ctrl key, select the LBDate, the Hello World Label, and the PBSetDate button. All of the selected beans have boxes around them, and the last bean selected has black boxes or handles to indicate it will be used as a reference.
Press the align center icon to position the GUI beans in the applet.
There are also buttons to align to the left, right, top, bottom, and middle. You can try these functions to see what they do, but they only work on a null layout.
Making Connections
When the applet runs and the user presses the PBSetDate button, it should set the text of LBDate to the current date. To achieve this without VisualAge for Java, you would need to write some Java code. VisualAge for Java introduces the construction from parts paradigm, which enables you to build event-driven logic by connecting predesigned components. First, add a Date bean to the applet with the following steps:
At the top of the bean palette, select the Choose Bean Button, and the Add Bean window appears.
In the Class Name field, enter Date, and then select the Browse button. You must fully qualify any Java classes you add to an applet. The java. util package is the only currently loaded package with a Date class, so it is high-lighted.
Select the OK button to close this window. Enter aDate in the Name entry field to properly name this bean as seen in Figure 2.22.
Select the OK button to close the Choose Bean window. Now the cursor is loaded with the Date bean. Move the mouse to the free-form surface and press the left mouse button to place the Date bean. Notice that because aDate is not a GUI bean, you are not allowed to drop it on top of the Applet.
Make a connection from the PBSetDate button to the LBDate bean to set it with the current date when the button is pressed, as follows:
Place the mouse over the PBSetDate button, and press the right mouse button to get the context menu.
Select Connect from this menu. This displays the preferred features list for a Button bean seen in Figure 2.23. This is a short list of the most commonly selected connection items. Some items on the preferred list can be disabled or gray. The Visual Composition Editor prevents you from making some types of improper connections by graying out improper or invalid options.
Select the actionPerformed Event by clicking the left mouse button. This is the source of the connection.
The mouse pointer changes its shape and looks like a spider attached by its web to the source of the connection. Now select a target for it. The spider needs a place to land.
Move the spider to LBDate in the HelloWorld applet, and press the left mouse button to select the target for the connection. Notice that as the spider pointer moves over the objects on the Composition Editor, they receive focus clearly indicating the object you are about select.
This displays the preferred features list for the Label object shown in Figure 2.24.
Select the text item on the menu. Now you see a dashed line connecting the PBSetDate and the LBDate objects. A dashed line indicates that the connection is incomplete. For now, this is correct, because we haven't yet told the connection what to set as the text when the button is pressed. A parameter is missing.
To complete the connection, pass a parameter into the connection with the following steps:
Move the mouse pointer so its tip is on the line representing the connection; press the left mouse button to select the connection. This displays a description of the connection listed in the information area at the bottom of the Visual Composition Editor. This is one way to find out what a connection does. Now make the following connection to pass the current date to the Label:
Select the connection from PBSetDate to LBDate.
Making sure that the tip of the mouse is not over one of the handles or black squares on the connection, press the right mouse button to display the pop-up menu.
Select Connect, then select value.
Move the mouse to the aDate object on the free-form surface; then press the left mouse button.
Select Connectable Features; a dialog appears. Select the methods radio button, and select the Date() constructor method to complete the connection and close the connection window. The HelloWorld applet should look like Figure 2.25.
Saving and Running the Improved Hello World Applet
Now you are ready to save and test your changes. It is really easy in the IDE: Just
select the Run button on the toolbar. The Visual Composition Editor saves the changes and compiles them into the workspace image. When you run the HelloWorld applet, it looks like Figure 2.26.
When the applet starts, the date does not appear in the LBDate object; you see the default text of Label1. When you press the Set Date button, the date and time replace the default text.
As you can see, it is very easy to create a graphical application with some basic function without writing any code! VisualAge for Java can generate most or all of the user interface code for your applications. Visual connections enable you to call methods in Java classes using event-driven programming.
Viewing the Generated Code
For this simple sample, you can review the code generated by VisualAge for Java by switching to the Methods or Hierarchy view of the browser. Probably the most interesting piece of code in this applet is the code generated by the connection. Note that connections in the Visual Composition Editor are just development artifacts. They are translated into 100-percent pure Java code when the code is generated.
To see the generated code for any connection, the first step is to find out the connection number. You do this by selecting the connection (clicking it with the mouse) and looking in the information area of the Visual Composition Editor. In this case, we are interested in connEtoM1; a corresponding connEtoM1 method can be found in the Methods view. Notice that not all connections are translated into code: In this example, there is no method called connPfromM1 for the parameter connection. See following code segment for the connEtoM1 generated code:
/**
* connEtoM1: (PBSetDate. action. actionPerformed
(java. awt. event. ActionEvent) --> LBDate. text)
* @param arg1 java. awt. event. ActionEvent
*/
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoM1 (java. awt. event. ActionEvent arg1) {
try {
// user code begin {1}
// user code end
getLBDate(). setText( String. valueOf
(new java. util. Date()));
// user code begin {2}
// user code end
} catch (java. lang. Throwable ivjExc) {
// user code begin {3}
// user code end
handleException( ivjExc);
}
}
There are a number of interesting points to observe in the code segment for the preceding connEtoM1 method.
- Comments are inserted at the beginning of the class. They are in Javadoc format and can be generated to an HTML file using VisualAge for Java.
- Possible exceptions are handled by generating the appropriate try and catch blocks.
- The code for this method is regenerated every time anything is changed and saved for the HelloWorld applet. Any modifications to this method will be lost the next time code is generated. To preserve your modifications, make them inside one of the user code areas.
// user code begin {1}
// Your code here
// user code end
- You cannot make your own user code areas, but you will find that they are automatically generated in the appropriate places.
- This line of code does all the significant work in the method getLBDate().
getLBDate(). setText ( String. valueOf( new java. util. Date()));
In Java, like in C++ and Smalltalk, messages to an object can be chained as long as the return type of the message is compatible with the next message. In this case, getLBDate() gets a reference to the LBDate object. If you look in this method, you will see that if it doesn't exist, the LBDate object is created. The setText() method, just as its name implies, sets the text of LBDate.
The next instruction is really the code generated by connPfromM1, the parameter for the connection. The code String. valueOf( new java. util. Date(), makes a new Date object, and then asks it for its string representation, which in the case of a Date object is a formatted String with the date and time the object was created. Each time this method is called, it will construct a new Date object. So each time you press the press the Set Date button, the current date is displayed. Pretty cool for not writing any code.
Now you can see why naming your beans is important. Reviewing the generated code would be a lot more difficult with the default bean names.
Summary
Well, you are off to a good start. You built a very simple Java application using VisualAge for Java. In this chapter, you did the following:
- Became familiar with making projects and packages
- Customized the Workbench with options
- Learned the basic workings of the Visual Composition Editor using simple beans to design an applet
- Made some visual connections
- Edited beans to change their default attributes
- Saved a JavaBean definition and generated Java code
- Ran the compiled applet and saw the many default features of the application by using AWT
Meet the Author
Customer Reviews
Average Review: