The Java Abstract Window Toolkit

Anil examines the Java Abstract Window Toolkit (AWT), a portable GUI class library for developing applications and applets. He then builds a text-editor application for Windows 95 and Solaris, along with an applet for Windows 95.


September 01, 1996
URL:http://www.drdobbs.com/jvm/the-java-abstract-window-toolkit/184409956

September 1996: Hemraji

The Java Abstract Window Toolkit

A portable GUI class library for applications and applets

Anil Hemrajani

Anil currently provides software engineering and training consulting services to a Fortune 500 corporation in McLean, VA. He can be contacted at [email protected] or via http://www.patriot.net/users/anil/.


One of the most important packages (class libraries) provided in the Java API is the Abstract Window Toolkit (AWT). AWT includes a complete set of classes for developing portable GUI applications in Java. It provides classes for basic GUI controls, containers, event handling, component placement, fonts, colors, drawing, images, sounds, and more. The main benefits of AWT over other GUI class libraries is that Java applications can run on all supported platforms (without recompiling or relinking), and Java applets can be accessed from anywhere by connecting to the Internet via a Java-compatible browser.

Java programs can be written as applications, applets, or both. Each is created by compiling Java source code into bytecodes using the Java compiler (javac). Figure 1 shows a sample text-editor application on Windows 95, and Figure 2 shows an applet version, also on Windows 95. Both are generated by the same Java program- TextEdit.java (available electronically).

Applets are invoked by a Java-compatible Web browser or the appletviewer utility (available with the Java Development Kit). Both require an HTML file with an <APPLET> tag that points to a Java class file. This file must contain a class that subclasses from the Applet class. The Applet class contains the methods init(), start(), stop(), and destroy(), which are invoked when an applet is initialized, started, stopped, and destroyed, respectively. These methods can be overridden by the subclass.

Java applications are invoked via the Java interpreter by providing it the name of a class. The interpreter searches for the class file (classname.class) in the directories indicated in the CLASSPATH environment variable or the current directory if CLASSPATH has not been set. The name of the class in this file must match the name passed to the interpreter. Additionally, it must contain a main() method with the signature public static void main(String args[]).

The basic steps for developing a Java application or applet include:

Basic GUI Components

The GUI components Java currently supports include Buttons, Canvases, Radio Buttons, Checkboxes, Choices, Dialogs, FileDialogs, Frames, Labels, Lists, Menus, Panels, ScrollBars, TextAreas, and TextFields. TextEdit.java (which generated Figures 1 and 2) uses most of these components. Components are created by using the new keyword. Most components can be created with default settings by passing in values; see Example 1 (excerpted from TextEdit.java).

All GUI components inherit from the Component class, which provides several methods for operations on components. These include checking the bounds of a component, getting/setting a component's font, enabling/disabling the component, getting/setting colors, requesting/moving focus, hiding/showing the component, resizing the component, moving the component, and more.

Containers

AWT Containers are GUI objects that group components in a specified area of a window. AWT provides two major types of containers-Windows and Panels-that are implemented by the Window and Panel classes, respectively. Both classes are subclasses of the Container class, which inherits from the Component class. Additional container classes include Frame, Dialog, and Applet. Frame and Dialog subclass from the Window class, whereas the Applet class subclasses from the Panel class.

Containers used in TextEdit.java include a Frame and a Panel. Figure 3 illustrates how this application uses these containers. Notice how panels can not only contain other components, but also other panels. For instance, topPanel.add("North", urlPanel); (extracted from TextEdit.java) adds a panel (containing choice lists and checkboxes) inside another panel. The line add("North", topPanel); adds another Panel object to the applet, which itself is a subclass of Panel.

Since applets cannot serve as an application's main Frame window, they require a browser or Java application to provide this frame window for them. TextEdit.java creates a frame window when it is run as an application, then creates an instance of the TextEdit class (a subclass of the Applet class) and calls its init() method (te.init()) just as a browser would.

Layout Managers

Layout Managers arrange components inside containers and automatically reposition (and sometimes resize) them every time the container changes its appearance. This simplifies the task of figuring out absolute coordinates for components. Additionally, this ensures that the components will have the best possible appearance in browsers and different monitor resolutions.

AWT currently provides five predefined Layout Managers:

The alternatives to using the predefined layout managers include designing a custom layout manager [Editor's Note: See "How Do I Create a Layout Manager,'' by Cliff Berg, on page 101 of this issue] or doing without them using absolute positioning. Custom layout managers can be created by providing an implementation for the LayoutManager interface (abstract class). Absolute positioning of components is not recommended, especially for applets that can be viewed through different browsers.

TextEdit.java uses BorderLayout, FlowLayout, GridLayout, and GridBagLayout to lay out its various panels (see Figure 3). For example, the panel containing the font controls uses FlowLayout to place its controls from left to right with left justification; see Example 2(a). The panel containing the push buttons uses the GridLayout with settings of one row and seven columns (corresponding to the seven buttons). GridLayout automatically resizes all buttons in this panel to equal sizes; see Example 2(b). The applet panel uses a BorderLayout to place its components in three of the five areas available with this layout; see Example 2(c).

Event Handling

Once an application's screen has been designed, you make it operational by reacting to events generated by user input. All events are handled in a component's subclass by overriding the handleEvent method. Alternatively, event-specific methods can be implemented in the subclass such as action, keyDown, mouseEnter, mouseExit, mouseMove, mouseUp, mouseDown, and mouseDrag.

Events in AWT are passed up in a component's hierarchy; in other words, a subclass gets a crack at the event before its parent class does. If the event is handled by a class, it should return a value of true to indicate that the event has been handled, or false if the event was not handled. A component's subclass can also invoke its parent event-handler method directly (return super.handleEvent(evt);).

The TextEdit class in TextEdit.java uses handleEvent to react to all events generated by controls inside the applet panel; see Example 3(a). Additionally, TextEdit handles all events generated by the TextFrame class. Since TextFrame is designed primarily to provide a frame for the applet, it forwards all its events to the handleEvent method in TextEdit; see Example 3(b).

More on the Java UI API

Java also provides an API for working with fonts, colors, drawing, images, sounds, and text-based user interfaces. The Font class can be used for setting the font of a GUI component: Create an instance of the Font class with the font name, style (bold, italic, normal), and size, then use the component's setFont() method; see Example 4(a).

The Color class provides some predefined static colors (black, blue, cyan, darkGray, gray, green, lightGray, magenta,orange, pink, red, white, and yellow) for setting the background or foreground of a component. Additional colors can be generated using RGB (0-255) or HSB (0.0-1.0) values. To set the background/foreground of a component, use the setBackground/setForeground methods provided in the Component class. To set the default color for a drawing object, use that object's setColor method, as in Example 4(b).

AWT provides classes and methods for drawing lines, oval shapes, polygons, rectangles, and rounded rectangles. Additionally, some of these drawing objects can have a 3-D look, a highlighted look, or both; see Example 4(c).

Java currently provides a limited API for multimedia processing. Methods are provided for reading, displaying, and manipulating images in GIF and JPEG formats. Also, simple animation can be performed by displaying multiple image files or drawing objects in the same or different areas of a window. This technique is analogous to playing several frames from a reel of film to produce a picture in motion. Java also provides sound support in applets via methods such as play(). As of this article, only Sun's .au audio files (8-bit -law, 8000Hz, one channel) are supported; see Example 4(d).

Text-based user interfaces generally involve the use of standard-output, standard-error, and standard-input devices. Java provides access to these devices via static variables in its System class (System.out, System.err, and System.in). For example, a sample message can be displayed to the standard-output device with System.out.println("Hello world!");.

Compiling and Running TextEdit.java

You can compile TextEdit.java from the command line by entering javac TextEdit.java. Once a Java bytecode file (.class file) has been created, it can be copied to any supported platform and accessed without having to recompile or relink. To run a Java application (such as TextEdit.java), type java TextEdit. To run the applet version, put the HTML code <applet code=TextEdit.class width=600 height= 400></applet> in a file (sample.html, for example) and pull it up in a Java-compatible browser, or use the appletviewer utility.

Future of Java

Java's future is promising. It is robust, object-oriented, and portable (source and bytecode). Java comes bundled with a suite of classes for GUI, multithreading, networking, file I/O, and the like. To add to this, APIs for database access (Java Database Connectivity), more robust multimedia processing, and remote object access are in the works. Finally, several powerful Java IDEs are already on the market.

Example 1: Creating GUI Components with default settings.

cs = new Choice();
cbb = new Checkbox("Bold");
buttonPanel = new Panel();
buttonPanel.add(new Button(MI_NEW));
ta = new TextArea(30, 80);
Menu fm  = new Menu("File");
fm.add(new MenuItem(TextEdit.MI_SAVE));
tURL = new TextField(80);

Example 2: (a) Using FlowLayout to place controls from left to right with left justification; (b) GridLayout automatically resizes all buttons to equal sizes; (c) using BorderLayout to place components.

(a)  fontPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

(b)  buttonPanel.setLayout(new GridLayout(1, 7));

(c)     setLayout(new BorderLayout(1, 2));
     add("North",  topPanel);
     add("Center", ta);
     add("South",  statusBar);

Example 3: (a) Using handleEvent to react to events generated by the controls; (b) forwarding events to the handleEvent method.

(a)     public boolean handleEvent(Event evt)
     {
       if (evt.id == Event.WINDOW_DESTROY)
             terminate(0);
       else
       if (evt.id == Event.ACTION_EVENT)
       ...

(b)     if (te != null)
         return te.handleEvent(evt);

Example 4: (a) Using the setFont() method; (b) using setColor method; (c) generating a 3-D look; (d) using an .au audio file.

(a)     cbb.setFont(new Font(cbb.getFont().getName(),
            Font.BOLD, cbb.getFont().getSize()));

(b)     ta.setBackground(Color.blue);
     g.setColor(getBackground());

(c)     g.f ill3DRect(0, 0, size().width, 2, false);

(d)     play(getCodeBase(), "hello.au");

Figure 1: Text-editor application on Windows 95.

Figure 2: Text-editor applet on Windows 95.

Figure 3: Text-editor application/applet.

Terms of Service | Privacy Statement | Copyright © 2024 UBM Tech, All rights reserved.