Hello World

Your First WFC Application

By Shannon Dunn

Microsoft Windows Foundation Classes (WFC) is a powerful and flexible framework for application, component, and Web design. In this article, we'll explore the history of WFC, starting with the inception of Java. We'll then examine the different packages that make up WFC, and highlight the important classes within each package.

We'll also create a traditional "Hello World" application so you can see how easy it is to create a simple window that displays text in the WFC framework. At article's end, you'll understand what WFC is and have an appreciation of its abilities to assist you in development endeavors, especially in the realm of Windows application development.

Java Is a Programming Language

Since its inception, Java has been a controversial technology. In its most basic form, it's a programming language that borrows and enhances syntax elements from C++. Java comes with a useful set of libraries that allows it to create just about any type of application, including applets for Web pages. Java differs from more traditional programming languages in that it provides the Java Virtual Machine (VM). The VM is an interpreter that — in theory — allows your application to be written on any platform and run on any platform. The VM is responsible for translating the Java commands to the underlying system commands. The premise is that you can write applications that are cross-platform. Because of this theoretical ability, Java has gained much notoriety.

In reality, however, the VM isn't quite that portable. Because it's supposed to be designed to run on the "least common denominator" system, the VM can't really take advantage of some interesting and powerful features particular to the system on which it runs. For most real-world application development, this lack of flexibility is unacceptable. Also, Java applications aren't truly cross-platform because no two VMs are the same. With each vendor writing VMs designed to run better for its particular platform, portability of Java applications written on different platforms is inconsistent. Finally, because the VM is an interpreter, Java programs tend to be slower than compiled languages.

Many people in the "write once, run anywhere" camp will explain that these are all problems you must either endure or repair to get the true features of Java working for you. For most companies, this answer is just not feasible. They need to be able to write fast, attractive applications that are optimized for their platforms. If losing cross-platform capabilities in a single code base is the result, most companies will pay this price.

Microsoft saw Java as a programming language — not as a platform. It also viewed Java as an excellent middle-ground language for writing Windows applications. Java's ability to produce object-oriented, pointerless, and memory-friendly software makes it an excellent language for writing Win32 applications. These views were based mostly on feedback from developers and corporations that were interested in Java, but who saw it as a technology that didn't satisfy their application development needs. Although this decision is unpopular with most "right-wing" Java developers, it's been embraced by the people who are most important when you're developing a programming tool, i.e. the customers.

WFC Saves the Day

Early on, Microsoft's answer for developers who wanted to write Java applications for the Win32 platform was a technology known as J/Direct. This technology allowed developers to access the Win32 application programming interface (API), as well as third-party libraries that supported Windows development. This answer was crude, however, because it forced developers to effectively "crack out the Petzold book" and write applications that had to handle message pumps, window handles, raw window creation, and other such issues. Many developers who wanted the richness of the Java language decided to take this path, and wrote successful Win32 applications.

Microsoft decided that J/Direct, although a great technology in and of itself, needed to be made easier. Visual J++ needed a development framework that could assist Java developers in writing applications targeted for the Win32 platform — a framework that could take away the complexities of writing Win32 applications using J/Direct exclusively, yet go beyond being a simple wrapper around the Win32 API.

The answer came in the form of Windows Foundation Classes, or WFC for short. WFC is a set of classes that provides an object-oriented methodology for writing Windows applications. By using J/Direct in the classes and methods, WFC goes beyond simply wrapping the API, and makes complicated tasks and features easy to implement. This framework is similar in many ways to the Microsoft Foundation Classes (MFC) provided with Visual C++. WFC not only encapsulates the Win32 API, it also provides features that remove the complexity and automate the process of creating Windows applications.

WFC: More Than a Framework

In addition to being a well-designed framework for developing Windows applications, WFC also provides several features that make it easier to use and more powerful than most other programming languages. For J/Direct to access the entire Win32 API, it must be able to call methods in the API known as callback methods. These methods require a function pointer, something that can be accomplished only in C/C++, Delphi, and Visual Basic 5.0.

Also, to create an easy-to-use event model, being able to call a callback method is a requirement. WFC introduced a keyword into the Java language, which is Java's answer to the callback method: delegate. Now a method can have a reference to a method that needs to be called after it completes execution. The ability to use delegates makes Visual J++'s event model one of the easiest to use, as well as one of the most powerful among all Windows' development languages.

To respond to the Java programmers' need for a component model they can use in their WFC-based applications, WFC incorporates a powerful component model. This model allows Java developers to create controls and components they can use in their Windows applications that don't need to be compiled into a special file, such as an ActiveX control. Unlike JavaBeans, WFC controls can be versioned and licensed, making them more useful and powerful for developers who want to distribute their controls as third-party components. Because a WFC control is designed to use the Component Object Model (COM) as its backbone, developers can also export WFC controls to an ActiveX control and use them with other applications that support ActiveX and COM. The framework and its component model make a powerful one-two combination for developers seeking a unified programming model under which to write.

With the release of Internet Explorer 4.0, with its Dynamic HTML (DHTML) capabilities, Microsoft realized that writing complicated Java applets wasn't the answer for customers interested in targeting the Windows platform as well as other platforms. If you really wanted to target multiple platforms, your best answer was to combine HTML and DHTML to create dynamic content.

The only problem with this answer is that DHTML, although very powerful, is difficult for most Web designers to use. Seeing this difficulty in writing DHTML code, the WFC team decided to give the WFC framework the ability to use Java to write the DHTML code. Because most of Java's libraries are designed for writing Web content, why not wrap the DHTML libraries into Java classes and give Java developers the ability to create truly cross-platform solutions using DHTML?

The html package of WFC contains a large number of classes that make writing DHTML code much easier for Web developers. If you combine the WFC framework with its ability to use delegates, the WFC component model, and the DHTML class libraries, you'll find that WFC is a powerful and flexible framework for building almost any type of application, component, or Web project.

WFC Packages

To get the most out of WFC, you should understand the various packages and classes that comprise it. Let's take a look at the different packages, and explore some of the more important classes within each.

com.ms.wfc.app

The app package is relatively small. However, it provides a number of important classes to support the application, as well as related application features such as messages and threads. It also includes classes that support application-wide features, such as the registry, Clipboard, and locale. Many of the classes are static classes that simply provide static methods; thus, many can't be instantiated. If you've seen the code that's provided for a form, you might have noticed calls to the Application class's run or exit methods. The Application class provides a number of static methods that allow you to run and exit an application, store information in the application's thread storage slot, obtain information about the current locale for the application, and conduct message filtering.

Other classes you'll often use in your applications are the Registry, RegistryKey, and Clipboard classes. The Registry and RegistryKey classes allow your application to easily gain access to hives, keys, and values in the system Registry. The Clipboard class provides two simple methods that allow you to retrieve and set information in the system Clipboard. The Clipboard class uses the app package's DataObject class for retrieving information from the registry. You'll use the DataObject class in a number of places where a specific data type is unknown.

Other classes you might find useful are the Time and TimeInfo classes, which encapsulate date and time information. They also provide a number of methods to simplify parsing and evaluation of dates and times.

If you want information from Windows, such as the directory for recently opened documents or the Windows desktop directory, you'll find the SystemInformation class extremely useful. When you're stumped about how to get information from Windows, look here.

Most of the other classes in the package are not frequently used in typical applications.

com.ms.wfc.core

The core package is exactly that: the core classes of WFC. In this package, you'll find not only classes that primarily support the framework, but also classes that support the Forms Designer and, more specifically, the Properties window. You'll notice a number of <DataType>Editor classes in the core package. The Properties window uses these classes to parse property settings that you enter. You can use these classes to parse data from text to a respective data type.

You might find yourself extending or implementing a number of the classes and interfaces defined in the package. Classes such as Component and Container are the base classes for WFC controls, and define some base behavior for controls. You might also want to extend the Event and EventHandler classes when you need to create an event or event handler for controls you're developing. Other than extending or implementing a class or interface in the core package, you won't typically have any real use for this package in your applications.

com.ms.wfc.data and com.ms.wfc.data.ui

The data and data.ui packages provide support and controls for accessing any type of database. The data package contains all the ActiveX Data Objects (ADO) classes for the Java data programming model. The classes in this package allow you to open and manipulate any type of database that's accessible from Open Database Connectivity (ODBC). You'll use the Connection, Command, and Recordset classes the most when accessing database information.

The data.ui package contains the DataSource, DataBinder, DataNavigator, DataList, DataCombo, and DataGrid controls, as well as any supporting classes for these controls.

com.ms.wfc.html

In addition to providing more than a framework for creating Windows applications, the WFC also provides classes for designing dynamic Web page content. The html package is this "framework within a framework." This relatively large package of classes contains all the Java classes you need to work with DHTML. Because many of the classes have related classes in other packages, the Microsoft developers prefixed each of the class names in the package with "Dh." The html package provides classes, such as DhComboBox and DhButton, for displaying intrinsic controls. Because these are DHTML controls, they don't extend from any of the same classes as the standard WFC controls. Instead, they extend other base classes such as DhButtonBase and DhElement.

The package also provides classes for working with tables, displaying images, and handling text to be displayed. For more detailed information on the DHTML classes in the html package, I recommend you consult the html package reference, as well as the procedural and conceptual documentation provided in the Visual J++ documentation.

com.ms.wfc.io

The io package provides everything you need to handle writing to, and reading from, file or memory. The io package's pivotal class is DataStream. Almost all stream classes, including File, extend DataStream. DataStream provides the base implementation of reading and writing data using streams. The io package also provides a number of other stream classes, such as File, MemoryStream, and BufferedStream. The most commonly used stream class is File. This class provides all you need to read from and write information to files. In addition, the File class provides methods that allow you to perform tasks, such as copying and searching for files and creating directories.

com.ms.wfc.ui

The largest package, comprising most of the more interesting classes, is the ui package. It contains classes responsible for almost every facet of an application's user interface, including the Form and Control classes. These are extremely important for applications, and define the basis for the application's user interface. The Form class represents a dialog box or window, and is extended for each dialog box or window an application uses. The Control class provides many of the base properties and methods that most controls will need to have defined.

With the exception of the data controls defined in the data.ui package, the ui package contains all other WFC controls. Here you'll find the Edit, Button, Label, and other intrinsic Windows controls. Other controls in the ui package include the TreeView, ListView, MonthView, and ImageList controls. You'll also find the Menu, MainMenu, and MenuItem classes defined here. These classes are used in combination to define the menus for a form. This package also provides all the common Windows dialog boxes, such as Open and Font.

The Graphics Device Interface (GDI) is a big part of applications that require drawing capabilities and image display. The Graphics class is the liaison between WFC and GDI, and provides a number of methods for drawing rectangles, circles, and polygons. You'll need the Graphics class, with support from the Bitmap and Image classes, to draw images onto a form. In addition, the ui package defines a number of classes to support the Graphics class. The Color, Font, Pen, and Brush classes all support the Graphics class, and are used in controls and in the Form class to define appearance.

Other common classes you'll find in the ui package include MessageBox, Help (used to display help in your application), AxControl (used to host ActiveX controls in your WFC applications), and Screen. If you're ever in doubt about where a class is, or where support for a specific user interface feature is, look at the ui package first.

com.ms.wfc.util

The last, and probably smallest, WFC package is util. Despite its size, this package provides some useful classes for your applications. To assist in sorting data, the util package includes the ArraySorter and StringSorter classes. These are handy to have when you want to quickly sort data from a file or non-indexed database. If you're looking for a solid list object to use in your projects, the util package also provides a List class that can accept any type of data. This can be useful when you want to perform list operations on a group of related objects.

The Debug class includes methods that allow you to print information to the output window, dump the contents of the call stack, and create assertions in your code. These methods can help you debug your application in the Visual J++ environment. Probably the most useful class in the package is the Util class. This class contains an extensive list of miscellaneous methods you can use to handle tricky situations. Some of the tasks you can perform with the methods in the Util class are capitalizing and lower-casing strings, comparing arrays, formatting strings, and parsing. If you're searching for an obscure feature, check out the Util class.

Wrapping Up Packages

As you can see, WFC packages are comprehensive and provide a solid architecture for building your applications, components, and dynamic Web pages. We'll examine a timeless example of a new language or framework, the "Hello World" application. In this case, though, we'll call it the "Hello WFC" application. We'll investigate the default code Visual J++ produces to display a window. We'll also add a control and some graphics code to display the infamous "Hello World" message in a way you won't often see.

Your First WFC Application: "Hello WFC"

Introductions to a new language or framework would be incomplete without the timeless classic "Hello World." To vary this time-honored tradition a little, we'll use the phrase "Hello WFC." We'll also display another string of text on the form in a different fashion. Figure 1 shows what the application looks like once it's completed.

Figure 1: The "Hello WFC" application at run time.

The goal of the following exercise is to give you a chance to see WFC in action with an easy-to-follow example. After we've created the example, I'll describe some of the code's more interesting features so you'll understand what WFC did for us, and what we had to add to make the application work.

Step 1: Creating the Project and Form

To start creating your first WFC application, start Visual J++. Once Visual J++ is displayed, you should see the New Project dialog box (see Figure 2). Click the Visual J++ Projects node in the tree view displayed, and select the Empty Project template from the list. Once you've selected the project template, enter a path where you want to store the project. To name the project, type HelloWFC in the Name text box. Then click Open to continue. The project will be created and displayed in Visual J++'s Project Explorer window.

Figure 2: The Visual J++ 6.0 New Project dialog box.

The project will be empty, so we'll need to add a form that will be displayed when we run the project. Choose Add Form from the Project menu. This will display the Add Item dialog box (see Figure 3). Select the Form item from the list. We'll use the default name of Form1.java for our form. Click Open to add the form to the project. The form that we added is a subclass of the com.ms.wfc.ui.Form class.

Figure 3: The Add Item dialog box.

Our form will need to display a caption in its title bar. Double-click the form in the Project Explorer window to select the form and display it in the Forms Designer. When the form is displayed, locate the text property in the Properties window and replace the text Form1, with Hello WFC. Now that we have a form in our project, our next step is to add a control to it for our first text display.

b>Step 2: Adding the First Text Display

We'll display two lines of text in our application. One will be displayed using graphics calls to draw a string of text on the form; the other will be displayed using a Label control. You can find the Label control in the WFC Controls section of the Toolbox (see Figure 4). To add this control to the form, double-click the Label control in the Toolbox. This will add the control to the middle of the form. Move the control to the top of the form, and size it to the width of the form.

Figure 4: The Visual J++ 6.0 IDE displaying the Toolbox with WFC Controls selected, the form we're working on, and the Properties window for the Label control.

To change the text of the Label control to the text we want to display, select the Label control (if it isn't already selected) and locate the text property in the Properties window. Double-click the text property to highlight all the text for the property and enter:

Hello World. This is a flexible label.

To make this statement correct, we'll need to change the anchor property of the Label control. This modification will allow the control to be resized and its text repositioned based on the sizing of the form. Select the Label control's anchor property, then click the drop-down button next to the value. The property editor shown in Figure 5 will be displayed.

Figure 5: The anchor property editor.

By default, the left and top rectangles will be selected, i.e. the control is anchored to the top and left edges of the control's container, and the form does nothing to resize the control. We want our Label control to be anchored to the top only so the text will always be displayed in the center of the form. To make the control anchor to the top only, deselect the left rectangle by clicking it; only the top rectangle should be selected.

The Label's textAlign property determines where the text is displayed within the Label control: Left, Right, or Center. In our case, we want it displayed in the center of the Label, so set the property accordingly. Our Label control is now configured correctly; Figure 6 shows what it should look like in the Forms Designer with all the properties set.

Figure 6: The example form at design time with all properties set.

Step 3: Adding the Second Text Display

As I mentioned in the previous step, the second text display uses graphics work to "paint" the text on the form. This is the more traditional "Hello World" approach. To add this display to our form, we'll need to add an event handler for the form's paint event. The paint event occurs every time a form needs to be repainted. A paint event handler is a preferred place to draw, because it allows all graphical displays to be updated when the form goes out of focus, or is covered by another window or application.

To add an event handler for the paint event, select the form and then click the "lightning" icon in the Properties window. This displays the Event View mode of the Properties window. Event View shows all the events for the currently selected control or form. It allows you to specify an event handler from existing event handlers in the form's code, or to supply a new one. Select the paint event in the list. In the box to the right of the event name, enter PaintForm as the event handler, and press R. The code editor will be displayed with a new event handler method created with the name you specified (see Figure 7). The paint event is now "wired" to this event handler, i.e. the event handler will be called whenever the form's paint event occurs.

Figure 7: Modifying the paint event handler.

To draw on a form, you must use the Windows Graphics Device Interface (GDI). WFC provides GDI services through the Graphics class. This class provides a number of methods for drawing objects and text to a control or form.

The paint event handler we created, PaintForm, contains a Graphics object for the form as one of its parameters that we can use to draw directly to the form. To add our second text display, enter the following statement to the PaintForm event handler:

e.graphics.drawString(
  "Hello World. This is a real Java application.", 10, 50);

This line of code uses the PaintEvent object, e, passed as a parameter, and accesses its Graphics object, graphics, and calls its drawString method. The drawString method takes three parameters: a string to draw to the form, the number of pixels from the left of the form to draw the text, and the number of pixels from the top of the form to draw the text. In this case, we'll be displaying the text 10 pixels from the left and 50 pixels from the top. This will place the text display below the Label control that we added previously. That's all there is to displaying simple text on the form.

It's the Code You Don't Write ...

Although this example is simple to create, Visual J++ did a lot of the grunt work for us. Let's take a look at the complete source code for the example and explore all the support code the Forms Designer added to display the form and its controls (see Figure 8).

import com.ms.wfc.app.*;
import com.ms.wfc.core.*;
import com.ms.wfc.ui.*;

/**
 * This class can take a variable number of parameters on
 * the command line. Program execution begins with the 
 * main() method. The class constructor is not invoked 
 * unless an object of type 'Form1' created in the main()
 * method.
 */
public class Form1 extends Form {

  public Form1() {

    // Required for Visual J++ Form Designer support.
    initForm();
  
    // TODO: Add any constructor code after initForm call.
  }

  /**
  * Form1 overrides dispose so it can clean up the
  * component list.
  */
  public void dispose() {
    super.dispose();
    components.dispose();
  }

  private void PaintForm(Object source, PaintEvent e) {

    e.graphics.drawString("Hello World, " +
      "this is a real Java application!", 10, 50);
  }

  /**
  * NOTE: The following code is required by the Visual J++
  * Form Designer. It can be modified using the form 
  * editor. Do not modify it using the code editor.
  */
  Container components = new Container();
  Label label1 = new Label();

  private void initForm() {

    this.setText("Hello WFC");
    this.setAutoScaleBaseSize(13);
    this.setClientSize(new Point(292, 273));
    this.addOnPaint(new PaintEventHandler(this.PaintForm));

    label1.setAnchor(ControlAnchor.TOP);
    label1.setLocation(new Point(8, 8));
    label1.setSize(new Point(280, 25));
    label1.setTabIndex(0);
    label1.setTabStop(false);
    label1.setText(
      "Hello World... this is a flexible label in WFC!");
    label1.setTextAlign(HorizontalAlignment.CENTER);

    this.setNewControls(new Control[] {
      label1});
  }

  /**
  * The main entry point for the application. 
  *
  * @param args Array of parameters passed to the 
  * application via the command line.
  */
  public static void main(String args[]) {
    Application.run(new Form1());
  }
}

Figure 8: The source of our "Hello World" example.

Everything starts with the main method, just as with C and C++. In main there's a single call to the run method of the Application class, with an instance of the form as its only parameter. This method call starts the application's thread, creates a message pump for distributing Windows messages, and displays the form. This line of code will stay active until the application has terminated.

Displaying the form causes the form's constructor to be called. The constructor for the form contains a lone method call to the initForm method. The initForm method sets the properties of the form and its controls. The controls are defined as members of the class and are accessible only from within the form class' methods. The form also defines a dispose method that's used when you want to close the form without terminating the application.

More impressive than the code we just explored is the code that manages the displayed windows and handles message distribution behind the scenes. This feature is one of WFC's greatest strengths: It performs these complex programming tasks for you, allowing you to concentrate on developing the application features specific to your solution.

To see our application run, press 5 or choose Run from the Debug menu. This will compile, build, and package our application in an .EXE file, and run the project. You should see a form displayed similar to the one shown in Figure 1. Resize the form, and notice that the top text display remains centered in the form as the form is resized.

Conclusion

Congratulations! You've created your first application using the WFC and Visual J++ 6.0. Although the example is simple, you should now feel comfortable using the Forms Designer and the general features of Visual J++ to build other applications.

I've introduced you to WFC, the framework of classes that allows you to create powerful Windows applications using Java. We reviewed the different packages and the important classes of each package in the framework. And finally, we created the venerable "Hello World" application to show you the basics of using the Visual J++ Forms Designer and WFC.

This article was adapted from Microsoft Visual J++ 6.0 Developer's Workshop by Shannon Dunn [ISBN: 1-57231-925-9]. Copyright 1998. Reproduced by permission of Microsoft Press, http://mspress.microsoft.com. All rights reserved.

Shannon Dunn is a Programmer/Writer for the Visual J++ User Education team. Before joining Microsoft, Shannon worked as a software developer for Lockheed Martin, as well as a consultant for a variety of small to large businesses. Shannon has worked with programming languages ranging from Clipper and Basic to C++ and Java.

Download source code for this article here.