+ All Categories
Home > Documents > Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet”...

Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet”...

Date post: 24-Sep-2020
Category:
Upload: others
View: 0 times
Download: 0 times
Share this document with a friend
48
Chapter 1 Creating your first Java program Chapter contents What a concept Before you begin Setting up your project Your first applet Removing tasks Limiting the number of tasks Sorting tasks Publishing your applet Creating an application Running an application outside VisualAge for Java Time required 4 hours Files required /solutions/chapter1/vptut1aa.jar So, you’ve bought the book and you’re ready to plunge into visual programming in Java. Before you install the product and create applications, let’s start with an over- view of visual programming and why Java is uniquely suited to this type of programming.
Transcript
Page 1: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Chapter 1

Creating your first Java program

Chapter contents

u What a concept

u Before you begin

u Setting up your project

u Your first applet

u Removing tasks

u Limiting the number of tasks

u Sorting tasks

u Publishing your applet

u Creating an application

u Running an application outside VisualAge for Java

Time required

u 4 hours

Files required

u /solutions/chapter1/vptut1aa.jar

So, you’ve bought the book and you’re ready to plunge into visual programming inJava. Before you install the product and create applications, let’s start with an over-view of visual programming and why Java is uniquely suited to this type ofprogramming.

Page 2: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

What a conceptVisual programming lets you build applications from reusable parts called beans.It’s a powerful tool because it lets computer users create applications themselves,without having to write code or employ a programmer.

Visual programming terminologyAll of the components that make up a program are also called objects. The objectterminology is used in many different programming languages, such as Visual Ba-sic and C++. In Java, reusable components are called beans.

For example, Figure 1-1 shows a simple to-do list in which you enter a task in onefield and then click a button to add the task to a task list. Each of the three interfaceitems is a bean that already has functions associated with it. For example, the but-ton has an event that you use to tell what happens when the button gets clicked.You link that property with whatever object will change when the button is clicked,in this case the task list. (The other connections are explained in the “Making con-nections” section under “Your first applet.”)

JavaBeansA bean is a reusable Java software component that can be manipulated visually in abuilder tool and conforms to Sun Microsystems’ JavaBeans specification. Beanscan be GUI elements or may have no GUI appearance at all; they are visually com-posed using a visual builder. The three most important features of a bean are prop-erties, methods, and events.

2 Chapter 1: Creating your first Java program

Figure 1-1: A simple TO-DO list applet

Page 3: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Properties are named attributes associated with the bean that can be read or written.

Methods are code fragments that can be called from other components.

Events provide a way for one component to notify other components that a certainaction has occurred.

Visual Composition EditorTo create programs visually, you need an easy-to-use tool. VisualAge for Java pro-vides such a tool in its Visual Composition Editor. You use Visual CompositionEditor to design the interface for your programs and specify the behavior of theprogram. VisualAge for Java generates the Java code under the covers, so that youcan design, implement, and debug your applications without getting into the se-mantics of coding Java.

Let’s take a closer look at our visual application. Figure 1-2 shows the Visual Com-position Editor.

3What a concept

Figure 1-2: The Visual Composition Editor

Page 4: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

To the left of the window is a palette containing all the components or beans avail-able. We placed three objects on the page: an Add button, a field for entering text,and a list that displays all the tasks. We told the components how to interact byconnecting them. So, when you click the Add button, it takes the text from the en-try field and adds it to the list.

We used the following connections to specify the interactions:

1. Connect the Add button to the TaskList. When the Add button getsclicked, the task is added to the list.

2. Connect the first connection to the TaskTextField. This tells the Addbutton where the task comes from; it gets it from the TaskTextField.

3. Connect the Add button to the TaskTextField for cleanup; after the taskhas been put on the list, it is removed from the TaskTextField.

4. Connect the Add button to the TaskTextField to put the cursor at thebeginning of the field.

Don’t try to understand all the details of this application right now; we’ll explain itin the “Your first applet” section. Figure 1-2 simply shows you the basic steps usedin visual programming: First you lay out the components of the interface, and thenyou “make it work” by connecting the components together to specify how theyinteract.

VisualAge for Java creates the applet for you, and even provides the HTML to callit. This to-do list applet can run in anyone’s Web browser on any operating system.So, let’s learn how to build the ToDoList.

Before you beginAre you skeptical about this whole visual programming concept? Do you needsome proof that you can make computers do what you want without having to writecode? This chapter eases you into visual programming, starting with the basic con-cepts and gradually adding more beans until you have a complete application: aToDoList that you can easily change and save for later use.

Chapter 1: Creating your first Java program4

Page 5: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

To create this application, we use VisualAge for Java, a great tool for heavy-dutyJava programming that also contains a great tool for you called the Visual Compo-sition Editor.

What you will createIn this chapter, you will develop a simple ToDoList tracking applet like the one inFigure 1-3. In the process, you’ll learn how software development can be donewithout manual coding.

You’ll begin by creating an applet, as shown in Figure 1-3, that can run in anyHTML browser. Then you’ll add the ability to save the ToDoList to a file and readit back in. Finally, you’ll turn the applet into an application that can run outsideyour browser.

What you will need

To follow along with the steps in this chapter,you need the following:

■ IBM VisualAge for Java Version 4.0:Install this from the CD included withthis book. See the Appendix for

Before you begin 5

What’s an applet?

An applet is a downloadableprogram that runs in a Webbrowser. Typically, an applethas restricted access to theclient system for securityreasons.

Figure 1-3: The applet you’ll create

Page 6: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

installation instructions. (If you prefer to use a previous version, you canalso use either version 3.02 or version 3.5.)

■ Beans and solution files from the /solutions/chapter1/ subdirectory on thevisual programming CD. This subdirectory contains vptut1aa.jar and thesolution file for the final application we’ll create in this chapter.

The vptut1aa.jar file contains free evaluation versions of all the beans that are nec-essary for the creation of the ToDoList application. The file contains beans fromthe following packages:

■ UIControls (for the BoundList and BoundTextField beans)■ Comparators (for the Less bean)■ FileManagement (for WriteFile and ReadFile beans)■ WiringHelpers (for the Iterator and Step beans)■ Sort (for the Sort bean)

Setting up your project

Before you can build your first applet, you need to do some set-up work inVisualAge for Java, specify where your applet will be saved, and bring all the nec-essary components into VisualAge for Java. In VisualAge for Java, you view all ofyour existing code in the Workbench window. The code is organized into projectsand packages; the projects can contain multiple packages.

Starting VisualAge for Java

To create a program, you first have to launch your development environ-ment—VisualAge for Java.

1. Start the VisualAge for Java integrated development environment bylocating and double-clicking its icon (on the folder or task bar).

2. If it starts up correctly, after a few seconds, the VisualAge for JavaWorkbench appears on your screen, as shown in Figure 1-4.

Chapter 1: Creating your first Java program6

Page 7: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Now, you can create the new project.

Creating the project

1. To create the project, right-click on an empty area in the project listpane of the Workbench and choose Add—>Project from the pop-upmenu.

Setting up your project 7

Figure 1-4: The VisualAge for Java Workbench

Page 8: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

2. In the SmartGuide window that appears, enter the name of the projectyou want to create, as in Figure 1-5 (in this case, it is the ToDoListproject).

3. Click Finish.

4. The new project ToDoList appears in the Workbench window.

Importing beans in VisualAge for JavaIn VisualAge for Java, you can save your work asJARs or as repositories. We’ve provided a JAR foryou so that you can have all the necessary compo-nents for creating the ToDoList application. You needto import the vptut1aa.jar file into your project. Thevptut1aa.jar file provides all of the beans that areneeded for this chapter. But before you can use any ofthe beans, you need to get them into VisualAge forJava.

Chapter 1: Creating your first Java program8

What are JARfiles?

Beans are packagedand delivered in JARfiles. JAR files are usedto collect class files, im-ages, help, and otherresource files.

Figure 1-5: Creating a project

Page 9: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

1. Since you just created the ToDoList project, it is selected. Right-clickon the project pane and select Import from the pop-up menu.

2. In the SmartGuide window that appears, select the Jar file radio buttonand click Next.

3. In the next page of the SmartGuide, choose the vptut1aa.jar file fromthe /solutions/chapter1/ subdirectory on your visual programming CD.

4. Click Finish.

Modifying the palette

1. The Modify Palette window now appears. Click the New Categorybutton. Enter the name for the new category, which is ToDoList.

2. Choose all the beans from the Available beans list, as shown inFigure 1-6.

3. Click the Add to Category button. This adds the selected beans to thenew ToDoList category.

Setting up your project 9

Figure 1-6: Modifying the palette

Page 10: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

4. Click OK.

5. The new packages appear in the Workbench under the ToDoList pro-ject: com.ibm.uicontrols, com.ibm.wiringhelpers, com.ibm.compara-tors, com.ibm.sort, com.ibm.filemanagement, and so forth.

Importing the .dat file in the repositoryWe’ve also provided a repository for you so that you can see the final wiring of theapplication. You might want to import this example if you have any problemsworking through this chapter. VisualAge for Java saves repositories as .dat files, soyou need to import the /solutions/chapter1/vptut1aa.dat file into the VisualAge forJava repository (a fancy name for the class libraries that VisualAge for Java can ac-cess). The vptut1aa.dat file includes the final sample application that you willbuild. However, you should build your own as we go along, so we’ve named oursolution application ToDoListFinal, with a package name ofToDoListPackageFinal, whereas you’ll call yours ToDoList and ToDoListPackage.

To import the final example to your repository, perform the following steps:

1. From the File menu, select Import.

2. In the SmartGuide window that appears, select the Repository radiobutton. Click Next.

3. On the next page, you need to specify the location of the repositoryyou are importing. Click the Browse button, and then from the listchoose the vptut1aa.dat file.

Chapter 1: Creating your first Java program10

Page 11: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

4. Select the Packages radio button, as shown in Figure 1-7.

5. Click the Details button to see the contents of this repository file. ThePackage import window appears.

6. Select the ToDoListPackageFinal in the left pane and version 1.1 in theright pane, as shown in Figure 1-8.

Setting up your project 11

Figure 1-8: Selecting packages to import

Figure 1-7: Importing a repository file

Page 12: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

7. Click OK.

8. In the SmartGuide, click the Finish button to import the componentsyou need to complete this chapter.

These components now exist only in the repository; they are not shown in theWorkbench. The repository contains all the class libraries ever known toVisualAge for Java. Now you need to add the imported package from the reposi-tory to the Workbench.

Adding a package to the Workbench

1. To add all the required components to the Workbench, select theToDoList project.

2. Right-click on the project pane and select Add—>Package from thepop-up menu.

3. In the SmartGuide window that appears, select the Add packagesfrom the repository radio button.

4. Select the ToDoListPackageFinal package in the list below this radiobutton.

Chapter 1: Creating your first Java program12

Page 13: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

5. In the right pane, select the 1.1 version, as shown in Figure 1-9.

6. Click Finish.

Now you have the ToDoListPackageFinal package containing the ToDoListFinalapplication in your VisualAge for Java Workbench. You can see all the wiring inthe final application by selecting ToDoListFinal in the Workbench and choosingSelected—>Open from the window’s menu. You can use ToDoListFinal to com-pare your wiring with ours if you encounter any problems.

You can run the finished application by right-clicking it and choosing Run—>Runmain from the pop-up menu that appears.

Now it’s your turn to create this application by yourself.

Setting up your project 13

Figure 1-9: Adding a package to the Workbench

Page 14: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Creating the package

1. Select the ToDoList project.

2. Right-click on the project pane and select Add—>Package from thepop-up menu. The SmartGuide window appears to help you add thepackage.

3. Name this package ToDoListPackage, as shown in Figure 1-10.

4. Click Finish.

5. Now you’ll see a warning window saying that, by convention, Javapackages are usually in lowercase letters. We chose to use uppercaseletters to make the names of packages stand out, which won’t causeany problems in your final application. So, press the Proceed button inthe warning window.

6. The package named ToDoListPackage appears in the Workbenchwindow.

Chapter 1: Creating your first Java program14

Figure 1-10: Creating a new package

Page 15: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Creating an appletNow you need to create the new applet.

1. Select the ToDoListPackage.

2. Right-click on the project pane and select Add—>Applet from thepop-up menu. This launches the Applet Wizard.

3. Specify ToDoList as your applet name, and click the Next button to goto the second SmartGuide window: Applet Properties.

4. In the Applet Properties window, select the first radio button, Yes, cre-ate an applet which can be run by itself or in an applet viewer. Thiswill generate the main() method for your applet, which will allow youto use it as a stand-alone application as well. (This is discussed furtherin the “Creating an application” section.)

5. Click Finish to go to the Visual Composition screen, where you canassemble your applications, as shown in Figure 1-11.

Setting up your project 15

Figure 1-11: Visual Composition Editor

Page 16: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

The next section will show you how to start building your applet by adding beansto the design surface of the Visual Composition Editor and wiring them together.

Your first appletIn this section, you’ll create the to-do list, an entry field, and an Add button to addthe text in the entry field to the list.

The Visual Composition Editor works just like any visual design tool (such asMicrosoft Paint or Adobe Photoshop). It has a palette of tools you can choose from,except that these tools are beans. You place the beans on the design surface, whichis the white space in the center of the window. This design surface has two areas.The first area is the visual surface, which is the area containing the visual elementsin your program (in other words, all the interface stuff that you see when you runthe application). The second area is the free-form surface, which is the area outsidethe visual surface. So, when we tell you to add something to the free-form surface,it means to place it outside the box in the design area.

Tip: If you accidentally click one of the tabs and the VisualComposition Editor disappears, you’ll be accosted by lots of uglycode. Just click the Visual Composition tab to get back to visualprogramming land.

Laying out the interface

Now you are ready to start designing your user interface.

1. The bean palette displays vertically on the left sideof the window. It is organized into different catego-ries of beans; the current category appears at the topof the palette. Choose the AWT (Abstract WindowToolkit) category from the palette’s menu, as shownin Figure 1-12.

2. To create a button, click the Button icon. Move thecursor to the visual surface, where it changes to across. Click the mouse to place the button on yourapplication, as shown in Figure 1-13.

Chapter 1: Creating your first Java program16

Figure 1-12:Choosing a categoryin the bean palette

Page 17: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

3. Next, place the text field on the visual surface using the TextField iconfrom the AWT palette category.

4. Finally, place the BoundList bean from the ToDoList category, asshown in Figure 1-14. (Remember to change the category on the pal-ette menu from AWT to ToDoList to access this bean.)

Your first applet 17

Figure 1-14: Adding a BoundList bean to your applet

Figure 1-13: Placing a button on your applet

Page 18: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Tip: If the BoundList bean does not appear on your palette, click the Choosebean icon on the palette. Select Class and enter com.ibm.uicontrols.BoundList, orfind it with the Browse button.

To move a bean, click on it and hold the left mouse button; then, move the mouseto change its location.

To change the size of a visual bean, select the bean by clicking on it. The gray out-line with small black rectangles tells you that this bean is selected (the currently se-lected bean’s name is written at the bottom of the screen in the information area).Place the cursor on one of the black rectangles and hold the left mouse button tochange the size of the bean, just like you would size a system window.

Customizing propertiesAs you can see, the button you added is labeled Button1 by default. You will usu-ally want to name your beans to better describe their purpose.

1. Right-click on the bean and select Properties from the pop-up menu.

2. The Properties window appears. In the property list, find the labelproperty and change the text Button1 to Add, as shown in Figure 1-15.

Tip: You can click the Show expert features check box if you want allthe customizable properties (not only the most common) to be shown.

3. Close the Properties window.

Chapter 1: Creating your first Java program18

What are bound and unbound properties?

A bound property is a property that notifies other components that its valuehas changed. This lets other components do some action based on thatchanged value. So, when you wire bound components together, they willperform an action when you run them. When you wire unbound properties,other components have to write their own code to find out when a propertychanges, so the components don’t do anything until you tell them to. There-fore, you should always look for beans with readable properties that arebound.

Page 19: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Now, repeat the previous steps to customize thebeanName property for thefollowing:

■ Change the BoundList bean from BoundList1to TaskList.

■ Change the Button bean from Button1 toAddButton.

■ Change the TextField bean from TextField1 toTaskTextField.

Making connectionsIn visual programming environments (like VisualAgefor Java), you can make visual connections from one

component to another to add function to your programs without writing any code.Making a connection defines the interaction between elements. There are five typesof connections in VisualAge for Java:

1. Property-to-property (blue): This synchronizes two property values onan event (for unbound properties) or continuously (for bound properties).

2. Event-to-method (dashed arrow in green): This is used to make amethod call whenever an event gets fired (sometimes you have to sup-ply parameters for these connections).

3. Event-to-property (green): This is used to update a property wheneveran event is fired.

4. Parameter connections (violet): This is used to supply parameters foranother connection.

5. Event-to-code (green): This is used to execute a code fragment when-ever an event is fired (this type of connection is not used in this tutorial).

Your first applet 19

Figure 1-15: The Propertieseditor

Page 20: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Connecting the Add button to the TaskList

Now you need to add the task described in the TaskTextField to the TaskList whenthe Add button is clicked.

1. First, connect the Add button to the TaskList. Right-click on the Addbutton and select Connect from the pop-up menu. A menu of preferredconnectable features for this bean appears.

2. Select actionPerformed (the event that is fired when the button isclicked), as shown in Figure 1-16.

3. When you select the connection, the menu disappears and you have adashed black connection line. Click the TaskList you placed earlier.

4. The connectable features list for the TaskList now appears. Choose theadd(String) method to specify that, when the user clicks the Add but-ton, the text in the String parameter gets added to the list. Your connec-tion should look similar to Figure 1-17.

Chapter 1: Creating your first Java program20

Figure 1-16: Connecting the Add button to the TaskList

Page 21: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Connecting the TaskTextField’s text property to the previous connection

The green connection line is dashed to indicate that more information has to beprovided for it to function properly. Next, you need to specify what the string willbe. The string comes from the string field of the TaskTextField, so follow thesewiring steps:

1. Right-click on the connection and choose Connect from the pop-upmenu.

2. Choose the item property, which represents the item added by this con-nection, as shown in Figure 1-18.

Your first applet 21

Figure 1-18: Connecting the text field

Figure 1-17: The final connection

Page 22: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

3. When you select the connection, the menu disappears and you have adashed connection line. Click the TaskTextField.

4. The TaskTextField’s connectable features list appears; it lists all of thiscomponent’s properties and methods that other components can con-nect to. Choose the text property. You get the connection shown inFigure 1-19.

Tip: At the bottom of the window, you can see how VisualAge for Java repre-sents this connection internally, but you can ignore it.

Connecting the Add button to the TaskTextField

You will also want to clear the TaskTextField after its value has been added to theTaskList, so do the following:

1. Connect the actionPerformed event of the AddButton bean to theTaskTextField’s text property.

2. Right-click on the connection and choose Properties from the pop-upmenu.

Chapter 1: Creating your first Java program22

Figure 1-19: The final text field connection

Page 23: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

3. Click the Set parameters button in the window that appears, as shownin Figure 1-20.

4. Provide the string “ ” (a blank character) as the value (this will clearthe TaskTextField after its value is added to the list), as shown in Fig-ure 1-21.

5. Click OK to close the Event-to-method connection window. For abetter visual representation, you can bend your connections by select-ing them and dragging one of the black squares shown. At this step, thewiring looks like Figure 1-22.

Your first applet 23

Figure 1-21: Setting the initial valuein the TaskTextField

Figure 1-20: Event-to-method connections

Page 24: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

6. Connect the actionPerformed event of the AddButton bean to therequestFocus() method of the TaskTextField bean (this will positionthe cursor on the text field after clicking the Add button). To create thisconnection, right-click on the AddButton and select Connect—>actionPerformed.

7. Click on the TaskTextField bean and select Connectable Featuresfrom the pop-up menu. The End connection to window displays.

8. In this window, click the Show expert features check box and selectthe requestFocus() method from the list, as in Figure 1-23. (See,you’re already an expert!)

Chapter 1: Creating your first Java program24

Figure 1-22: Connection between the Addbutton and the TaskTextField

Page 25: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

The final wiring looks like Figure 1-24.

Your first applet 25

Figure 1-24: Final wiring for your firstapplet

Figure 1-23: Positioning the cursor via therequestFocus() method

Page 26: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Running the applet

Clicking the Run icon executes your newly created applet. As you can see, clickingthe Add button really adds a new item to the list, as shown in Figure 1-25.

Removing tasksAs you’ve probably noticed, you can’t remove tasks from your applet. Let’s addthis functionality in two ways: removing all items at once and removing only theselected item.

Chapter 1: Creating your first Java program26

Figure 1-25: The ToDoList applet in action

Saving your work

Selecting Save bean from the Bean menu (or pressing theCtrl+S key combination) in the Visual Composition Editorsaves your applet. You can now close the Visual CompositionEditor or exit VisualAge for Java if you wish. Right-clicking onyour applet in the workspace and selecting Open To—>VisualComposition takes you to the Visual Composition Editor.

Page 27: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Creating a Clear button

Here’s how you create a button that clears the entire TaskList:

1. Add another button from the AWT palette category and label it Clear.

2. Change its beanName property to ClearButton.

3. Connect its actionPerformed event to the TaskList’s removeAll()method (this method can be found in the Connectable Features list ofthe TaskList bean). This removes all items from the list after the buttonis clicked. Your wiring should look like Figure 1-26.

Creating a Done button

Here’s how you create a button that removes a selected item of the TaskList:

1. Add a button from the AWT palette category to the design surface andlabel it Done.

2. Change the button’s beanName property to DoneButton.

3. Connect its actionPerformed event to the remove(String) method of theTaskList bean.

Removing tasks 27

Figure 1-26: Connecting the Clear button tothe TaskList

Page 28: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

4. Right-click on this connection and select Connect—>item; then selectthe TaskList’s selected Item property. This connection specifies thatthe selected item is the one to remove. Your composition should nowlook like Figure 1-27.

Limiting the number of tasksNow let’s limit the number of tasks in the list with the Less bean. This sectionshows you how to add a field, called CountField, where you can input the maxi-mum number of list items. You’ll use the Less bean to see if the number of items inthe list has exceeded this CountField. The Less bean returns true if its first argu-ment is less than its second argument.

Placing beans

1. Add a Less bean from the ToDoList palette category. Because thisbean is a nonvisual bean, it can be placed only on the free-form designsurface. Place it to the left of the Add button, outside the dotted line(you might need to move your applet a bit to make room).

2. Change its beanName property to LessThan.

Chapter 1: Creating your first Java program28

Figure 1-27: Connecting the Done button to theTaskList

Page 29: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

3. Add a BoundTextField bean from the ToDoList palette category.

4. Name it CountField.

5. Add a Label bean from the AWT palette category.

6. Name it CountFieldLabel.

7. Change its text property to Max entries.

Making connections

1. The Less bean has two arguments that it compares. In this case, you’llcompare the CountField to the number of items in the list. TheTaskList bean provides a count of all of its items called itemCount.Connect the TaskList’s itemCount property to the LessThan’sinputFirstArg property. The connection should look like Figure 1-28.

Limiting the number of tasks 29

Figure 1-28: Specifying the first argument for the LessThan bean

Page 30: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

2. Connect the CountField’s text property to the LessThan’sinputSecondArg property. It should look similar to Figure 1-29.

3. To limit the number of items in the TaskList, you must disable theAddButton when the count is equal to the number in the CountField.To do this, connect the LessThan’s result property to the AddButton’senabled property, as shown in Figure 1-30.

4. For the applet to work properly, the number in the CountField must begreater than zero before running the application. Using the Property

Chapter 1: Creating your first Java program30

Figure 1-30: Disabling the AddButton when the maxi-mum number of entries is reached

Figure 1-29: Specifying the second argument for the LessThanbean

Page 31: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Editor, set the CountField’s text property to some number other thanzero (in this case, it is 10).

Sorting tasksNow let’s get really fancy and sort the list alphabetically. This example will intro-duce a second list in which the items will be sorted. To do that, you’ll use the Sortbean (which takes an array and sorts it) and the Iterator bean (which iteratesthrough an array).

Placing beans

1. Add a second BoundList bean from the ToDoList palette category.

2. Name it SortedList.

3. Add a Label bean from the AWT palette category to the design surface.

4. Change the bean’s text property to Sorted.

5. Arrange these beans as shown in Figure 1-31.

Sorting tasks 31

Figure 1-31: Adding a second list

Page 32: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Making connections

1. Connect the TaskList’s items property to the removeAll() method ofthe SortedList. This will remove all items from the sorted list whenanything in the first list changes. Both the items property and theremoveAll() method can be found in the Connectable Features lists ofthe TaskList and the SortedList beans accordingly. The connection isshown in Figure 1-32.

Placing more beans

1. Add a Sort bean and an Iterator bean from the ToDoList palettecategory.

2. Name them Sort and FillList, respectively.

Making more connections

1. Connect the TaskList’s items property to the sortStringArray(java.lang.String[]) method of the Sort bean. The wiring should looklike Figure 1-33. Pass the event data for this connection by dou-ble-clicking on the connection and checking the Pass event data checkbox in the Event-to-method connection window.

Chapter 1: Creating your first Java program32

Figure 1-32: Connecting the SortedList to the original TaskList

Page 33: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

2. Connect the normalResult for this connection to the FillList’sinputStringArray property. This specifies that the return value of thesortStringArray() method (which sorts elements of a list) provides theFillList bean with items.

3. Connect the FillList’s currentStringResult property to the add(String)method of the SortedList and pass the event data for this connection.This specifies that the sorted items are added one by one to theSortedList.

Sorting tasks 33

Figure 1-33: Connecting the TaskList to the Sort bean

Page 34: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

The final wiring for the applet is shown in Figure 1-34.

Now you can run your applet again.

As you can see, in some cases, the running applet does not show all of its contents.To see it all, right-click on the ToDoList applet in the Workbench window andchoose the Properties option from the pop-up menu. The Properties for ToDoListwindow appears. Modify the width and height of the applet as you see fit. Wechose the size 470, 270.

Publishing your appletNow you have an applet that performs some functionality. As mentioned before,applets are downloadable programs that run in a Web browser. Now you’re proba-bly wondering how to incorporate your applets in your Web pages. You can do thatwith the help of VisualAge for Java.

Chapter 1: Creating your first Java program34

Figure 1-34: Final applet wiring

Page 35: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

1. Select your applet in the Workbench window (in this case, it is theToDoList applet in the ToDoList project). From the Selected menu,choose Properties. The Properties for ToDoList window appears.

2. Switch to the Code generation tab and select the Do not use any in-ner classes radio button in the Event handling section. Answer Yes tothe question about regenerating code. Click the OK button.

These two steps prevent VisualAge for Java from generating additionalclass files for event handling and put all the program code to one file.

3. From the File menu, select Export.

4. In the SmartGuide window that appears, select the Jar file radio but-ton.

5. Click the Next button. In the next window, select the files that must beexported in the JAR for your applet to work properly.

6. By default, one class is selected. This class is your ToDoList applet inthe ToDoListPackage. To select all necessary components, click theSelect referenced types and resources button.

7. Check the .html check box under the question Do you want to create.html files to launch applets? This will create an example HTML fileused to launch your applet.

8. If you click on the Details button, you will see that one file is se-lected—the ToDoList applet.

Publishing your applet 35

Page 36: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

9. Make sure that you select the check boxes shown in Figure 1-35.

10. Click Finish.

The new applet.jar file and ToDoList.html file will be placed in the directory thatyou have specified in the SmartGuide window (in this case, the C:\VP directory).

The source of the ToDoList.html file is listed in Figure 1-36.

Chapter 1: Creating your first Java program36

Figure 1-35: Exporting to a JAR file

Page 37: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

As you can see, the applet is your ToDoList applet in the ToDoListPackage, andthe applet.jar file is the archive file.

Now you can view this ToDoList.html page in your Web browser, as shown in Fig-ure 1-37. (Double-click it to open.)

It works, try it out!

Publishing your applet 37

Figure 1-37: The ToDoList applet running in a browser

<HTML><HEAD><TITLE>ToDoList</TITLE></HEAD><BODY><H1>ToDoList</H1><APPLET CODE=ToDoListPackage.ToDoList.class ARCHIVE=applet.jarWIDTH=470 HEIGHT=270></APPLET></BODY></HTML>

Figure 1-36: The source of the ToDoList.html file

Page 38: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Creating an applicationNow that you have finished your applet, you may decide that you would like it towork with files so that you don’t lose your to-do list every time you restart yourapplet.

However, one of the restrictions of applets is that, because they download informa-tion from a server to your machine, they always have to worry about security. So,applets have to get special permission to work with files (otherwise, a hostile appletmight steal private information from your hard drive without your permission).

Instead, we’ll teach you how to develop Java applications—programs that don’t getautomatically loaded from Web pages, as applets do, but have unrestricted accessto the file system and other system resources.

Usually, when creating applications from scratch, you would use the Add Class orAdd Application wizard that is launched if you select Add—>Class from the Se-lected menu in VisualAge for Java, as shown in Figure 1-38 (but don’t do it now,we have an easier way).

Chapter 1: Creating your first Java program38

What’s an application?

An application is a stand-alone Java program,normally launched from the command line. AJava application contains a method called main,which is where the program starts execution.

Page 39: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

You would usually pick Frame (JFrame is for creating applications with a differentset of components called Swing) as the superclass of your class (the class that thisnew class will inherit its features from). Then you would enter a descriptive classname and click Finish to create the class and start working on it in the Visual Com-position Editor.

However, following this scenario, you would have to repeat all the wiring you didbefore to produce an application with the same functionality that your applet had. Itturns out that this is unnecessary. When you were creating your applet, you chosethe Yes, create an applet which can be run by itself or in an applet viewer op-tion in the SmartGuide window, so VisualAge for Java already included a main()method that lets your applet function as an application (in other words, not bear thesecurity restrictions) when run outside the Web browser.

Therefore, we can assume that you now have a ToDoList application with the samefunctionality as the ToDoList applet.

Creating an application 39

Figure 1-38: Creating an application from scratch

Page 40: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Working with filesSo, now you want to save and load your ToDoList. Once again, you only need toadd a couple of beans and wire them to your existing components. The WriteFileand ReadFile beans (for writing a String array into a file and reading it from a file)are just what you’re looking for.

Loading the ToDoList from a file

For this functionality, you need the ReadFile bean from the ToDoList palettecategory.

1. Place a ReadFile bean on the design surface, and customize itsbeanName property to ReadFile.

2. Place a BoundTextField bean on the design surface, and set itsbeanName property to FileName.

3. Place a button on the design surface, and set its beanName toLoadButton. Set the bean’s label property to Load.

4. Place a Step bean from the ToDoList category. Set its beanName prop-erty to ClearList.

Chapter 1: Creating your first Java program40

Reordering the connections

Sometimes the order of your connections is important. For example,you have made two connections on the same event from the samebean: one connection that takes the first item from the array and theother that deletes all items from that array. The function of the firstconnection has to be done before the second. Bean connections arerun in the order in which you make them. To ensure the correct flow ofcontrol in the generated source code, you might need to reorder theconnections using the Reorder Connections From item of the pop-upmenu or use a special bean that ensures the correct order (for exam-ple, the Step bean).

Page 41: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Now you will implement reading from the saved files.

5. Connect the FileName bean’s text property to the ReadFile bean’sinputFileName property. This will supply the input file name to theReadFile bean.

6. Connect the ReadFile’s currentStringResult property to the add(String)method of the TaskList. Pass event data for this connection.

7. Connect the actionPerformed event of the LoadButton to thetriggerAction() method of the ClearList bean. This means that clickingthe Load button will activate the work of the ClearList bean.

8. Connect the triggerThisAction event of the ClearList bean to theremoveAll() method of the TaskList bean.

9. Connect the triggerNextAction event of the ClearList bean to thetriggerAction() method of the ReadFile bean.

The last two connections define the order of two methods that must be executed ina specific sequence—removing all items from the list and loading a new list fromthe file. Your final application should look something like Figure 1-39.

Creating an application 41

Figure 1-39: The wiring for loading the list from a file

Page 42: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Saving the ToDoList in a fileFor this functionality, you need the WriteFile bean from the ToDoList palettecategory.

1. Place a WriteFile bean on the design surface, and customize itsbeanName property to WriteFile.

2. Place another button on the design surface, and set its beanName prop-erty to SaveButton.

3. Set its label property to Save.

Now you will set the connections for writing the list to a file.

4. Connect the TaskList’s items property to the WriteFile’s inputArrayproperty. This will send the contents of the list to the WriteFile bean asan array.

5. Connect the FileName’s text property to the WriteFile’sinputFileName property. This will set the file name in which you wantto save your ToDoList for the WriteFile bean.

6. Connect the actionPerformed event of the SaveButton bean to thetriggerAction() method of the WriteFile. This will activate the functionof WriteFile. Your wiring should now look similar to Figure 1-40.

Chapter 1: Creating your first Java program42

Page 43: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Now you can run your application. Choose Bean—>Run—>Run main from thewindow menu to execute the main() method of the ToDoList class. The final run-ning application is shown in Figure 1-41.

Now you’d probably like to execute the ToDoList application outside VisualAgefor Java. This is discussed in the next section.

Creating an application 43

Figure 1-41: The running ToDoList application

Figure 1-40: The wiring for saving the list to a file

Page 44: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Running an application outside VisualAge for JavaAs you know, one of the main advantages of Java is its platform independence.You can create an application using a UNIX system and let Windows users run iton their computers (and vice versa). What allows Java to be so independent of theoperating system? The answer is the Java Virtual Machine (JVM). The JVM acts asa translator between your compiled Java code (class file) and the underlying hard-ware platform and operating system where this class executes. Even though theJava code and the class files are the same, the JVMs differ for each particular oper-ating system.

What is the Java Virtual Machine?So, what is the JVM? It is a virtual computer that resides only in memory. It actu-ally has a very small footprint when running in RAM. The JVM enables you to ex-ecute Java programs and Web applets on your computer, outside of the VisualAgefor Java integrated development environment. Therefore, to run your applicationsoutside VisualAge for Java, you need the JVM installed on your computer. Youmight already have it.

The easiest way to check whether you already have the JVM is to get to the com-mand prompt and try to execute the java command without any parameters. If youget the description of the command syntax for this command, you have the JVM.You also need to know the version of the JVM you have. Your version of the JVMshould be compatible with the version in the VisualAge for Java release you’re us-ing. If you are using VisualAge for Java 3.0, you need Java Development Kit(JDK) 1.1 (we recommend you use JDK 1.1.8). If you are using VisualAge for Java3.5 or 4.0, you need JDK 1.2 or later. We’ve provided both of these JDKs on theCDs included with this book.

So, how do you check the version? If the java command executes on your systemsuccessfully, you can figure out the version of the JVM by executing the java-version command in the command prompt. If the JVM version you have matchesthe level for the VisualAge for Java version you are using, skip the next sectionand continue with the “Exporting to a directory” section.

Where to get the JVM for your platformThe appropriate JVMs are included on the CDs with this book, but you can down-load future updates from IBM’s developerWorks site at www.ibm.com/java/jdk/download/. IBM’s JVM comes as part of a JDK package and is available for AIX,

Chapter 1: Creating your first Java program44

Page 45: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Linux, AS/400, OS/2, Windows, and some other operating systems. For Windowsoperating systems, developerWorks also provides a separate Java Runtime Envi-ronment (JRE) package.

Another option for Solaris and Windows users is the JRE package available on SunMicrosystems’ site at http://java.sun.com/jdk/.

For instructions on installing the appropriate JVM for your system, see the Appen-dix. After you’ve installed the JVM, you can execute Java class files. The next stepis to prepare your application and export it from VisualAge for Java to a class file.

Exporting to a directory

To save your application as a class file, export the package containing your appli-cation to a directory on your computer. We’ll demonstrate this process usingthe ToDoList example. To simplify the explanation, let’s create a special directoryto export your files to such as the C:\export directory.

1. Make sure that you have set the Do not use any inner classes optionin the ToDoList application’s property window to avoid additionalclass files generation for event handling (Selected—>Prop-erties—>Code generation tab). Create the export directory on yourdisk.

2. In a Workbench window, right-click on the ToDoListPackage andchoose the Export option from the pull-down menu.

3. In the SmartGuide window, select the export destination Directory andclick Next.

4. Use the Browse button in the next SmartGuide window to specify theC:\export directory.

5. In the What do you want to export? section, check the .class checkbox. This exports only compiled Java code (ready-to-execute code) tothe directory.

Running an application outside VisualAge for Java 45

Page 46: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

6. Unselect all other check boxes in the window, as shown in Figure 1-42.

For future applications, if you want to save the text source of your Javacode, check the .java check box. If your application uses any resource files(such as images or music), check the resource check box. In this example,there is no need to select these two check boxes.

7. Click the Finish button.

Once you have completed these steps, the export directory contains theToDoListPackage subdirectory with the ToDoList.class file inside.

Chapter 1: Creating your first Java program46

Figure 1-42: Exporting an application

Page 47: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

Referenced classesNow you have exported the ToDoList class to the directory. However, as you prob-ably remember, you used some beans (such as the Less and Step beans) to con-struct this class, and they weren’t exported with the ToDoList class. These beans’classes reside in the vptut1aa.jar file, so we are going to use this .jar file to executeour application. Even though this step is not necessary, let’s put this file in thesame export directory to simplify the execution command.

Copy the vptut1aa.jar file into the export directory. Now the application is ready tobe run outside VisualAge for Java.

Simple syntax of the java command

java -classpath <list> package.class

The list in this command represents the list of directories, separated by semicolons,in which to look for referenced classes. For classes packaged as .jar files, you needto specify the .jar files directly.

Running the application from the command promptTo run your application, you’ll need to go to your system’s command prompt tochange to the export directory and execute a java command that specifies the ap-propriate options and class file.

We’ll use the Windows operating system; for all other operating systems, the pro-cess is very similar. Windows users can run the application by opening the MSDOS command prompt (Start—>Command Prompt) and entering the followingcommands:

c:cd c:\exportjava -classpath vptut1aa.jar;.;%CLASSPATH% ToDoListPackage.ToDoList

The first two lines are DOS commands that move you to the correct subdirectory.The last line is an IBM JDK command.

Even though this isn’t necessarily the easiest way to execute commands, for thoseof you familiar with the DOS commands, it might be the fastest way. For

Running an application outside VisualAge for Java 47

Page 48: Chapter 1editorial.mcpressonline.com/web/mcpdf.nsf/wdocs/... · in the “Your first applet” section. Figure 1-2 simply shows you the basic steps used in visual programming: First

applications you use often, you might want to create a special executable file (like a.bat file in Windows) that contains all the necessary commands.

To get more information on DOS commands, just enter help in the command line.Enter java to get an overview of the syntax of the command.

Now you can run the application outside VisualAge for Java.

Note: If you receive error messages such as “Class not found,” verify that yourCLASSPATH setting includes all the required .jar files needed to run your applica-tion. This should include the standard Java classes, the current folder (“.”), andany bean .jar files used by the application.

In reviewThis chapter describes how you can use visual programming to develop the appli-cations you need. It shows you how to create applets and applications in VisualAgefor Java and how to export an application and run it from the command line. Chap-ter 2 shows you how to create subcomponents (a.k.a. beans).

ReferencesIBM developerWorks Web site: www.ibm.com/java/jdk/download/

Sun Microsystems’ Java Web site: http://java.sun.com/jdk/

Chapter 1: Creating your first Java program48


Recommended