The designers of the Abstract Windowing Toolkit (or AWT) attempted to make the classes provided by the AWT "do the right thing." Much of the time, the result is pleasing and effective. However, they were wise enough to provide mechanisms by which the AWT's idea of the "right" behavior and appearance could be changed, so that programmers could alter the behavior and appearance of components.
This column, my last on the AWT, introduces five techniques for enhancing a user interface. The techniques draw upon and extend the concepts learned in my previous two columns. I will describe how to select the font, the background color, and the foreground color of components; how to specify the preferred size of a component, and the insets of a container; and how to enable and disable components on the fly.
The default font for components is the "Dialog" font. Java provides a number of other fonts for specialized display purposes. The exact number depends on the platform. Figure 2 contains a listing of the fonts available in your implementation of Java. The source is available here.
When a programmer needs to display a component, such as a TextArea object, in a font other than the default font, the new
font may be selected with the setFont() method:
public void setFont(Font f)
The setFont() method expects a Font object as a parameter. The code in Listing 1 illustrates the use of the setFont() method.
TextArea ta = new TextArea();
Font f = new Font("Helvetica", Font.ITALIC, 12);
ta.setFont(f);
Listing 1: The setFont() method
The code in Listing 1, with only slight modifications, will work for any component.
Figure 3 illustrates the result of changing the font for several components provided by the AWT. The font in this example has been set to 12 point, italic Helvetica.
If a container's font is changed, all of the components placed within the container will automatically use the new font. The code in Listing 2 illustrates this point. The font is set only for the Frame object. The Button, Checkbox, and TextArea objects, in turn, also use that font.