Skip to main content.

Web Based Programming Tutorials

Homepage | Forum - Join the forum to discuss anything related to programming! | Programming Resources

JAVA Developer's Guide

Chapter 15 -- Window Programming with the java.awt Package

Chapter 15

Window Programming with the java.awt Package


CONTENTS




This chapter introduces the classes of the java.awt package. These classes provide the foundation for Java window programming. You'll learn how the java.awt package is organized and cover each of the classes that it contains. You'll also cover the java.awt.image and java.awt.peer packages. This chapter, unlike others in this part, does not provide programming examples. Part IV, "Window Programming," provides a detailed tutorial of Java window programming, including numerous programming examples.

Window Programming Classes

The Java Abstract Windowing Toolkit (AWT) provides numerous classes that support window program development. These classes are used to create and organize windows, implement GUI components, handle events, draw text and graphics, perform image processing, and obtain access to the native Windows implementation.

This chapter covers these classes in sections consisting of logically related classes. The "Components and Containers" section introduces the GUI components supported by the AWT and the Windows classes that contain these components. The "Constructing Menus" section describes the classes that are used to implement menu bars and pull-down menus. The "Organizing Windows" section describes the classes that are used to organize windows and lay out the components they contain. The "Handling Events" section introduces the Event class and describes the process of Java event handling. The "Working with Images" section introduces the Image class and the image-processing classes of the java.awt.image class. The "Geometrical Objects" section covers the Java classes that are used to represent points, rectangles, polygons, and dimensions. The "Using Fonts" section introduces the Font and FontMetrics classes and shows how to use these classes to control the display of text. The "Using the Toolkit" section describes the interface between the platform-independent AWT classes and their native platform-dependent implementations.

Components and Containers

The Component class is the superclass of the set of AWT classes that implement graphical user interface controls. These components include windows, dialog boxes, buttons, labels, text fields, and other common GUI components. The Component class provides a common set of methods that are used by all these subclasses. These methods include methods for handling events and working with images, fonts, and colors. More than 70 methods are implemented by this class. It is a good idea to browse the API pages of the Component class to get a feel for the kinds of methods that are available. You don't have to worry about learning them now. The important methods are covered in Part IV.

Although Component contains many GUI-related subclasses, its Container subclass is the class used to define Windows objects that contain other objects. As such, it is used to define classes for working with application windows, dialog boxes, panels, and applets. The Container class and subclasses are covered in the next section. The classes for GUI controls are covered in later portions of that section.

The Container Class

The Container class is a subclass of the Component class that is used to define components that have the capability to contain other components. It provides methods for adding, retrieving, displaying, counting, and removing the components that it contains. It provides the deliverEvent() method for forwarding events to its components. The Container class also provides methods for working with layouts. The layout classes control the layout of components within a container.

The Container class has two major subclasses: Window and Panel. Window provides a common superclass for application main windows (Frame objects) and Dialog windows. The Panel class is a generic container that can be displayed within a window. It is subclassed by the java.applet.Applet class as the base class for all Java applets.

The Window Class

The Window class provides an encapsulation of a generic Window object. It is subclassed by Frame and Dialog to provide the capabilities needed to support application main windows and dialog boxes.

The Window class contains a single constructor that creates a window that has a frame window as its parent. The parent frame window is necessary because only objects of the Frame class or its subclasses contain the functionality needed to support the implementation of an independent application window.

The Window class implements important methods that are used by its Frame and Dialog subclasses. The pack() method is used to arrange the components contained in the window according to the window layout style. Layout classes are covered later in this chapter. The show() method is used to display a window. Windows are hidden (invisible), by default, and are displayed only as a result of invoking their show() method. The toFront() and toBack() methods are used to position windows relative to their frame windows. The dispose() method is used to release the resources associated with a window and delete the Window object. The getWarningString() method is used to retrieve the warning message associated with untrusted windows. Warning messages are associated with windows that are created by applets. The other Window methods are used to support peer operations. AWT peers are discussed later in this chapter in the "Using the Toolkit" section.

A Window object does not have a border or a menu bar when it is created. In this state it may be used to implement a pop-up window. The default layout for a Window object is BorderLayout.

Frame

The Frame class is used to provide the main window of an application. It is a subclass of Window that supports the capabilities to specify the icon, cursor, menu bar, and title. Because it implements the MenuContainer interface, it is capable of working with MenuBar objects.

The Frame class defines 14 constants that are used to specify different types of cursors to be used within the frame. Consult the Frame class API page for a description of these constants.

Frame provides two constructors: a default parameterless constructor that creates an untitled frame window and a constructor that accepts a string argument to be used as the frame window's title. The second constructor is typically used.

Frame extends the set of access methods that it inherits from Window by adding methods to get and set the window title, icon image, cursor, and menu bar. Methods for removing the menu bar and specifying whether the window is resizable are also provided.

Dialog

The Dialog class is a subclass of the Window class that is used to implement dialog box windows. A dialog box is a window that takes input from the user. The Dialog class allows dialog boxes that are modal to be constructed. Modal dialog boxes must be closed before control returns to the window that launched them. The Dialog class also provides the capability to construct non-modal dialog boxes. Non-modal dialog boxes do not need to be closed before other program windows can be accessed.

The Dialog class provides two constructors. Both constructors require the Window object containing the dialog box, as well as the modal flag, to be specified. The second constructor allows the title of the dialog box to be specified.

The Dialog class provides only a handful of access methods. These methods are used to get and set its title, determine whether it is modal, and get and set the dialog box's resizable properties.

FileDialog

The FileDialog class is used to construct dialog boxes that support the selection of files for input and output operations. It is a subset of the Dialog class and provides two constructors. The first constructor identifies the Frame window that contains the dialog box and the title to be used at the top of the dialog box. The second constructor adds a mode parameter that can be set to the LOAD or SAVE constants defined by FileDialog.

FileDialog provides methods that are used to access the directory and filename of the user-selected file and to specify an object that implements the FileNameFilter interface.

The Panel Class

The Panel class is a subclass of the Container class that is used to organize GUI components within other container objects. It provides a single constructor that takes no parameters. The methods used with Panel objects are usually inherited from the Component and Container classes. The Applet class of the java.applet package is a subclass of the Panel class. The default layout for a Panel object is FlowLayout.

The Label Class

The Label class is used to display read-only text labels within a window or other GUI container. It has three constructors. The first constructor takes no parameters and is used to construct a blank label. The second constructor takes a String object as its parameter that is used to specify the label's text. The third constructor has an alignment parameter in addition to the text string. This parameter specifies how the label should be aligned within its container. The Label class defines the LEFT, CENTER, and RIGHT constants for use as alignment values.

The Label class provides methods to get and set the displayed label and its alignment value.

The Button Class

The Button class implements a clickable button GUI control. The button is capable of displaying a text label. Two Button constructors are provided. The first constructor takes no parameters and creates a button with a blank label. The second constructor accepts a String object that is displayed as the button's label. The Button class provides methods for getting and setting its label.

The Checkbox Class

The Checkbox class is used to implement checkbox and radio button GUI controls. The checkbox or radio button is associated with a label. If a Checkbox object is not associated with a CheckboxGroup object, it is implemented as a traditional checkbox. If a Checkbox object is associated with a CheckboxGroup object, it is implemented as a radio button.

The Checkbox class provides three constructors. The first constructor takes no parameters and implements a blank checkbox. The second constructor takes a String parameter that is used as the title of the checkbox. The third constructor allows a CheckboxGroup object and the initial state of the radio button to be specified in addition to its label.

The Checkbox class provides methods for getting and setting the label and state of the checkbox and its CheckboxGroup object, if any. The state of the checkbox is boolean.

CheckboxGroup

The CheckboxGroup class is used with the Checkbox class to implement radio buttons. All Checkbox objects that are associated with a CheckboxGroup object are treated as a single set of radio buttons. Only one button in the group may be set or on at a given point in time. The CheckboxGroup provides a single, parameterless constructor. It also provides methods for getting and setting the Checkbox object.

The Choice Class

The Choice class is used to implement pull-down lists that can be placed in the main area of a window. These lists are known as option menus or a pop-up menus of choices and allow the user to select a single menu value. The Choice class provides a single, parameterless constructor. It also provides access methods that are used to add items to the list, count the number of items contained in the list, select a list item, and determine which list item is selected.

The List Class

The List class implements single- and multiple-selection list GUI controls. The lists provided by the List class are more sophisticated than those provided by the Choice class: The List class provides the capability to specify the size of the scrollable window in which the list items are displayed and to select multiple items from the list. The List class has two constructors. The first one takes no parameters and constructs a generic List object. The second one allows the number of rows of the visible window to be specified and whether or not multiple selections are allowed.

The List class provides several access methods that are used to add, delete, and replace list items, count the number of items in the list, determine which items are selected, and select items within the list.

The TextComponent Class

The TextComponent class is the superclass of all text-based classes. It provides a common set of methods used by its TextField and TextArea subclasses. It does not provide any constructors and cannot be instantiated. It provides methods for getting and setting the text that is displayed in a text object, setting the text object to an editable or read-only state, or selecting text that is contained within the object.

TextField

The TextField class implements a one-line text entry field. It provides four constructors that are used to specify the width of the text field in character columns and the default text to be displayed within the field. It provides several methods for accessing the field's size and for specifying whether the characters typed by the user should be displayed. The setEchoCharacter() method is used to specify a character that is to be displayed in lieu of text typed by the user. This method is used to implement password-like fields.

TextArea

The TextArea class implements scrollable text entry objects that span multiple lines and columns. It provides four constructors that allow the number of rows and columns and the default text display to be specified. It provides several methods that return the dimensions of the text area and insert, append, and replace the text that is contained in the text area. It also provides the capability to set the text to read-only or edit mode.

The Canvas Class

The Canvas class implements a GUI object that supports drawing. Drawing is not implemented on the canvas itself, but on the Graphics object provided by the canvas. The Canvas class is usually subclassed to implement a custom graphics object. It provides a single, parameterless constructor and one useful method-the paint() method, which specifies how its Graphics object is to be updated.

Graphics

The Graphics class supports the drawing of graphical objects and text within a window. It is used with all graphical applications. The Graphics class is an abstract class that is created through methods of other classes. A Graphics object is typically provided as an argument to the paint() method of a Canvas object.

The Graphics class provides numerous methods for drawing lines, ovals, rectangles, polygons, text, images, and other objects that can be displayed within a window. It also provides methods for setting the foreground and background colors and the current text font. You should browse through the API description of this class to get a feel for all the methods it provides.

The Scrollbar Class

The Scrollbar class is used to implement vertical and horizontal scrollbars. It provides three constructors that allow the orientation of the scrollbar to be specified, as well as parameters that control the scrollbar's operation. It provides several methods that allow the scrollbar's parameters and current value to be read and set. See Chapter 24, "Scrollbars," for more information.

Constructing Menus

Java provides several classes that allow menu bars to be constructed and attached to a Frame window. These classes are directly descended from the Object class and are not subclasses of the component class.

The MenuComponent class is the superclass of the menu-related classes and provides a common set of methods that are used by its subclasses. The MenuComponent class provides a default parameterless constructor, although objects of this class should not be directly created. The getFont() and setFont() methods are used to specify the font to be used with a MenuComponent object. The getParent() method is used to retrieve an object that implements the MenuContainer interface and contains a specified MenuComponent object.

The MenuBar Class

The MenuBar class implements a menu bar that is attached to a Frame window. It provides a default parameterless constructor and several access methods for adding and removing Menu objects from the menu bar. It also provides methods that are used to return the current number of menus and to get and set a special help menu.

The MenuItem Class

The MenuItem class is used to implement items that may be selected from a pull-down menu. It is extended by the Menu and CheckboxMenuItem classes. The MenuItem class implements items that can be selected from a pull-down menu. Because it is subclassed by the Menu and CheckboxMenuItem classes, it provides the capability for objects of these classes to be selected from a pull-down menu. This allows multiple levels of menus to be implemented.

The MenuItem class provides a single constructor that takes a String object as a parameter. The String object is used as the label of the menu item. The MenuItem class provides methods for enabling and disabling a menu item and for getting and setting its label.

The Menu Class

The Menu class implements a single pull-down menu that is attached to a menu bar or other menu. It provides two constructors that allow the menu's label to be specified and determine whether it is to be implemented as a tear-off menu. It also provides methods that are used to add or remove menu items, add menu separators, count the number of items in the menu, and determine what menu item is currently selected.

The CheckboxMenuItem Class

The CheckboxMenuItem class is used to implement menu items that may be checked on or off. It provides a single constructor that contains the label to be used with the checkbox menu item. The setState() and getState() methods are used to determine the checked state of the menu item.

The MenuContainer Class

The MenuContainer interface provides a set of methods that are implemented by classes that contain menus. These methods are getFont(), postEvent(), and remove(). The getFont() method returns the current font associated with a menu object. The postEvent() method is used to generate a menu-related event. The remove() method is used to remove a MenuComponent object.

Organizing Windows

The method by which the components of a Container object are organized is determined by an object that implements the LayoutManager interface. The layout of a Container is specified using the setLayout() method of the Container class. It passes an object that implements the LayoutManager interface as a parameter.

The LayoutManager Class

The LayoutManager interface provides a set of methods that are implemented by classes that control the layout of a container. These methods include those that add or remove components from a layout, specify the size of the container, and lay out the components of the container.

The BorderLayout Class

The BorderLayout class is used to lay out the GUI components contained in a Container object. It lays out components along the north, south, east, and west borders of the container and in the center of the container. The center component gets any space left over from the north, south, east, and west border components. It is the default layout for the Window, Frame, and Dialog classes. It provides the capability to specify the horizontal and vertical gap between the laid out components and the container.

The CardLayout Class

The CardLayout class is used to lay out the components of a Container object in the form of a deck of cards where only one card is visible at a time. The class provides methods that are used to specify the first, last, next, and previous components in the container.

The FlowLayout Class

The FlowLayout class is used to lay out the components of a Container object in a left-to-right, top-to-bottom fashion. It is the default layout used with the Panel class. It allows the alignment of the components it lays out to be specified by the LEFT, CENTER, and RIGHT constants.

The GridLayout Class

The GridLayout class is used to lay out the components of a Container object in a grid where all components are the same size. The GridLayout constructor is used to specify the number of rows and columns of the grid.

The GridBagLayout Class

The GridBagLayout class lays out the components of a Container object in a grid-like fashion, where some components may occupy more than one row or column. The GridBagConstraints class is used to identify the positioning parameters of a component that is contained within an object that is laid out using GridBagLayout. The Insets class is used to specify the margins associated with an object that is laid out using a GridBagLayout object. Refer to the API description of the GridBagLayout class for more information on how to use this layout.

Handling Events

The user communicates with window programs by performing actions such as clicking a mouse button or pressing a key on the keyboard. These actions result in the generation of Event objects. The process of responding to the occurrence of an event is known as event handling. Window programs are said to be event driven because they operate by performing actions in response to events.

The Event class encapsulates all Windows event processing and is, therefore, a very important class. Because the Windows user interface is event driven, all nontrivial window programs must handle user events.

The Event class defines the entire list of events handled by window programs using class constants. These constants are used to identify the events that are passed to event-handling methods. You should review the Java API description of the Event class to familiarize yourself with these constants.

The Event class provides four constructors for constructing events, but you probably won't need to use these constructors because events are internally generated by the Java runtime system in response to user interface actions. The Event class also provides methods for determining whether the Control, Shift, or Meta (Alt) keys were pressed during the generation of an event.

Working with Images

The Image class is an abstract class that provides a content-independent mechanism for implementing graphical images. Images are created by invoking methods of other classes that create images. The createImage() methods of the Component and Applet classes and the getImage() methods of the Toolkit and Applet classes allow images to be created. Image objects are usually displayed on a Graphics object using the drawImage() method of the Graphics class. The Image class provides several methods for accessing the properties of an image.

The Color Class

The Color class provides a system-independent color implementation and defines several color constants. It provides three constructors that allow a color to be constructed from its red, green, and blue (RGB) color components. Its access methods provide access to the RGB values of a color; brighten and darken a color; and convert colors to a hue, saturation, and brightness (HSB) representation.

The java.awt.image Package

The java.awt.image package defines interfaces and classes that support image generation, storage, and processing. These classes are based on the concept of an image producer and an image consumer. The image producer provides the data associated with an image and the image consumer uses the data produced by the image producer to process or display an image.

The ImageProducer interface provides a set of methods for classes that produce images. These methods are used to reconstruct or modify an image being produced. The ImageConsumer interface provides a set of constants and methods for accessing image data provided by classes that implement the ImageConsumer interface. The ImageObserver interface provides a set of constants and methods by which objects are notified about an image that is being constructed.

ColorModel

The ColorModel class is an abstract class that provides a general framework for representing colors and maps this framework to the RGB color model. It is extended by the DirectColorModel and IndexColorModel classes.

The DirectColorModel class is used to directly access the color values of a pixel. It specifies a method for directly translating pixel values to their RGB values. The IndexColorModel class translates fixed colormap pixel values to their RGB component colors using pixel values as an index into a color map.

FilteredImageSource

The FilteredImageSource class provides the capability to filter an image using an object of class ImageFilter. FilterImageSource implements the ImageProducer interface. Its objects are used as intermediate image producers by filtering the image data produced by an image's original image producer using an object of the ImageFilter class. The FilterImageSource constructor takes the original image's ImageProducer and an ImageFilter object as its parameters. Its access methods provide the capability to add and remove image consumers and control the generation of image data.

ImageFilter

The ImageFilter class provides a common set of methods for implementing image filters. It does not implement any filtering of its own and must be subclassed to provide a specific filtering mechanism. It is extended by the CropImageFilter and RGBImageFilter classes.

CropImageFilter

The CropImageFilter class is an image filter that is used to crop images to a specific area. Its constructor takes the upper-left coordinate of the location of the cropping rectangle and the rectangle's height and width. Its access methods provide the capability to work with subsets of the pixels of the cropped area.

RGBImageFilter

The RGBImageFilter class is an abstract class that is used to create image filters that modify the pixels of the default RGB color model. In order to create a color filter based on this class, you subclass it and override the filterRGB() method. This method provides the x- and y-coordinates and RGB value of the pixel at the specified coordinates and returns the filtered color value. Setting the canFilterIndexColorModel flag to true enables filtering to be performed on the color model instead of the image. This greatly speeds up the filtering process and should be used when the filter is position independent.

PixelGrabber

The PixelGrabber class is used to capture the pixels of an image and store them in an array. It provides two constructors that specify the area to be captured and the array where the captured pixels are to be stored. The access methods provided by PixelGrabber are used to control the image capture process.

MemoryImageSource

The MemoryImageSource class is used to create an image using an array of pixel values. It implements the ImageProducer interface and provides six constructors for the creation of ImageProducer objects based on in-memory descriptions of the image's pixel values.

The MediaTracker Class

The MediaTracker class provides a set of methods for managing images used to implement multimedia objects. It provides the capability to load a specified set of images, wait on the loading of the images in the set, and maintain the load status of the images. It defines the COMPLETE, ABORTED, LOADING, and ERRORED constants to indicate the load status of an image. It provides a single constructor that identifies the Component object for which the images are to be loaded. Its access methods are used to manage the image-loading process.

Geometrical Objects

Java provides several classes for working with standard geometrical objects: Point, Rectangle, Polygon, and Dimension. These classes are described in the following subsections.

The Point Class

The Point class is used to represent general two-dimensional x,y-coordinates. It contains a single constructor that takes the x- and y-coordinates as its parameters. The x and y field variables are declared as public, providing access to individual coordinates. Methods to perform movement and translation of points are provided.

The Rectangle Class

The Rectangle class represents a rectangle using the x,y-coordinates of its upper-left corner, its width, and its height. Five constructors are provided to allow rectangles to be created using a variety of approaches. Methods are provided that allow a rectangle's parameters to be accessed, to support movement and translation operations, and to perform other geometrical operations.

The Polygon Class

The Polygon class represents a polygon as a list of x,y-coordinates that identify the polygon's vertices. It provides a default parameterless constructor and a constructor that identifies the polygon's vertices. The Polygon class provides several access methods that are used to access the polygon's vertices, add vertices, test whether a point is contained in a polygon, and get the minimum bounding box containing a polygon.

The Dimension Class

The Dimension class is used to represent the width and height of a two-dimensional object. It provides three constructors: a default parameterless constructor, a constructor that creates a Dimension object using another Dimension object, and a constructor that takes width and height parameters. The access methods provided by the Dimension class allow the height and width of a dimension to be accessed.

Using Fonts

The Font class implements a system-independent set of fonts that control text display. Java font names are mapped to system-supported fonts. The Courier, Dialog, DialogInput, Helvetica, TimesRoman, and ZapfDingbats fonts are the system-independent font names provided by Java. A default font is also supported that may consist of one of the above fonts or may be unique to a given operating-system platform.

Fonts can be specified in terms of font name, style, and point size. The supported styles are defined by the PLAIN, BOLD, and ITALIC constants of the Font class. Font styles can be combined by adding these constants. Font sizes can be any integer size supported by the system. The Font class provides a single constructor that takes the font name, style constants, and point size as its parameters.

The Font class provides several methods for querying the parameters of a font. The getName() method returns the Java name for the font. The getFamily() method returns the system-dependent font name. The getStyle() and getSize() methods return the font's style and size parameters. The isBold(), isItalic(), and isPlain() methods provides the capability to test the style parameter.

The FontMetrics Class

The FontMetrics class is used to access the specific display parameters of a Font object. A FontMetrics object is usually constructed using the getFontMetrics() method of the Component class. It provides several methods for determining a font's display parameters, as described in Chapter 22, "Text and Fonts."

The getHeight(), getLeading(), getAscent(), and getDescent() methods are used to determine the vertical size properties of a font. The stringWidth(), getWidths(), charWidth(), charsWidth(), and bytesWidth() methods are used to determine a font's horizontal size properties.

Using the Toolkit

The Toolkit class provides the linkage between the platform-independent classes of the AWT and their platform-dependent implementation. It provides the capability to access the platform-dependent peer classes of the subclasses of the Component class. These classes can be used to obtain direct access to a component's local implementation. The use of peer classes is discouraged because it limits the portability of any software that utilizes these methods. The java.awt.peer package contains the interfaces that are implemented by the platform-dependent AWT software.

The Toolkit class also provides several methods that provide access to implementation-dependent characteristics that can be safely used in Java programs. The getFontList() method provides a list of the fonts that are supported by the windowing environment. The getImage() method allows an image to be retrieved from an URL or the local file system. The getScreenSize() and getScreenResolution() methods return useful characteristics of the screen display. You should read the API description of this class to familiarize yourself with the methods that it provides.

Summary

This chapter introduces you to the classes of the java.awt package, which provide the foundation for Java window programming. You have learned how the java.awt package is organized and have covered the classes that it contains. You have also covered the java.awt.image and java.awt.peer packages. Part IV provides a detailed tutorial of Java window programming with numerous programming examples that will further help you understand the concepts.