UpPreviousNext

Java Example

In this example, we will work with Java to construct a very simple color selector. The finished application will allow the user to choose a color and see it displayed. Additionally, we will include a simple dialog. The finished JAVA color selector is shown in A Simple Java Color Selector .

You have a choice of creating a program that runs as a Java Application, or as an Applet. You can make this choice at any time during the development cycle, and you can easily change your mind at any time as well.


Note: We will postpone work with the Abstract Window Toolkit (AWT) advanced layout classes, and classes in general, until later in this guide ( Classes and Methods and Java Layouts ).

A Simple Java Color Selector

Preparing for a Work Session

Starting Builder Xcessory

1. Start Builder Xcessory.

If you have been using Builder Xcessory, select New from the Browser File menu to begin a fresh session.

2. Select Java as your language from the Choose a Language dialog of the Browser Options menu.

Applets and Applications

1. Create your main window about three inches wide and two inches high.

You have a choice of creating a Java Application or Applet. To create an Application, use a Frame. To create an Applet, use the Applet. We'll be building a menu system in this example, so create a Frame.

2. Click on the Frame Palette icon. You are presented with a rectangular outline of the object. Move this to a convenient screen location and with MB1, drag the rectangle out to the desired size. (See Using the Palette for review.)


Note: From this point forward, we will refer to your top-level object, in this case, a Frame, as your "main window."

Creating Objects

1. Create a MenuBar and place it as a child of the main window, using one of the following methods:

· Click on the MenuBar Palette icon and click again on top of the main window.
· Drag the MenuBar Palette icon from the Palette and drop it on the main window.
· Drag the MenuBar Palette icon from the Palette and drop it on the main window instance representation in the Browser display area. (See Display area and Instances/ Classes view combination box for review.)

Note: The AWT Frame is the only container that accepts a Menu Bar as a child. It "knows" about MenuBar objects and automatically moves the MenuBar to the top of the window and resizes it to span the entire width of the container.

2. Create a Label and place it as a child of the main window.


Note: The first time you create and place an object, it is usually best to resize it as you place it. Otherwise you are likely to end up with a widget that is too small to easily deal with. If this happens, select Enlarge from the Browser:Edit menu, or from the MB3 Quick Access menu.

3. Create a Scrollbar and place it as a child of the main window.

Selecting Multiple Objects

Select both the Label and the Scrollbar in preparation for copying, using one of the following methods:

· Select the first object normally to ensure that no other objects are accidentally included. Select the other objects, each in turn, with Ctrl-MB1. You can perform this operation directly on your interface, or in the Browser clicking on the instance representations.

· Using Shift-MB1, drag out a rectangle, enclosing all of the desired objects. Any object entirely within the rectangle is selected. You can circle the objects directly, or you can circle their Browser representations.

Copying Objects

1. Copy the Label and Scrollbar, and paste two copies as main window children, for a total of three Label/Scrollbar groups. Use one of the following methods (check that both objects are currently selected, or select them by clicking on the objects or their Browser representations):

· Select Copy from the Browser Edit menu. Then select Paste from the same menu. You are presented with an outline of the object. Place it into the main window. Select Paste a second time and place the next object into the main window.
· Select Copy from the MB3 Quick Access menu by pressing MB3 while the cursor is over any of the objects or its Browser representation. Then select Paste from the same menu. You are presented with an outline of the object. Place it into the main window. Select Paste a second time and place the next object group into the main window.

Shortcut

· While holding down the Control-key, drag the objects with MB2 to another location in the main window and drop them. Repeat to create the third group. You can also perform this Ctrl-MB2 drag operation with the Browser representations.

Hint: Be careful not to drop a new scale onto another scale. That creates the new scale as a child of the existing scale. If this happens, use MB2 (without Ctrl) to drag the new scale out and onto the BulletinBoard.

Creating a Canvas

2. Create a Canvas and place it as a child of the main window.

This is the area in which the user will view the selected color. It should be about 1" wide and 1.5" high.

Your Interface in Progress shows the result of the preceding steps:

 

Your Interface in Progress

Setting Instance Names

Using your own instance names when working with Builder Xcessory is good practice. There's no guarantee that the default names will be maintained from session to session. (Besides, imagine sitting down to maintain your application months later and trying to figure out what pushButton73 is supposed to do...)

1. Assign instance names to the existing objects.

To save time, we'll only assign names to objects that are directly referenced in our code.

2. Select each object and enter the new name in the Instance Name field at the top of the Resource Editor. Use the following names:

label -> redLabel
label1 -> greenLabel
label2 -> blueLabel
scrollbar -> redScrollbar
scrollbar1 -> greenScrollbar
scrollbar2 -> blueScrollbar
canvas -> colorArea

Note: When generating Java source code, Builder Xcessory automatically prepends an underscore character to all instance names (following accepted convention). So redLabel appears as _redLabel in all generated code.

Working with Multiple Objects

Now that we have created the basic objects, we'll begin customizing them and designing the layout.

Setting resources

We'll begin this stage by setting a number of resources.

1. Select all of the Scrollbars using one of the following methods:

· Select the first object normally to ensure that no other objects are accidentally included. Select the other objects, each in turn, with Ctrl-MB1. You can perform this operation directly on your interface, or in the Browser by clicking on the instance representations.
· Using Shift-MB1, drag out a rectangle, enclosing all of the desired objects. Any object entirely within the rectangle is selected. You can circle the objects directly, or you can circle their Browser representations.

2. Update the Resource Editor using one of the following methods:

· Select Update from the Resource Editor View menu.
· Click on the Update toolbar icon.
· Double-click on the selected object or its Browser representation.

3. Set the following resources (check that All Resources is selected from the Resource Editor View menu):

maximum: 255
minimum: 0
Java deals with 8 bits of precision in each color, thus the range of 0 - 255
value: 255
We'll start off at white.
increment: 1
The increment value represents how much the scrollbar's value is changed when its end is clicked once. It represents the minimum change that can be made to the value. Here, and in most cases, we want this to be 1.
visible: 1
The visible value represents the "page size" of the scrollbar, or how much of the minimum-maximum range is represented by the visible area of the scrollbar. It controls the size of the scrollbar thumb. Here, where we are using the scrollbars to control single values, and not a scrolled area, the visible resource is not particularly meaningful. Setting it to one insures that the scrollbar thumb is as small as possible.

Hint: Use the search area of the Resource Editor to quickly locate each of the resources. (See Search area for review.)

4. Set the following resources on all the Labels:

label: 255
The label resource should match the value of the scrollbars at start-up.

5. Set the following resources on the Canvas:

background: white
We want to make sure all the settings start out in synch, so make the color display match the scale values.
height: 150
weight: 150
Canvas components have no default size, so we set a value here so the layout manager knows how much space to allow.

Java Layouts

Now we'll work on the layout. Java layout objects can be fairly complex to use. Builder Xcessory simplifies this by hiding the actual layout objects from you during the Builder Xcessory session. To specify a layout, you set an attribute on the container using the Resource Editor. For layout policies that allow you to specify positions for the container's children, you set constraint resources on each child using the Resource Editor. Builder Xcessory takes care of synthesizing this information and creating the proper layout and constraint objects for you. For discussion of the various layouts and how to use them, see Java Layouts .

Flow Layout

In our example, we will use the simplest layout, the Flow Layout. This allows our main window to manage each of its children into rows. Each child keeping its preferred size.

1. Set the following resource on your main window (Frame):

layout: FlowLayout

At this point, you'll notice that Builder Xcessory immediately applies the new layout policy to your interface. You can see that the labels, scrollbars, and canvas have all been placed into a row. You'll also notice that you cannot move or resize the children. This is because Java layout objects, for the most part, do not permit resizing.

Working with the Flow Layout

Your labels and scrollbars may not be in the proper order. The FlowLayout object manages its children in the order that they are created, from left to right, one row at a time. To change the order of creation, select an object and use one of the following methods:

· Use the Raise and Lower options from the Browser:Edit menu.

· Use the Raise and Lower options from the MB3 Quick Access menu.

Your Interface in Progress shows the result of the preceding steps:

 

Your Interface in Progress

Adding Action to your Interface

In this section, we add methods to various objects so that when the user adjusts the scrollbars, something actually happens. Some methods we will write, others are already part of the AWT classes.

1. Set the following resources on all of the Scrollbars.

scrollAbsolute: setColor()
scrollLineDown: setColor()
scrollLineUp: setColor()
scrollPageDown: setColor()
scrollPageUp: setColor()
An AdjustmentEvent argument is added automatically to the setColor() function when the code is generated.
For the last value that you set, use the Builder Xcessory extended editor, invoked by clicking on the button labelled... to the right of the resource field in the Resource Editor. We will use this editor in the next step.

2. Add the code for the setColor method using one of the following methods:


Note: In order to add code to a file, the file must exist. Builder Xcessory automatically generates code when you bring up the Method (or Callback) Editor. It's a good habit to be sure that you are in the correct working directory so that your files will be in the right place. Use the File Names tab panel (Browser:Options:Code Generation Preferences) to set your working directory. Performing a Save, Save As, or Open operation (Browser:File) also sets your working directory.

Callback Editor

· Write the setColor code using the Builder Xcessory Callback Editor. Bring this up by clicking on the Edit button to the right of the method name in the extended editor. This starts up the configured editor with the correct file loaded in at the appropriate User Code Block.
If this is your first time using the Callback Edit feature, you must specify an editor to use, such as emacs or vi. You can do this without dismissing the Callback Editor. Choose an editor from the Options menu (Browser:Options:Tools Preferences:Editor). See Using emacsclient for information on Emacs.

Generating code

· Add your callback code by generating code (Browser:File:Generate) and editing the appropriate file from outside the scope of Builder Xcessory.

User code blocks

In either case, you insert code into a User Code Block. User Code Blocks are present in many different locations in all Builder Xcessory-generated files. Any code that you insert into a User Code Block is preserved by Builder Xcessory whenever source code is generated.

Note: If you add code to any of the files outside of these User Code Blocks, it will be lost when you generate new versions of these files with Builder Xcessory.

Insert the following code into the setColor method User Code Block in the AwtFrame.java file.

// Begin user code block <setColor>
int red = _redScrollbar.getValue();
int green = _greenScrollbar.getValue();
int blue = _blueScrollbar.getValue();
_colorArea.setBackground(new Color(red,green,blue));
// The Windows Java ports don't update the canvas
// after setting the background, so we have to do a
// repaint here.
_colorArea.repaint();
_redLabel.setText(Integer.toString(red));
_greenLabel.setText(Integer.toString(green));
_blueLabel.setText(Integer.toString(blue));
// Don't pass this event any further.
// It's been handled.
return(true);
// End user code block <setColor>

Working with Menus

Now that we have taken care of the basics of our application, we'll fill in the gaps by adding menus and a simple dialog window.

1. Create a File menu.

Drag a Menu onto the MenuBar. Builder Xcessory automatically creates a Menu object, a MenuPane object, and your first Menu Item.

Note: When you select the Menu, all of the menu items are displayed in your interface. You can control this display by turning Show Menu Children (Browser:View) on or off while the Menu is selected. With menu items posted, you can select any number of them in the usual manner, drag and drop, raise and lower them, and so forth.

2. Set the following resources on the Menu:

instance name: fileMenu
labelString: File

3. Set the following resources on the Menu Item:

instance name: exitButton
labelString: Exit

4. Create an Exit method for the Exit Menu Item:

For the next resource, use the extended editor to bring up the callback editor.
actionEvent: exitApp()
Using the Edit button on the extended editor, add the following line to the User Code Block:

Note: You must "Apply" the procedure name before editing it.
// Begin user code block <exitApp>
System.exit(0);
// Don't pass this event any further.
// It's been handled.
return(true);
// End user code block <exitApp>
An ActionEvent argument is added automatically to the exitApp() function when the code is generated.
Save the file and apply this method with the Apply button on the extended editor.

5. Create a Dialogs menu and apply the following resources to the Menu:

instance name: dialogMenu
labelString: Dialogs

6. Set the following resources on the Menu Item:

instance name: aboutButton
labelString: "About..."
actionEvent: popupAbout()
 
// Begin user code block <popupAbout>
_aboutDialog.show();
// Don't pass this event any further.
// It's been handled.
return(true);
// End user code block <popupAbout>
An ActionEvent argument is added automatically to the popupAbout() function when the code is generated.
We'll create the aboutDialog in the next section.

Working with Dialogs

1. Create a Dialog as a child of your main window.

When creating Dialogs, you are prompted for a class name. Specify the desired name.

2. Set the following resource on the Dialog:

instance name: aboutDialog
Resize the Dialog, if necessary, so that it is about 2" wide by 1.5" high.

3. Create the Dialog contents.

Because the Dialog is now a class, you cannot modify its instance directly. You need to enter Builder Xcessory Classes view. Select Classes from the combination box located under the Browser Panner. (See Builder Xcessory Browser .)
Once in Classes view, you can edit the object(s) directly.

4. Prepare the Dialog layout.

For this section, we'll use a new layout policy, Border. The Border layout places its children into North, South, East, West, and Center positions. (See Border .) Set the following resource on the Dialog:
layout: Border

5. Add two Labels to the Dialog. (Java does not directly support multiline labels.) Set the following resources:

label: Java Color Editor
alignment: Center
direction: North
label1:
label: Version 1.0, Created by <your name>
alignment: Center
direction: Center

6. Create a Panel as a child of the Dialog.

The Border layout policy resizes each child to entirely fill their specified region. We will add a "Dismiss" button to the dialog and do not want it to resize. Placing the button in the Panel prevents this. Set the following resources:
layout: Flow
direction: South

7. Create a PushButton as a child of the Panel and set the following resources:

label: OK
actionEvent: popdownDialog()
// Begin user code block <popdownDialog>
if(e.getActionCommand().equals("Ok"))this.setVisible(false);
// Don't pass this event any further.
// It's been handled.
return(true);
// End user code block <popdownDialog>

8. Enter Instances view.

Now that we've finished the Dialog, select Instances from the Browser combination box.

Your Interface in Progress shows the result of the preceding steps:

 

Your Interface in Progress

Testing Your Application

We've now reached a point where we would like to test our application and specifically, its interface.

1. Save the interface (Browser:File:Save).

The first time you save a new project, you'll be presented with a file selection dialog. To change filenames for subsequent save or generate code operations, use the Save As option (Browser:File). Open, Save, Save As, and Generate Code operations all set your working directory for subsequent save and generate operations.

2. Enter Play Mode (Browser:Project:Play Mode) and test your interface.

In Play Mode, you can try out your interface. Your menus will post, buttons will push, and so forth. You can test all of your resize behavior. Methods you've written, however, are not active. To test these methods, generate code by selecting Generate Code from the Browser File menu, compile, and run.

Note: Using the UNIX command line is still the preferred method for many developers. Builder Xcessory generates both Imake and Makefiles for you. See Working with Source Code for more information.

3. When you are finished testing, re-enter Build Mode (Browser:Project).

Creating a Uniform Look and Feel for Your Application

There are many attributes, such as colors, fonts, and so forth, that contribute to an application's personality, or look and feel. Builder Xcessory helps you to define a total look and feel by building style sheets that can be reused and shared with other developers. You can use system styles to help all of your developers conform to a corporate style guide, clearly identifying all of your applications as part of a single family, and reducing the learning curve for your end-users.

A Builder Xcessory style is basically a collection of resource:value pairs that you define. Styles are related to one another as parents and children. Substyles inherit the resource values of their ancestors while overriding any ancestral values that are specifically re-defined in the substyle.

In this section, we'll build a very simple set of styles for your color selector.

Bringing up the Style Manager

1. Bring up the Style Manager (Browser:Managers:Styles).

In the Style Manager you see a style named "BaseStyle". This is the root style and serves as a placeholder. Notice the padlock symbol next to the name. This style, and any style with the padlock symbol, including system styles you create, cannot be edited.

Creating a new style

2. Create a new style.

Select Create Substyle from the Style Manager:Edit menu. This creates a new style as a child of the currently selected style, in this case as a child of BaseStyle.

Note: Just as with other UI objects, styles can be cut and copied or manipulated with the mouse, including all drag and drop operations, reparenting, and so forth.

Defining a new style

3. Define the new style.

Select the style (BaseStyle1). Select Edit Substyle from the Style Manager:Edit menu to bring up the Style Editor. You can also double-click on the style to invoke the Style Editor.

Creating a list of resources

First create a list of the resources you want to define in this style, using one of the following methods:
· Click on the Resources combination box arrow. This drops down a scrollable list of all available resources. Click on one or more resources to select them. You can deselect a resource by clicking on it a second time. When satisfied, click again on the combination box arrow.
· Type the resource names into the Resources combination box text field, separating multiple resources with commas. Enter Return to terminate the list.
Your selected resources appear below the combination box, where you can set their values just as you would in the Resource Editor.
You can add or delete resources from a style at any time. This affects all objects using the style.

Adding resources

Add the following resource:value pairs to the style:
background: blue
foreground: yellow
fontList:-*-helvetica-bold-r-*-*-*-100-*-*-*-*-iso8859-1
It's easiest to use the extended editor to select the font.
The font above is Helvetica, bold, 10 point. Choose any values you prefer.
See Extended Editors for more information.

Applying new definitions

Use the Apply button in the Style Editor to set the style definition.

Applying a style to an entire interface

4. Apply the style to your entire interface, preserving the background value of the Canvas widget.

You can apply a style to part, or all, of your interface by using one of the following methods:
· Select Apply from the Style Manager to apply the selected style to the selected object or to the selected object and all of its descendants. Force overrides any resource values already set on the affected objects. Otherwise, the resource values are preserved. Don't force the style in this case to maintain the white background of the Canvas.
· Dragging a style onto an object or its Browser representation with MB2 forces the style to the object, overriding any duplicated resource values.
· Dragging a style onto an object or its Browser representation with Ctrl-MB2 forces the style to the widget and all of its descendants, overriding any duplicated resource values.
· Selecting any group of widgets and entering the style name into the Style field of the Resource Editor applies the style to all of the selected widgets, preserving any resource values already set.

Note: Styles applied to classes while in Instances view are ignored. To apply a style to a class, you must be in Classes view.

5. Create a second style as a child of BaseStyle1 (the style we've created above).

Select the intended parent style, then select Create Substyle from the Edit menu of the Style Manager.

6. Add the following resource:value pairs to the style:

foreground: red
fontList: -*-times-bold-r-*-*-*-100-*-*-*-*-iso8859-1
It's easiest to use the extended editor to select the font.
The font above is Times, bold, 10 point.

7. Apply (force) this style to your DialogShell and its children.

Your new style has inherited the blue background from its parent.

8. Edit the first style you created (BaseStyle1), changing the value of the following resource:

background: black
Apply the change in the Style Editor. Note that each widget using that style immediately reflects the change and that each widget using a descendant of this style (including your dialog) also reflects the change.

For more information about styles, including the creation of system styles, refer to Styles .


Note: Bugs in the current Windows implementation of AWT prevent the java.awt.Panel class from behaving correctly, particularly with regard to the background resource. If you display this example application on a Windows system, this will be evident.

Working with Source Code

You can generate source code and run your application at any point in the development process.


Note: Builder Xcessory always generates code that compiles and runs, generating stubs where your routines will be placed. However, if you have begun adding incomplete routines such as callbacks, methods, and so forth, they may prevent your application from executing.

Creating source code

To create source code with Builder Xcessory, perform the following steps:

1. Customize your makefile to use your compiler of choice and reflect the library locations of your system (Browser:Options:Code Generation Preferences).

Be sure that your working directory is set correctly with the File Names tab sheet in the dialog. Use the Makefile tab panel to set up your makefile (specify your compiler, library locations, and so on).
You can also add your own include information, customize filenames, and turn on and off generation of any particular file.
See Code Generation Preferences for more information on these dialogs.

2. Generate source code (Browser:File:Generate).

3. Build and run your application.

Use the Make or Imake files that Builder Xcessory creates from the UNIX command line, your normal build process. Builder Xcessory also generates an HTML file for you. You can load this file into your favorite Java-enabled web browser and run your Java application from there.

Note: Though you can launch a Java application from your browser, keep in mind that many common application-oriented methods, such as System.exit() generate security violations in a browser environment. In this case, it would mean that the only way to exit the application would be to exit the browser.

You can now run your color selector. This concludes our Java example.

Additional work

Feel free to continue to explore Builder Xcessory' capabilities. Some ideas for additional work include:

· Experiment with the GridBag layout.

One major problem with using the Flow layout is that the default size for Java scrollbars is very small. Simply setting their height resource does not work, as it does for the Canvas class (you'll have to ask Sun why this is so). Getting a reasonable size for the scrollbars requires using a layout manager that controls the size of its children. FlowLayout does not; it merely asks each component for its preferred size and tries its best to lay them out as they like. One idea would be to use a GridBag, with the components laid out along row 0. The fill for the scrollbars would be set to vertical, while the canvas would be filled along both axes. The labels would most likely want a center anchor.
(See GridBag for more information.)

· Allow the user to enter an RGB value directly.

The labels might be replaced with TextField components. The actionEvent method must first verify that a valid number had been typed (perhaps warning the user with another dialog), then ensure that the scrollbars and labels are in sync, and then call the setColor() method.
UpPreviousNext