12 Other Java Topics

This chapter explores a variety of miscellaneous topics a Java programmer needs to understand. Included are a brief overview of graphical user interface development and a discussion of properties files and Java utilities.

GRAPHICAL USER INTERFACE DEVELOPMENT

Graphical user interface (GUI) development is a big topic, but I will touch on it only briefly. The basic GUI functionality for Java is contained in the Abstract Window Toolkit (AWT), released with the earliest versions of Java. AWT is a standard interface that Java applications (or applets) can use to create and interact with GUIs. The AWT interfaces talk directly to the underlying graphical operating system interfaces. Since AWT is ported to every Java environment, any Java application that uses AWT can display GUIs in any Java environment, although the look and feel of the application may vary.

So far it sounds good, but because of several problems, AWT has been regarded by many as the weakest part of the original Java environment. The primary problem is that AWT was designed to the lowest common denominator of graphical environments. Important capabilities (e.g., tabbed views, spinners, complex layouts) required by graphical applications are not available in AWT.

Sun improved on AWT with the newer Java Foundation Classes (JFC), released as a patch to the Java Development Kit (JDK) 1.1. These APIs are grouped in a package named for the code name for the internal development project at Sun (Swing). The Swing package is meant to replace the AWT. Most applications that have Java UI’s use Swing instead of AWT.

Applications that use Swing have access to more control over the user interface. For example, an application can now manage borders around graphical components, and components do not all need to be rectangular. Swing brings with it a more robust event model and widgets not available in AWT, such as table and tree control. Swing is not dependant on the native components and, therefore, the look and feel of Swing applications are independent of the platform.

For development of new Java applications, Swing and JFC are clearly the best choices available. Yet the learning curve is relatively steep if you have no experience in GUI development. Following are some of the basic concepts and knowledge you need to get started.

The javax.swing and javax.swing.event packages contain most of the classes you will need, but you will also use java.awt and java.awt.event packages extensively because Swing is built on or uses AWT.

The JFrame class is used to create the main frame window of an application. You can add a menu bar to it using JMenuBar or add a tool bar using JToolBar. You can populate the frame with buttons, combo boxes, text fields, and other GUI elements. A layout manager is generally used to control the appearance. Various layout managers are defined in java.awt.

Figure 12.1 describes how these various components combine to create a Swing user interface.

Image

FIGURE 12.1
Swing user interface.

The JFC is an event-driven model. Once you create the main window and populate it with GUI elements, the program operates by reacting to the various events for which you have registered interest. The way you show interest is to implement listener interfaces and attach the listener to GUI elements. For example, you might code an ActionListener and attach it to a button. When the button is clicked, the actionPerformed() method in your listener is called with information about the event. To understand how to do all this, you should go to the Java Sun Web site and find the tutorials on constructing GUIs.

PROPERTIES FILES

In many environments where COBOL is used, important runtime information exists outside the program. Most of the time, the actual file names that are the target of execution and other parameters to control execution are defined in job control language and passed to COBOL by the operating system. This allows the same program to be used with different files, such as test and production files, or with various execution options, without having to recompile the program.

One alternative for a Java program is to use command-line arguments. This can become quite cumbersome if the number of arguments becomes extensive. Not only do you have difficulty editing the command line, you also have the problem of parsing and interpreting the arguments on the program side.

A better alternative is a properties file. In a Java environment, a properties file is often used to supply this runtime information. A properties file is simply a text file that consists of name-value pairs separated by the equals (=) operator. It is much like a Hashtable written in text and, in fact, the Properties class that you use to read and write the properties file extends Hashtable. Here are the contents of a simple properties file:

# my property file containing runtime file names
inputfile=testin.fil
outputfile=testout.fil

The file has two properties: inputfile and outputfile. The line with the # is simply a comment. To load the properties, you write code like this:

Properties props = new Properties();
props.load(new FileInputStream("myproperties.prop"));

Once the properties are loaded, you can access them like this:

// returns "testin.fil"
String inputFilename = props.getProperty("inputfile");
// returns "testout.fil"
String outputtFilename = props.getProperty("outputfile");

Using this technique, the program could go into production and use production files simply by editing the properties file.

JAVA UTILITIES

Java provides a number of utilities to assist in your development processes. I’ll cover a few here.

JAR UTILITY

The Java Archive utility is used for bundling classes, images, and other resources that compose a Java project. The Java Archive utility was discussed in Chapter 2 from the standpoint of a user of a jar file. Here I’m going to discuss how to create one.

Internally, a jar file is much like a zip file. It contains entries for files and directories, and it contains the compressed content of the files. Packaging applications in jar files simplifies distribution and reduces the network load when classes are passed over the Internet or through a network.

There are two primary differences between a jar file and a zip file: A jar file can be signed with a digital signature to provide security and authentication, and a jar file contains a manifest that carries information about the content of the file and how it is to be handled.

The jar utility program comes with the SDK. It is the tool used to create and manage jar files. Like the rest of the SDK, it must be run from a DOS command window. The simplest format for using the jar program is as follows:

jar               -cf          ajarfile            *.class

This command copies all the classes in the current directory to the jar file named ajarfile. If any subdirectories exist in the current directory, that directory is processed recursively (that is, any class files in a subdirectory are included in the jar file, along with the subdirectory name). In addition, a manifest is created and included in the jar file. It describes the contents of the jar file.

The following command updates an existing jar file with all the class files in the current directory:

jar -uf      ajarfile   *.class

The next command lists the contents of the jar file ajarfile:

jar -tf      ajarfile

or with more details:

jar-tvf      ajarfile

After you’ve created a jar file, you can use it by treating it like a subdirectory in your CLASSPATH directory. The CLASSPATH variable lists directories from which any of these three class container types may exit:

  • The directory location of actual class files.

  • The initial directory for a package (that is, further subdirectories that may contain class files).

  • The directory location where a jar file exists (which contains class files, perhaps in subdirectories inside the jar file).

For example, the classes in a jar file named ajarfile.jar can be included in the CLASSPATH option when running a Java program, as follows:

java –cp c:java4cobolm,c:java4cobolajarfile HelloWorld

In the case of an applet, a jar file is identified with the archive= parameter of the applet tag, as follows:

<applet
CODEBASE = codebaseURL
code=HelloWorld
archive="ajarfile"
width=200
height=200>
</applet>

As with regular class files, an applet’s jar filename is relative to the CODEBASE directory.

JAVADOC UTILITY

Javadoc is a utility that allows the programmer to document the code in the source and then easily generate the documentation in a readable format. Javadoc goes well beyond the comment feature in COBOL, although it also can serve the same purpose. The difference with Javadoc is that the utility has the ability to process specially formatted comments in Java source code and produce external documentation, including a complete class structure showing inheritance and other relationships between the classes.

Javadoc is a utility provided in the standard Java SDK that parses source code and, by default, automatically generates HTML output that documents the Java code. The executable code for Javadoc is found in the bin directory in which the SDK is installed. In reality, the Javadoc executable is a starter application that creates a Java VM and invokes a doclet to do the work of generating the output documentation.

You run Javadoc by executing the program at the command line and passing a directory or list of directories to the utility. This action produces HTML pages that link together to document and index the classes found in the directories. It does not automatically copy the various images referenced in the HTML to the proper location, so you will need to do that manually.

Standard Javadoc comments start with /** and end with */. Note the double asterisks at the start that distinguish the Javadoc comment from an ordinary multiline Java comment. Comments can be plain text or can include HTML code. Here’s how a comment might look embedded in Java code:

/**  The purpose of this comment is to help in the automatic generation of
documents. A programmer can insert (well-written) descriptions of classes
and members. These will be extracted and placed into a published document
in HTML format.
*/

Javadoc comments are recognized when placed immediately before class, interface, constructor, method, or field declarations. Documentation comments placed in the body of a method, however useful they may be, are ignored.

Even if you do not include any comments, Javadoc will produce a listing of classes and methods. By default, it lists public and protected methods and members and excludes the private ones. This can be changed with command-line options.

Javadoc comments can also be marked with special markup tags, which provide for additional formatting and cross-reference control for the generated document. The following markup tags are used to document the interface of public methods:

@param
@return
@throws

The following markup tags are used to document packages or classes that contain public methods:

@version

It is a good idea to place Javadoc comments (with at least these tags) at the beginning of your classes and methods. Java programmers will expect to see them, and several useful tools are available that will process this type of program comment specification. The output of the Javadoc tool included with the SDK is especially nice looking and useful.

The advantage of in-program documentation is that, since the code and the documentation are in the same file, the chances that the documentation will match the code are improved. In addition, the public class interface definitions will always be accurate because the tools automatically generate this information from the Java source code.

One disadvantage is that you still must rely on the programmer to type in the comments and specifications. There is no guarantee that the comments actually do match the code. Another problem is that Java editing environments are not WYSIWYG graphical editors. Generating nice-looking end-user documentation with Javadoc and HTML markups takes a lot of work, even if the end users are developers and so, presumably, have lower expectations.

Most people find it useful to include comments before method definitions and for the class as a whole. The comments may contain special tags that Javadoc understands and can use to customize the output. These tags follow the comments.

The following shows a lightly commented source code fragment:

/**
* This method returns a string describing DocTest.
** @return a string description of DocTest
*/

public String getDescription()
{
...
}

When Javadoc creates the documentation for the class, it includes the description “This method returns a string describing DocTest.” as the description for the method getDescription() and adds a return label in bold with the description “a string description of DocTest” after it.

The leading asterisk characters on each line are not necessary. If you omit the leading asterisk on a line, however, all leading white space is removed. Without leading asterisks, the indents are lost in the generated documents. Here are some common tags and their uses:

The default doclet (called standard) by default produces HTML documentation. Most people do not go beyond usage of the standard doclet, but it is possible to override the standard doclet with a custom doclet. In fact, several other doclets have been written. Sun has a list of experimental and third-party doclets at its Web site.

EXERCISES

Image

Even though you haven’t explored in depth how to create a GUI, you are going to walk through a simple example. To start, copy the file SimpleFrame.java from the Chapter12 subdirectory in the Exercises directory on the CD-ROM to your java4cobol directory.

  1. Compile the SimpleFrame class. SimpleFrame takes care of the work of creating a frame window and various listeners so that the window will respond properly to messages. It also provides some utility methods for creating buttons and menu items. You won’t be using a menu in this exercise, but you will be creating a button.

  2. Create a new Java file called MyFrame.java. Add the following import statements to the file.

    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;

  3. Write the code to create the MyFrame class. Notice that MyFrame must extend SimpleFrame for this exercise to compile correctly.

    public class MyFrame extends SimpleFrame
    {
    }

  4. Add a constructor. This constructor invokes the constructor in Simple-Frame. The text “My Frame” will become the title on the window.

    public MyFrame()
    {
        super("My Frame");
    }

  5. Override the buildGUI() method in SimpleFrame. This method is automatically invoked in the SimpleFrame constructor.

    public void buildGUI()
    {
    // Call the createButton method in SimpleFrame.
        JButton button = createButton("Click me", "Click me");
    // Tell the frame how to lay out components you add.
        getContentPane().setLayout(new FlowLayout());
    // Add the button to the frame.
        getContentPane().add(button);
    }

  6. Override the actionPerformed() method in SimpleFrame. SimpleFrame and, by extension, MyFrame are listeners for action events. The create-Button() method added the ActionListener in the button creation process, so any action taken on the button (that is, clicking it) automatically calls this method. If you had multiple buttons, the action command would allow you to distinguish which button had been clicked.

    public void actionPerformed(ActionEvent e)
    {
    // Get the action command.
        String command = e.getActionCommand();
    // Pop up a message when the button is clicked.
        if (command.equals("Click me"))
            informationMessage("I've been clicked", "Click Message");
    }

  7. Finally, code a main method that can be executed.

    static public void main(String [] args)
    {
        new MyFrame();
    }

  8. Compile MyFrame and execute it. A window entitled “My Frame” should pop up with a single button centered in the upper part of the window. When you click the button, the message “I’ve been clicked” should appear.

  9. The file SimpleFrame.java has had Javadoc comments added to it. As a final task, go to the java4cobol directory and key in the following command:

    →   javadoc SimpleFrame.java

    If your system paths are set up correctly, the Javadoc should run and create HTML that documents the SimpleFrame class. With your browser, open the index.html file that was created in the java4cobol directory and examine the output.

REVIEWING THE EXERCISES

In this exercise, you created a simple window by extending a class called Simple-Frame. In order to understand more fully what is required to develop a fully functional GUI application, look at the code in SimpleFrame and use it as a basis for building more complex applications.

You also generated the Javadoc that was already supplied in the SimpleFrame source. You might want to add Javadoc comments to your MyFrame source and generate the Javadoc for that class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset