IBM WebSphere Developer Technical Journal: Comparing WebSphere Studio Application Developer with VisualAge for Java -- Part 3

Using the New Visual Editor

Are you a VisualAge for Java developer looking to move to WebSphere Studio Application Developer? This article describes the Visual Editor available with Version 5.0, and where applicable, draws comparisons with its predecessor, the Visual Composition Editor that was available with VisualAge for Java.

Joe Winchester (winchest@uk.ibm.com), WebSphere tools developer, IBM Hursley Lab, United Kingdom, IBM

Joe Winchester is a member of the WebSphere Tools Development team working on the Visual Editor for Java for the Software Solutions group in Hursley, United Kingdom.



16 October 2002

© Copyright International Business Machines Corporation 2002. All rights reserved.

Introduction

WebSphere® Studio Application Developer Version 5.0 (hereafter called Application Developer) introduces the Visual Editor that lets developers build graphical user interfaces based on the JavaBeansTM component model. The Visual Editor provides a palette that lets you select Java beans from the Abstract Widget Toolkit (AWT) or Swing; and of course you can also add and use your own controls. This article describes the Visual Editor functionalities, and where applicable, draws comparisons with its predecessor, the Visual Composition Editor that was available with VisualAge® for Java.

One of the main differences between the two editors is how the Java beans and the generated Java source code work together. The earlier Visual Composition Editor let you drop Java beans and modify them using the property sheet or customizers, and then regenerated the source each time the file was saved. You could only modify the source code within the predefined user code sections or by adding new methods. Source code modifications were not reflected back in the Java beans; the Visual Composition Editor was a top-down development tool that generated source from the Java beans, but not vice versa. By comparison, the new WebSphere Studio Visual Editor performs round-tripping of changes between the Java beans and the source code. You can modify the Java beans and see the modifications reflected in the source, and you can also change the source code and see the changes applied to the Java beans. The Visual Editor is a code-centric editor that not only supports round-tripping of changes, but also displays the Java beans and the source code side-by-side using a split pane. When you select a Java bean, the source code shows the method that initializes it, and when you select an individual property, you can see the statement that sets its value.

Another difference between the two editors involves how event handling logic is created. In the earlier Visual Composition Editor, you could make connections between Java beans; the code to add listeners and perform the appropriate callback logic was created during code generation. Besides event-to-method connections, the Visual Composition Editor also supported higher-level program constructs such as property-to-property connections. While some users of the Visual Composition Editor enjoyed programming with connections, others experienced problems resulting from the complexity of having to maintain and debug classes within programs that had a large number of connections. By comparison, to add event handling program logic using the new Visual Editor, you write the event handling logic directly in the source itself.


Launching the Visual Editor

To illustrate the features of the Visual Editor, we will create a Java class called MyPanel that subclasses javax.swing.JPanel.

Create a Java class by clicking the Create Class wizard button Screen capture of the Create Class wizard icon located in the Java and Java Browsing perspective toolbar, or by selecting File => New from the menu, and choosing Class. The standard Java Editor now opens displaying the contents of the source file.

To launch the Visual Editor, you must first close the Java Editor, and then right-click the new file. Select Open With => Visual Editor from the drop-down menu.

Figure 1.
Selecting Open With => Visual Editor on the MyPanel class

The default editor for a Java file (i.e., the editor that launches when you create or double-click a file in the package explorer view) is indicated with a black dot in the list of available editors. If you want the Visual Editor to be the default editor for all Java files, then you can make this change globally: select Window => Preferences to launch the Preferences dialog, and then select Workbench => File Associations.


Getting to know the Visual Editor look and feel

The Visual Editor consists of multiple panes (see Figure 2). A graphical canvas is located in the top section and the source file is displayed beneath it. A palette of common Java beans is displayed on the left, and each area is separated by split bars that can be selected and moved to new positions so that you can make the most out of the available space.

Figure 2.
Screen capture of the WebSphere Studio Visual Editor

When the Visual Editor is launched, two additional panes open automatically: the Java Beans pane, which displays the structure of the Java beans in a tree view, and the Properties pane, which lets you view and modify attribute settings. The Java Beans pane is similar to the Beans List that was available in the earlier VisualAge for Java Visual Composition Editor.

The source pane at the bottom of the Visual Editor is an embedded version of the standard Java Editor included with Application Developer. Here you can set breakpoints in the source, use content assist, and benefit from the other functionalities available with the Java Editor.

When you make a change to the source in the canvas, in the Properties pane, or in the Java Beans pane of the Visual Editor, the change is automatically updated in the source code; you do not need to explicitly generate the code. You can click the Undo button Screen capture of the Undo icon in the Visual Editor toolbar in the toolbar to undo any modifications. Besides modifying the Java beans, you can also make changes to the source code directly and see the changes reflected in the Java beans. This lets you make changes to the Java beans and then have the changes reflected in the source code, and vice versa.

By comparison, the Visual Composition Editor in VisualAge for Java was primarily a top-down development tool, where changes made to the Java beans were generated into the source, but not vice versa. Because the Java source is always recreated from the Java beans, user modifications were restricted to new methods or to predefined sections in the source delimited by //user code comments.


Working with Java bean properties

When the Visual Editor is opened on a .java file it parses the source to look for the presence of Java beans. Because the MyPanel class created earlier subclasses javax.swing.JPanel, a Java bean is created that represents the instance of the class itself. The new Java bean is called this, and is displayed in the Java Beans pane and also in the canvas. The Visual Editor only creates a this bean if settable properties on the class are composed. Any Java bean that is a descendent of java.awt.Component is shown in the canvas with its graphical run-time representation, so that MyPanel (which includes java.awt.Component in its list of superclasses) is shown as a gray panel. No size has been set yet for MyPanel so it appears in the canvas at its default size. The default size is the result of calling getPreferredSize(), which for an empty JPanel with no components is 10,10.

The canvas lets you select Java beans; use the mouse to move and resize them. To make the JPanel larger, move the cursor over its bottom right edge so that it becomes a southeast arrow Screen capture of the arrow pointing south-east , and then left-click and move the cursor to the desired size, and then release it:

Figure 3.
Screen capture showing the JPanel Java bean dropped in the Visual Editor canvas

When JPanel is resized, the source code is updated to include the line of code that sets the new size. This is the setSize(157,112) statement within the initialize() method that is called from the MyPanel constructor. After resizing, the source is updated incrementally; you do not need to explicitly regenerate in order to refresh the code. The Properties pane also displays a right arrow, > , next to the size property to indicate that this is a value that has been explicitly set in code. Properties without the right arrow, > , are displayed with the default value from the Java bean by calling the get method associated with the property. Besides changing the size property visually by using the resize handles on the panel, you can also select the Value column in the Properties pane and edit it there. The size property is changed by entering a new value directly into the Properties pane and pressing Enter. If the value entered is invalid, then the error message is shown in the status bar at the bottom of the editor:

Figure 4.
Screen capture showing the error message displayed in the status bar when the valued entered is invalid

Some properties have a restricted set of enumerated values; in these cases, you do not have to change the value in the text field of the Properties pane.

Figure 5.
Screen capture of the values drop-down field

Other properties, such as font, color, and icon, have additional dialog editors that you can launch from the Properties view. These editors will open a separate window that lets you specify a new value.

Some properties, for example the FlowLayout value for the layout property shown above, are themselves Java beans. You can expand these beans to view and modify their properties. If the nested properties are Java beans that contain further properties, then you can expand the list further to drill down into the attributes that comprise a particular property value (see Figure 6).

Figure 6.
Screen capture of the attributes list

The list of Properties shown for a Java bean includes properties that have get and set methods and therefore are read and write properties. Using the menu, you can configure the Properties pane to also show read-only properties.

Figure 7.
Screen capture of the Properties list

Selecting Show null values on the menu lets you distinguish between a property with a null value and one with an empty value. For example, the name property for the panel could be either a blank String or undefined. Setting Show null values in the Properties pane lets you distinguish between the two; the value <null> appears next to the properties whose values are null.

Figure 8.
Screen capture showing the value null appears next to the properties whose values are null

If you want to set a property to be null, click the Set to null button Screen capture of the Set to null button in the toolbar in the toolbar. If you want to reset a property value back to its original default value, click the Reset property value button Screen capture of the Reset property value button in the toolbar in the toolbar.

Because the Visual Editor supports the round-tripping of source code, you can also modify property values by changing the source code directly. This is covered in the section, Round-trip Java source.


Adding new Java beans

Besides working with the this Java bean that represents the instance of the class being created, you can also use the palette to add new Java beans. The palette is located on the left of the Visual Editor, and is also available from the toolbar. The Choose Bean button Screen capture of the Choose Bean button opens a dialog that lets you select any Java bean, while the down arrow beside it opens a menu with categories of common Java beans (see Figure 9):

Figure 9.
Screen capture showing a drop-down menu of Java bean categories

To drop a new Java bean on the canvas, select it from the palette and move it over the desired destination. You can drop the Java bean either on top of a Java bean that is able to accept children or as a new top-level Java bean. You can also drop Java beans on the Java Beans pane. When you select a palette item, for example JButton, the status bar label gets updated, indicating which Java bean has been selected:

Figure 10.
Screen capture showing the status bar label updated to indicate that the JButton Java bean has been selected

The cursor also changes, Screen capture of the cursor now in create mode, to indicate that you are now in create mode.

Java beans, such as JPanels, can accept children that represent their components. If you move the mouse over MyPanel's this Java bean and then release it, then the JButton Java bean will be added. The button is now displayed on the canvas:

Figure 11.
Screen capture showing the JButton Java bean displayed on the canvas

To set properties on the button, such as text, select it and see its attributes listed in the Properties pane. When you add a Java bean to a container such as a JPanel, the position and size of the Java bean is determined by the container's layout manager. A layout manager class is used as a delegate by the container to determine the appearance of its components, and is typically used when the run-time size of the Java bean or when any of its user-visible strings may vary. A JPanel's default layout manager is the java.awt.FlowLayout class that gives each component its preferred size and lays them out from left to right. Because the container's layout manager is responsible for the position of its components, then you do not have precise control over each Java bean's location. To see this, select a second Java bean, for example JScrollBar, from the palette. As you move the mouse over the JPanel, you will see a vertical line drawn on either side of the existing JButton. This is the target feedback from the Visual Editor. It lets you know where the new Java bean will be added relative to the existing Java beans:

Figure 12.

Drop the JScrollBar Java bean by pressing and releasing the left mouse button. The new Java bean is now positioned next to FlowLayout before JButton. The two components are shown at their preferred sizes and positioned evenly the across the available width:

Figure 13.

Having a layout manager such as java.awt.FlowLayout lets the GUI can react at run time to changes that affect its appearance. These could include the preferred size of a component changing as a result of a different font or language-dependent label, or as a result of the user making the window size smaller or larger. If these changes occur at run time in an environment that may be different from the one that you built the application in, then the layout manager reflows the GUI components based on the current values for the preferred size and window area.

Some of the applications that you build may be deployed in only one language locale. The label strings are hard-coded, and you may not be concerned with reflowing the components when the window is resized. In these cases, rather than use a layout manager, you can get greater control over your components' positions and sizes by setting the layout manager to null. To do this, select the panel in the Properties pane, and then select null from the list of available values in the layout property:

Figure 14.

Because the panel's layout manager is no longer responsible for the size and position of its components, then you must now set the size and position explicitly in the source code. When you set the panel to have a null layout, the Visual Editor queries the existing size and position of each component and makes this their bounds property. Use the bounds property of a component to conveniently combine the size and location properties in a single rectangle. Visually, you will see no difference in the Java beans on the canvas because their sizes and positions relative to the panel remain unchanged; however, the code is updated to include the method call to set the component's bounds property:

private javax.swing.JScrollBar getIvjJScrollBar() { 
   if(ivjJScrollBar == null) { 
      ivjJScrollBar = new javax.swing.JScrollBar(); 
      ivjJScrollBar.setBounds(50, 5, 17, 61); 
   } 
   return ivjJScrollBar; 
}

To size and position components whose container has no layout manager, use the Alignment dialog. Open this dialog by clicking the Alignment dialog button Screen capture of the open alignment dialog button on the toolbar. The Alignment dialog contains a set of buttons that let you change the size and/or location of the selected Java beans. When you use the alignment actions, you typically select a number of Java beans, one of which is known as the anchor. The anchor is the last Java bean selected; it forms the rule by which the other controls will be moved or resized. The type of alignment depends on the action used, but selecting Align Bottom would make every Java bean's bottom edge be the same as the anchor by changing their y coordinate.

Figure 15.
Selecting the Align bottom button

Besides aligning the edges of the Java beans, you can also align their size by using the Match Width Screen capture of the Match Width button and Match Height Screen capture of the Match Height button buttons. The Distribute actions let you space the selected Java beans evenly, either within their parent container or within an explicit area defined by a bounding box Screen capture of the bounding box icon. Use the Align and Distribute buttons for components whose container has no layout manager, and also for Java beans that have no container and are directly on the canvas.

When FlowLayout was the container's layout manager, its components, the JButton and the JScrollBar, did not display the bounds, location, and size properties in the Properties pane. Setting the properties would have had no effect, because the FlowLayout instance, not the individual components, determined their size and position. Without a layout manager, the bounds, location, and size properties are made available in the Properties pane for each component and can be modified using property editors. Because each component can have a precise coordinate specified for its size, you can use its handles in the canvas to move and position it. When you add a new Java bean to a container whose layout manager is set to null, you can also determine exactly where you want the component to be placed. If you do not specify a size when you drop the bean on the canvas, then the size will be explicitly set to be the component's preferred size.

The java.awt.FlowLayout class sizes each component according to its preferred size and lays them out from left to right. It is an instance of an unconstrained layout manager, and implements the interface, java.awt.LayoutManager. The Java language includes the interface java.awt.LayoutManager2; this lets each component specify additional data that the layout manager should use when determining its size and position. An example of a layout manager that implements java.awt.LayoutManager2 is the class java.awt.BorderLayout. The BorderLayout class divides the container into four edge regions (North, East, South, and West) and one middle region (Center). Each component can specify which region it wants to be placed in. When an edge region is specified, it occupies the entire edge and its remaining axis is based on its preferred size. When the middle region is specified, the component occupies all of the remaining available space in the container.

To use the BorderLayout class for a container, select it from the list of available layout properties. The bounds, location, and size properties are removed from the Properties pane for each component, and default constraints are generated for each existing component within the container. For our example, this means that the JScrollBar is placed in the North region and the JButton is placed in the East region. If more than five components exist in a container when it is switched to BorderLayout, then the excess components are deleted.

Figure 16.
Screen capture showing the excess components deleted

The Properties pane shows the constraint property for components whose parent container layout manager implements java.awt.LayoutManager2. The editor for the constraint property varies depending on the layout manager; for BorderLayout, the drop-down menu lists the available constraint regions. When you drop a new Java bean on top of the panel, you will see the five constraint regions. Regions that are already occupied, such as North and East in the example below, are shown in dark gray. You cannot drop the new Java bean in these spaces. The current region, highlighted with the cursor, is labeled with its name, in this case, West:

Figure 17.
Screen capture showing the highlighted region labeled with its name, in this case West

Besides supporting the FlowLayout and BorderLayout layout managers, the Visual Editor also supports CardLayout, GridLayout, BoxLayout, and GridBagLayout. The java.awt.GridBagLayout class is the most powerful of the layout managers; it divides the container into a series of rows and columns, and lets you specify the cell that the component should be placed in, as well as how it is anchored there and how many cells it should span.

When using GridBagLayout, new Java beans are created with a constraint that is an instance of GridBagConstraints created with its null constructor. Although the panel displays results based on the existing columns, the new component is always added at the end (it does not matter where you drop the component). By comparison, the earlier VisualAge for Java Visual Composition Editor generated a constraint based on where you dropped the Java bean on the canvas (i.e., the position of the mouse).

Because a default constraint is always used for GridBagLayout, you must use the Properties pane, or edit the source directly, to modify the value of the GridBagConstraints object for the component.

Figure 18.
Screen capture showing how to edit the source directly to modify the value of the GridBagConstraints object for the component

A technique that works well for GridBagLayout is to position it precisely and size each component without setting a layout manager on the container (i.e., set the layout property to null). When the GUI is complete, set GridBagLayout to be the layout manager. The Visual Editor now generates the constraint for each component based on its current bounds property; this results in each component having the same location and size, except that instead of having an explicit bounds property, a GridBagConstraints object is used. The advantage of using GridBagLayout as the layout manager instead of setting the layout property to null is that when the window is resized by the user at run time, the components will be laid out to make the most of the available space. Likewise, if the visible strings within components such as buttons or labels change due to different run-time fonts or locales, then the GUI will adjust appropriately when GridBagLayout is used. This would not occur with a null layout and explicit bounds where each component has a a fixed run-time position and size.


Adding custom Java beans

Besides selecting Java beans from the list of commonly used classes defined in the palette, you can select the Choose Bean option to add any Java bean to the class you are creating:

Figure 19.
Screen capture the Choose Bean option selected

Select Choose Bean; a dialog opens displaying a list of available classes (see Figure 20). Only public classes can be selected (unless the class is in the same package as the class you are going to use it in). It should have a public null constructor, either as an explicit method or as an implicit default constructor.

Figure 20.
Screen capture of the Choose a Bean dialog

You can enter a search string in the Class field at the top of the Choose a Bean dialog if desired. You can also use the Swing and AWT radio buttons to restrict the list further.

The list of classes in the Choose a Bean dialog is determined by using the Java Build Path for the project of the class being created. If you want to include your own Java beans that are not in the current project, open the Properties dialog for the project and ensure that the location of your Java beans are included in the build path. After modifying the Java Build Path, you will need to close and reopen the Visual Editor for the change to take place.

When the Visual Editor is opened, a VM is created that is used to host the Java bean instances. The VM class path is determined by the entries in the project's Java Build Path, so if you change the JRE of the build path, then you are also changing the JRE that the Visual Editor will use. To see this, define new JREs in Application Developer by selecting Window => Preferences, and then selecting Java => Installed JREs. Then, click Add. This lets you specify the location of a JRE. You can make any of the JREs the default JRE in the Preferences dialog; the Visual Editor will now use this to start its VM. By doing this, you can work with another JRE, such as JDK 1.4; you can then select its new Java beans, such as javax.swing.JSpinner, from the Choose a Bean dialog.

The ability to have pluggable JREs is a powerful feature of the Visual Editor. By comparison, the earlier Visual Composition Editor used the fixed JDK level that was built into VisualAge for Java.

Besides changing the default JRE in Application Developer, you can also override the JRE on a per-project basis. To do this, you need to remove the existing default JRE from the project's build path, and then add the new JRE. To add a new JRE to the build path, press the Advanced button on the Libraries page, and then select Add Container =>JRE System Library. This brings up a list of all known JREs for you to choose from. However, because of the way the Visual Editor locates some of its internal classes, the variable entry JRE_LIB must be present in the Java project's build path. Therefore, instead of removing JRE_LIB from the build path, you should leave it there and ensure that the new container is placed before it in the build path.

When the Visual Editor starts its VM to run its Java beans, you cannot reload the changes that were made to the classes being used. For example, if you are using a custom panel while also modifying it, the Visual Editor, since it is using the custom panel, will not reflect the changes until you close and reopen the editor. By comparison, the VisualAge for Java Visual Composition Editor was able to dynamically display the result of changed classes without having to reopen the editor.


Round tripping from Java source to Java beans

The examples used so far have demonstrated how to make changes to the Java beans in one of the Visual Editor's panes, after which the source code is appropriately modified. Besides making changes through the panes, the Visual Editor also lets you modify the source code directly. For example, if you want to set a JButton background color to be cyan, you can either open the editor for the background property in the Properties pane, or you can add the line directly into the source code:

private javax.swing.JButton getIvjJButton() { 
   if(ivjJButton == null) { 
      ivjJButton = new javax.swing.JButton(); 
      ivjJButton.setBackground(java.awt.Color.cyan); 
   } 
   return ivjJButton; 
}

When you have added the method call in the code to set the button's background color, the Java beans will be refreshed and the canvas will display the button with its new color. Changes made to the Java source are automatically updated in the Java beans; you do not need to explicitly refresh the Java bean.

The Visual Editor is a code-centric editor. To help you navigate through the code when you select a Java bean in either the canvas or the Java Beans pane, the method that is responsible for setting the Java bean's initial properties is highlighted in the source code. You can also select a property in the Properties pane to drill down to the exact line of code that is responsible for setting the value.

The Visual Editor is able to handle changes made directly to the source code, and then update the source when the Java beans are changed in the different panes, and vice versa. This is known as round-tripping. By comparison, the VisualAge for Java Visual Composition Editor only let you make changes to the Java beans in the panes; it then regenerated the source code and serialized the Java beans into the repository as metadata. The Visual Editor, however, has no metadata. Each time the Visual Editor is opened, it parses and analyzes the source code to determine the Java bean model used by its panes. This means that you can edit the Java source code in another editor and then reopen it in the Visual Editor to see your changes. When the Visual Editor is opened, it "listens" to the changes made to the contents of its Java source file and then refreshes its Java beans incrementally, even if the source code was modified in another Java editor.

After you modify the source code, a background synchronizer observes the changes and then updates the Java beans used by the Visual Editor. The status bar at the bottom of the editor shows the status of synchronization between the Java beans and the source code. The status In Sync means that the two are synchronized, the status Out of sync means that a change has been made and there is a pending update queued, and Synchronizing means that an update is occurring. The two arrows are updated to show the direction of the update that is being performed: the down arrow represents changes from the Java beans to the source code and the up arrow represents changes from the source code to the Java beans. Although the bottom-up synchronization between the source code and the Java beans is running in the background and should not slow down performance when making changes to the code, you might want to suspend the process when making substantial changes to the code. You can do this by clicking the Pause button Screen capture of the pause button icon in the status bar; the button then becomes a green Resume arrow. Press the Resume button to restart the synchronizer. To avoid a reconciliation issue arising while the synchronizer is paused, all changes made to the Java beans in the panes are ignored and you should only change the source code. When the synchronizer is resumed, the entire contents of the source file are analyzed to refresh the Java beans, so using Pause and Resume can be an effective way to reload from source code to the Java beans.

Figure 21.
Screen capture of the Pause and Resume buttons

To successfully update Java beans from the source code, you must utilize recognized patterns. These patterns are based on the code patterns that the earlier Visual Composition Editor generated to let users easily migrate to WebSphere Studio. For a field to be recognized as a Java bean, it be instantiated in a get method. The following is a typical Visual Editor method that creates a JPanel and will be recognized by the Visual Editor because the field is instantiated by the statement, ivjJPanel = new javax.swing.JPanel(), within a get method.

private javax.swing.JPanel ivjJPanel; 
private javax.swing.JPanel getIvjJPanel() { 
   if(ivjJPanel == null) { 
      ivjJPanel = new javax.swing.JPanel(); 
      ivjJPanel.setBackground(java.awt.Color.cyan); 
   } 
   return ivjJButton; 
}

The get method returns the field, and can instantiate more than one Java bean.

With the method that instantiates a Java bean, the first occurrence of a set method that isn't inside a catch block is used as the initial property value. In the above method where ivjJPanel was recognized as a Java bean, the statement, ivjJPanel.setBackground(java.awt.Color.cyan), was parsed as the initialization code for the background color property. The set methods for properties on the class being created must be in a method called initialize() or init() for applets.

To apply the value of the property to the live Java bean instance, the set method argument syntax should be a fully qualified self-contained initialization string, such as java.awt.Color.cyan. If the initialization string references a class that is not fully qualified but is included in an import statement, then it may not be able to evaluate the expression, although for public fields and constructors, it is able to resolve the class through the imports. Complex argument expressions, such as those that use innerclasses cannot be evaluated. This means that you won't be able to see the effect of the set method on the live Java bean, although you will receive a warning indicating that this has occurred. The initialization string cannot be applied to the live Java bean because it is too complex for the evaluation engine used by the Visual Editor. However, when you compile and execute the .class file, it will be applied. The warning simply reminds you that at design time, the GUI Java bean may be incomplete.

Figure 22.
Screen capture showing a warning indicating that at design time the GUI Java bean may be incomplete

Writing event handling code

With the VisualAge for Java Visual Composition Editor, you wrote program logic to make connections between Java beans. These connections then generated the appropriate code to attach the listener to the source Java bean, and then executed the desired action on the target. By comparison, the new Visual Editor does not carry forward the concept of connections between Java beans; such program logic is specified by writing code directly in the editor. To help developers write the event handling code, the Visual Editor provides several content assist templates.

Each template has the same name as the method it is designed to work with. For example, the template for adding an action listener to a button is called addActionListener. To use the template, select the Java bean for the button, either in the canvas or in the Java Beans pane, and the Visual Editor will select the appropriate method that initializes it. After you write the beginning of the line of code, for example ivjJButton.addA, you can invoke content assist by pressing Ctrl-Space on your keyboard. The template will appear at the bottom of the content assist list:

Figure 23.
Screen capture showing the template appearing at the bottom of the content assist list

If you select the addActionListener(ActionListener l) item in the content assist list, then the code to call the method will be added. However, if you select the addActionListener template, then the code to call the method, along with the code for an anonymous innerclass to be the listener, will be added.

Private javax.swing.JButton getIvjJButton() { 
   if(ivjJButton == null) { 
      ivjJButton = new javax.swing.JButton(); 
      ivjJButton.addActionListener(new java.awt.event.ActionListener() { 
         public void actionPerformed(java.awt.event.ActionEvent e) { 
         } 
      }); 
   } 
   return ivjJButton; 
}

After the template is used, the cursor will be positioned inside the actionPerformed() method. You can then write the code that will be executed when the button is pressed.

If the template for the event you wish to add a listener to is not present in the available code assist list, then you might be able to import it into Application Developer. The Visual Editor provides additional templates that are located in the directory, /plugins/com.ibm.etools.jbcf.codegen_5.0.0/Examples/Templates. Content assist templates are available for the common AWT and Swing Java beans as individual files, or you can import all templates in a directory by selecting the AllTemplates.xml file in a directory. To import these templates, launch the Preferences dialog by selecting Window => Preferences from the menu, and then selecting Java=> Templates. Click the Import button to open a file browser, and then navigate to the directory containing the template files.


Testing Java beans

To execute your Java bean and see its run-time behavior, you need to write a class with a public static void main(String[] args) method that instantiates the Java bean and makes it visible. If the Java bean is not a top-level window, but is for example a panel, then you would need to create a frame to put the panel in. If the class is an applet, then you need to write an HTML file to test the applet.

The Visual Editor includes a Java Bean launcher, which you can use instead of writing a main(String[] args) method. Open the Java Bean launcher by selecting Run => Run As => Java Bean from the menu, or by clicking the drop-down button in the toolbar:

Figure 24.
Selecting Run =&gt; Run As =&gt; Java Bean from the menu to launch the Java Bean Launcher

The Java Bean launcher instantiates the selected class using the default constructor, and if required, will create a Frame or JFrame to place it in. When you use the Java Bean launcher, you are creating a configuration for the class being tested. Select Run => Run to edit configuration properties, and to delete and create new configurations.

Figure 25.
Screen capture of the Create, manage, and run launch configurations dialog

If the class you are testing extends java.awt.Applet or javax.swing.JApplet, then go to the Applet Parameters tab view of the launch configuration to specify its parameters; it will be launched inside an applet viewer. Other tab views let you specify VM arguments, classpath information, and so on. Besides using the Java Bean launcher to run your Java beans, you can also select Debug => Debug As => Java Bean to run Java beans using the debugger. Of course, in the debugger you can set breakpoints to stop the code and analyze its behavior.

By comparison, in VisualAge for Java, you could not test a Java bean, and you could only execute Java beans through a public static void main(String[]) method. The Visual Composition Editor was able to generate a default implementation of the main(String[] args) method to help test the Java bean. However, the disadvantage is that in an application, you typically want to launch only a few classes. Having every Java bean implement a main(String[] args) method unnecessarily inflates the size of the run-time Class file.


Migrating from VisualAge for Java

Because the new Visual Editor directly reads and writes source code and has no additional metadata files associated with it, you can open a Java file that was created with the Visual Composition Editor and begin working with it immediately in the Visual Editor. No formal migration step is required; however, you can choose to run a migration utility inside VisualAge for Java to help prepare the source code before importing it into Application Developer. The migration utility can remove comments that are no longer required, and it can also capture the positions of top-level Java beans on the free form surface. Note that these steps are optional, so even if you do not run the migration utility, you can export your source from VisualAge for Java, import it into Application Developer, and then open a Java file with the Visual Editor to continue editing.

The migration utility is used to capture the positions of top-level Java beans on the free form surface because this position is design-time data that is not present in the source code. In the earlier VisualAge for Java Visual Composition Editor, if you moved a top-level Java bean around, and regenerated it, the source would not change. The position is stored in the metadata that is used to serialize the Visual Composition Editor's Java beans. In the new Visual Editor, there is no metadata and all data must be stored in the Java source file, so the position of a top-level Java bean on the canvas is stored in a comment beside each field, such as:

private javax.swing.JButton ivjJButton = null; 
   // @jve:visual-info decl-index=0 visual-constraint="205,26"

The comment is optional; without it the Visual Editor will position the Java bean in a default position. It is only used for Java beans located directly on the canvas, so a component that is a child of a container doesn't require a positional comment because its location is captured in actual source code statements. The migration utility in Visual Age for Java will write the positions of any top-level Java beans in the comment format that is recognized by the Visual Editor, so that after you migrate the source code to Application Developer and open it in the Visual Editor, all non-visual and top-level visual Java beans will be placed in the same position as they were in the Visual Composition Editor.


Conclusion

The new WebSphere Studio Visual Editor provides similar functionalities as the earlier VisualAge for Java Visual Composition Editor. This article covered the basics of the Visual Editor and discussed how to use the various panes to work with Java beans. To build a fully functional application GUI, you would need more in-depth knowledge of each AWT or Swing component, and how to apply best practices within the Visual Editor. Future articles and tutorials will examine these aspects in more depth and cover different scenarios to help you use the Visual Editor to build a client application quickly and efficiently.

Questions from users

Question: The author completely ignored SWT and why it might be a better choice than Swing.

Response from authors: Thank you for your question and for taking an interest in the Visual Editor for Java. For the first release of the Visual Editor for Java, our goal was to provide a tool that would provide Visual Age for Java customers (using the Visual Composition Editor) with a GUI builder within WebSphere Studio Application Developer. The Visual Composition Editor lets users create classes using JavaBeans components. The JavaBeans specification is part of the Java language specification. A Java bean class must have a default constructor, get and set method pairs that can be combined together as properties to allow for easy modification of state, and the ability to describe editor details within BeanInfo classes. If the JavaBean is part of, or subclasses part of, the Abstract Window Toolkit (AWT) or Swing, then the Visual Editor for Java will display the graphic of the GUI component to give you a preview of how the class will look at design time.

The Standard Widget Toolkit (SWT) is part of the Eclipse project and is used by WebSphere Studio Application Developer for its interface. When the SWT was first created, it was intended to be used as a set of widget classes simply for the Eclipse-based tools. It uses native OS controls for its widgets, unlike Swing, which is a lightweight toolkit, or AWT, which doesn't have a rich set of advanced UI classes. Some users have expressed interest in developing end-user applications that take advantage of SWT.

Currently, customers can create GUIs using SWT, and the Eclipse OPL lets you do this: http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/faq.html#useStandAlone. Currently, no GUI builders are available to let you build an SWT application, although efforts are being made to create such a tool: http://eclipsewiki.swiki.net/145.

SWT widgets are not JavaBeans because of how they must be constructed and their use of a bitmask of style constructor arguments rather than properties for many of the attributes. Therefore, they cannot be used in the Visual Editor for Java, which is based around the JavaBeans components model. Whether SWT is a better choice than Swing is a debate that has been discussed in numerous places, such as the Java Developer's Journal, http://www.sys-con.com/java/articlenews.cfm?id=1634, and many newsgroups, including http://dev.eclipse.org/newslists/news.eclipse.tools/msg38571.html and http://dev.eclipse.org/newslists/news.eclipse.tools/msg31906.html. To obtain a password to access the eclipse newsgroups, refer to http://www.eclipsecorner.org.

Question: With VisualAge for Java's Visual Composition Editor, we were able to wire non-visual components. Can you do this with the new Visual Editor for Java?

Response from authors: While some users of the Visual Composition Editor liked the approach of programming by connections, others found it hard to use because of problems introduced when the number of connections became too large. This resulted in visual complexity for users when trying to understand and modify a diagram; some users also experienced problems debugging and analyzing the generated code. Connections were introduced into VisualAge for Java so that the user did not have to understand the generated code (keep in mind that VisualAge for Java was built at a time when Java programming skills were rare and at a premium). Later versions of VisualAge for Java moved away from being a top-down development tool to one where developers wanted more access to the generated source. User code points were introduced in Version 2.0 to 1) allow developers to add logic within code generated methods, 2) provide event-to-method connections with the method name visually attached to the end point, and 3) provide a feature that tried to reverse engineer the JavaBeans model from the source code itself. Many of our users found that connections became difficult to manage. They ended up using the Visual Composition Editor as a GUI builder for the visual components, and then did the event coding by hand.

The Visual Editor for Java is a code-centric tool that works with the Java code; this differs from the Visual Composition Editor whose role was to separate the user from the source code. To accomplish this, we read and write Java code with no additional metadata, and we generate and parse incrementally, and have linked selection from the JavaBeans and their properties to the source. To write event handling logic, you must select the JavaBean, which will then drive the source to the relevent initialization method, and then use code assist to write the code. The Visual Editor for Java provides templates that let you add common patterns such as addActionListener with simply a few keystrokes. Refer to the user documentation for more information on how to use templates.

We built the Visual Editor for Java on the philosophy that the editor is code-centric, and that it drives and reads and writes the source code, so that developers can make modifications at both ends. We hope that the solution we create will satisfy both users who prefer high-level programming and those who like to work directly with the source code. If you want to provide more input on connections, or enter discussions with other users, visit the newsgroup server news.software.ibm.com and group ibm.software.websphere.studio.application-site-developer.

Question: On my project, we have a lot of custom Beans (DatField, AdvancedTable, etc.), so I created a palette for our bean. For the tricky part, see
C:\Program Files\IBM\WebSphere Studio\wstools\eclipse\plugins\com.ibm.etools.jbcf.visual_5.0.1.1\palette. You can duplicate the Swing palette and add your own component! Our bean in VisualAge for Java had a BeanInfo companion, but in WebSphere Studio one of them was no good -- no visual compositions were viewable or editable. The solution was to delete one of them (losing some predefined values for properties editor -- everything has a price ;-) ). For those interested in getting the resources (translation, etc.) in the new editor, I suggest making the resource project a simple Java project. It works fine, though I'm not sure why.

P.S. What is the date for the next release?

Response from authors: For the palette, you should not change the supplied palette file, as this will be overwritten when you upgrade to new versions of WebSphere Studio. An API mechanism for adding new palette categories is described in Extending the Palette in the WebSphere Studio Visual Editor for Java. The bean you describe that was created in VisualAge for Java should have migrated across to the Visual Editor and should be viewable and editable. The only things that would not be viewable and editable are the connections, but the GUI should still show the Java beans and it should let their properties be modified.

We did extensive testing for this scenario, and the only defect we found is that if the Java bean being used is abstract or if the bean being edited extends an abstract class, then an exception is thrown. PTF 001 fixes this problem. If this does not work, please post a description of your problem, together with screen shots and a test case with sample code, either on the newsgroup server news.software.ibm.com and group ibm.software.websphere.studio, or else in a note to wsdd@us.ibm.com.

I don't understand whether making the project a Java project fixes this problem or not. It is true that the Visual Editor can be used only with a project that has a Java nature, which gives it a build path and lets you edit Java artifacts, so a simple Java project works, but so should any kind of Web project. If the project type is anything other than just a resource project and there are problems, please provide more detail, including screen shots, sample code if possible, and detailed sequential steps to re-create the problem.

Regarding the release date for the next version of WebSphere Studio, an announcement on this topic will be made in early August on WebSphere Developer Domain. For legal reasons, we cannot give details before the formal announcement.

To see additional user comments, click the View results button below.

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere
ArticleID=13208
ArticleTitle=IBM WebSphere Developer Technical Journal: Comparing WebSphere Studio Application Developer with VisualAge for Java -- Part 3
publish-date=10162002