The Awt/Swing Class Hierarchy: Jframe Jframe Paint Jframe
The Awt/Swing Class Hierarchy: Jframe Jframe Paint Jframe
Java's Abstract Windowing Toolkit, or AWT, is the portion of the Java run-
time library that is involved with creating, displaying, and facilitating user
interaction with window objects. The AWT is an example of a software frame-
work . A framework is a way of structuring generic solutions to a common
problem, using polymorphism as a means of creating specialized solutions for
each new application. Thus, examining the AWT will illustrate how polymor-
phism is used in a powerful and dynamic fashion in the language Java.
Beginning with Java 1.2, the AWT has been augmented with a newer library,
called Swing. A problem with the earlier AWT components was that they
depended upon the underlying operating system. For instance, an AWT button
will look like a Windows button on a Windows based PC and like a Macintosh
button on a Macintosh. The Swing library overcomes this limitation, and a
swing component will look the same on any platform. This means you do
not have to worry about inconsistences in the GUI between platforms. The
downside is that Swing components are much more computationally intensive,
since they operate with only minimal operating system support. This means a
Swing-based interface may take longer to draw than would an interface based
on the earlier AWT components. Nevertheless, the newer Swing library is slowly
becoming the preferred technique for creating user interfaces.
will help illustrate the functioning of the Java windowing system, as well as
illustrate the power of inheritance as a mechanism for code reuse and sharing.
The class Object is the parent class of all classes in Java. It provides the
ability to compare two objects for equality, compute a hash value for an object,
and determine the class of an object. Methods dened in class Object include
the following:
equals (anObject) Return true if object is equal to argument
getClass ( ) Return the class of an object
hashCode ( ) Return a hash value for an object
toString ( ) Return a string representation of an object
A Component is something that can be displayed on a two-dimensional screen
and with which the user can interact. Attributes of a component include a size,
a location, foreground and background colors, whether or not it is visible, and
a set of listeners for events. Methods dened in class Component include the
following:
setEnabled(boolean) Enable/disable a component
setLocation(int,int), getLocation( ) Set and get component location
setSize(int,int), getSize( ) Set and get size of component
setVisible(boolean) Show or hide the component
setForeground(Color), getForegound( ) Set and get foreground colors
setBackground(Color), getBackground( ) Set and get background colors
setFont(Font), getFont( ) Set and get font
13.1 The AWT/Swing Class Hierarchy 217
window class. This allows the code written in the AWT class Window to
perform application-specic actions, by invoking methods in the application
class that override methods in the parent class (paint( ), for example). The
fact that composition is used to link the container with the layout manager
makes the link between these two items very dynamic|the programmer can
easily change the type of layout manager being employed by a container. This
dynamic behavior is very dicult to achieve using inheritance alone, since the
inheritance relationship between a parent and child is established at compile
time. Finally, the fact that LayoutManager is simply an interface; and as well as
the fact that various dierent classes of objects implement this interface, means
that the programmer is free to develop alternative layout managers using a wide
variety of techniques. (This freedom would be much more constrained if, for
example, LayoutManager was a class that alternative layout managers needed to
extend.)
The next most common type of layout is the GridLayout. The manager for
this layout creates a rectangular array of components, each occupying the
same size portion of the screen. Using arguments with the constructor, the
programmer species the number of rows and the number of columns in the
grid. Two additional integer arguments can be used to specify a horizontal and
vertical space between the components. An example of a panel formatted using
a GridLayout is shown in Figure 13.13. The section of code for that application
that creates the layout manager is as follows:
JPanel p = new JPanel( );
// make a 4 by 4 grid,
// with 3 pixels between each element
p.setLayout (new GridLayout(4, 4, 3, 3));
The most general type of layout manager is the GridBagLayout manager. This
manager allows the programmer to create a nonuniform grid of squares, and
place components in various positions within each square. However, the details
of the use of this manager are complex and will not be described here.
222 THE AWT AND SWING
13.3.1 Labels
The simplest type of user interface component is a JLabel. A label has only the
text it will display. It will display as much of the text as it can in the area it is
given.
Unlike other components, a label does not respond to any type of event, such
as a mouse click or a key press. However, the text of the label can be changed
using the method setText(String), and the current text of a label can be retrieved
using getText( ).
13.3 User Interface Components 223
13.3.2 Button
A JButton is a labeled component, represented by a rounded box, that can
respond to user interaction. As we have seen in earlier programs, interaction
with a button is achieved by attaching an ActionListener object to the button.
The ActionListener object is then notied when the button is pressed.
JButton b = new JButton ("do it!");
b.addActionListener (new DoIt( ));
.
.
.
private class DoIt implements ActionListener {
public void actionPerformed (ActionEvent e) {
// whatever DoIt does
.
.
.
}
}
A useful technique is to combine the button object and the button listener
in one new class. This new class both subclasses from the original JButton class
and implements the ActionListener interface. For example, in the case study
presented in Section 13.5, we create a set of buttons for dierent colors. Each
button holds a color value, and when pressed it invokes a method using the
color as argument. This class is written as follows:
private class ColorButton
extends JButton implements ActionListener {
private Color ourColor;
Notice how the object registers itself as a listener for button actions. The
pseudovariable this is used when an object needs to denote itself. When pressed,
the button will invoke the method actionPerformed, which will then invoke the
method setFromColor that is found in the surrounding class.
224 THE AWT AND SWING
We can even take this technique one step further, and dene a generic
ButtonAdapter class that is both a button and a listener. The actions of
the listener will be encapsulated by an abstract method, which must be
implemented by a subclass:
abstract class ButtonAdapter
extends JButton implements ActionListener {
public ButtonAdapter (String name) {
super (name);
addActionListener (this);
}
13.3.5 Checkbox
A JCheckBox is a component that maintains and displays a labeled binary state.
The state described by a checkbox can be either on or o. The current state of
the checkbox can be set or tested by the programmer. A checkbox is typically
used in an application to indicate a binary (on/o, yes/no) choice (see Figure
13.6).
Both the label and the state of the checkbox can be set by the programmer,
using the methods getText, setText, isSelected, and setSelected. Changing the
state of a checkbox creates an ItemEvent, that is registered with any ItemListener
objects. The following simple application illustrates the use of these methods:
import javax.swing.*;
import java.awt.event.*;
public CheckTest ( ) {
setTitle("Check box example"); setSize(300, 70);
cb.addItemListener (new CheckListener( ));
getContentPane().add ("Center", cb);
}
if (cb.isSelected( ))
cb.setText ("The checkbox is on");
else cb.setText ("The checkbox is off");
}
}
}
Figure 13.8 Three selection possibilities: radio button Checkbox group, Choice object,
and a List.
228 THE AWT AND SWING
public ChoiceTest ( ) {
setTitle ("selection example"); setSize (300, 300);
theChoice.addItemListener(theListener);
theList.addListSelectionListener (new ListSelectionListener( ) {
public void valueChanged (ListSelectionEvent e)
{ setDisplay( ); }});
getContentPane().add("West", makeRadioButtons());
getContentPane().add("North", theChoice);
getContentPane().add("East", theList);
getContentPane().add("South", display);
}
ve or more. A combo box takes up less space in the display, but makes it more
dicult to view all the alternatives.
To create a JComboBox or a JList object, the programmer species the
alternatives as an array of objects passed to the constructor. An ItemListener
can be attached to the object. When a selection is made, the listener will be
informed using the method itemStateChanged. The text of the selected item can
be recovered using the method getSelectedItem.
To structure a group of radio buttons as a group, the programmer rst
creates a ButtonGroup. Each button is registered with the button group. As a
checkbox group is constructed out of several components, it is almost always
laid out on a JPanel. The JPanel is then placed as a single element in the original
layout. This is shown in Figure 13.9. Here a 5 by 2 grid is used as layout for
the 10 checkboxes.
13.4 Panels
A JPanel is a Container that acts like a Component. A panel represents a rectan-
gular region of the display. Each panel holds its own layout manager, which
can dier from the layout manager for the application display. Items can be
inserted into the panel. The panel, as a single unit, is then inserted into the
application display.
The use of a panel is illustrated by the application described in Figure 13.9.
Here the method makeRadioButtons creates a panel to hold the 10 radio buttons
that make up the group. This panel is structured, using a GridLayout as a 5 by
2 element matrix. This group of 10 components can then be treated as a single
element, and is placed on the left side of the application layout.
More examples of the use of panels will be provided by the application
that will be described in the next section. A snapshot of the window for this
application is shown in Figure 13.13. The three scroll bars on the left are placed
on a panel. This panel is laid out using a BorderLayout manager. The method
to create and return this panel is described as follows:
private JPanel makeScrollBars ( ) {
JPanel p = new JPanel( );
p.setLayout (new BorderLayout( ));
p.add("West", redBar);
p.add("Center", greenBar);
p.add("East", blueBar);
return p;
}
The panel returned as the result of this method is then placed on the left
side of the application window.
230 THE AWT AND SWING
13.4.1 ScrollPane
A JScrollPane is in many ways similar to a JPanel. Like a panel, it can hold
another component. (See Figure 13.9.) However, a JScrollPane can only hold one
component, and it does not have a layout manager. If the size of the component
being held is larger than the size of the ScrollPane itself, scroll bars will be
automatically generated to allow the user to move the underlying component.
We illustrate the use of a ScrollPane with a simple test program, shown in
Figure 13.11. The application window in this program will be set to 300 by
300 pixels, but a scroll pane is created that holds a canvas that has been
sized to 1000 by 1000 pixels. Scroll bars will therefore be added automatically
that allow the user to see portions of the underlying canvas. As mouse events
are detected by the canvas, points will be added to a Polygon. The listener
is here doing double duty, trapping both mouse presses (subclassing from
frame MouseAdapter and overriding the message mousePressed) and scroll bar
movements (implementing the AdjustmentListener interface and implementing
the method adjustmentValueChanged). To paint the application window, the
canvas simply draws the polygon values.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public BigCanvas( ) {
setSize (300, 300); setTitle ("Scroll Pane Test");
// make canvas larger than window
jp.setPreferredSize(new Dimension(1000, 1000));
jp.addMouseListener(mouseListener);
// add scroll pane to manage canvas
JScrollPane jsp = new JScrollPane(jp);
jsp.getHorizontalScrollBar().addAdjustmentListener(mouseListener);
jsp.getVerticalScrollBar().addAdjustmentListener(mouseListener);
getContentPane().add("Center", jsp);
}
bars and the use of methods provided by the class Color. Finally, we can also
use this program to illustrate how nested classes can be employed to combine
the actions of creating a new graphical component (such as a button or a slider)
and listening for actions relating to the component.
The class ColorTest (Fig. 13.12) creates a window to display color values. The
window (Fig. 13.13) is divided into four regions. The regions are managed by
the default layout manager for class Frame, which is a value of type BorderLayout.
At the top (the \north" side) is a text region, a component of type JTextField,
that describes the current color. To the left (the \west" region) is a trio of sliders
that can be used to set the red, green, and blue values. To the right (the \east"
region) is a 4 by 4 bank of 16 buttons. These are constructed on a JPanel
that is organized by a GridLayout manager. Thirteen of the buttons represent
the predened color values. Two more represent the actions of making a color
brighter and darker. The nal button will halt the application. Finally, in the
middle will be a square panel that represents the specied color.
The class ColorTest holds six data elds. The rst represents the text eld
at the top of the page. The second represents the color panel in the center.
the third represents the current color of this center panel. The remaining three
represent the three scrollbars that will be placed in the panel on the left.
The three sliders make use of the class ColorBar described earlier in Sec-
tion 13.3.3. The argument used with the constructor for each class is the color
to be used in painting the buttons and background for the scroll bar. You will
recall that when adjusted, the scroll bar will invoke its listener, which will ex-
ecute the method adjustmentValueChanged. This method will then execute the
method setFromBar.
A method makeScrollBars, used to create the panel that holds the three scroll
bars, was described earlier in Section 13.4.
The idea of combining inheritance and implementation of an interface is used
in creating the buttons that represent the 13 predened colors. Each instance
of ColorButton, shown earlier in Section 13.3.2, both extends the class JButton
and implements the ActionListener interface. When the button is pressed, the
method setFromColor will be used to set the color of the middle panel using the
color stored in the button.
The class BrightenButton is slightly more complex. An index value is stored
with the button. This value indicates whether the button represents the
\brighten" button or the \darken" button. When pressed, the current color
is modied by the appropriate method, and the new value used to set the
current color.
private class BrightenButton
extends JButton implements ActionListener {
private int index;
public BrightenButton (int i) {
super ( i == 0 ? "brighter" : "darker");
13.5 Case Study: A Color Display 233
public ColorTest( ) {
setTitle ("color test"); setSize (400, 600);
getContentPane().add("North", colorDescription);
getContentPane().add("East", makeColorButtons( ));
getContentPane().add("Center", colorField);
getContentPane().add("West", makeScrollBars( ));
setFromColor (current);
}
index = i;
addActionListener(this);
}
A panel is used to hold the 16 button values. In this case the layout is
described by a 4 by 4 grid pattern. Thirteen represent the predened buttons.
Two represent the brighter and darker buttons. And the nal creates a button
that when pressed exits the application.
private JPanel makeColorButtons ( ) {
JPanel p = new JPanel( );
p.setLayout (new GridLayout(4,4,3,3));
p.add (new ColorButton(Color.black, "black"));
p.add (new ColorButton(Color.blue, "blue"));
p.add (new ColorButton(Color.cyan, "cyan"));
p.add (new ColorButton(Color.darkGray, "darkGray"));
p.add (new ColorButton(Color.gray, "gray"));
p.add (new ColorButton(Color.green, "green"));
p.add (new ColorButton(Color.lightGray, "lightGray"));
p.add (new ColorButton(Color.magenta, "magenta"));
13.6 Dialogs 235
13.6 Dialogs
A JDialog is a special purpose window that is displayed for a short period of
time during the course of execution, disappearing thereafter. Dialogs are often
used to notify the user of certain events, or to ask simple questions. A dialog
must always be attached to an instance of JFrame, and disappears automatically
when the frame is hidden (such as when the application halts).
Dialog windows can be modal or nonmodal. A modal dialog demands a
response from the user, and it prevents the user from performing any further
action until the dialog is dismissed. A nonmodal dialog, sometimes called a
modeless dialog, can be ignored by the user. The processing of actions for a
nonmodal dialog is often placed in a separate Thread (see Chapter 20), so that
the actions produced by the dialog will not disrupt the continuing processing
of the rest of the application. Whether or not a dialog is modal is determined
when the dialog is created. The two arguments used in the constructor for the
dialog are the application Frame and a Boolean value that is true if the dialog
is modal.
// create a new nonmodal dialog in current application
JDialog dig = new JDialog (this, false);
For modal dialogs, the show method does not return until the dialog is dis-
missed. Such dialogs must therefore invoke the setVisible(false) method sometime
during their processing.
public DialogTest( ) {
setTitle ("Dialog Test Program");
setSize (300, 220);
.
.
.
JMenuBar bar = new JMenuBar( );
setJMenuBar (bar);
.
.
.
Individual menus are named, and are placed on the menu bar using the
method add:
.
.
.
JMenu helpMenu = new JMenu ("Help");
bar.add (helpMenu);
.
.
.
Menu items are created using the class JMenuItem. Each menu item maintains
a list of ActionListener objects, the same class used to handle JButton events.
The listeners will be notied when the menu item is selected.
.
.
.
JMenuItem quitItem = new JMenuItem ("Quit");
quitItem.addActionListener (new QuitListener( ));
helpMenu.add (quitItem);
.
.
.
.
.
.
// add quit menu item to application
new QuitItem (this);
.
.
.
}
}
Study Questions
1. What do the letters AWT stand for?
2. What is a Component object in the Java AWT?
3. What are the parent classes of class JFrame?
4. In what class is the method setBackground dened?
5. How is a container dierent from other types of components?
6. What is the dierence between a frame, a window, and a container?
7. Explain why in a framework there are two views of an overridden method,
such as paint.
8. What is the task performed by the layout manager?
9. Explain how the three mechanisms of inheritance, composition, and
implementation of an interface are all involved in the task of attaching a
layout manager to a container.
10. What are the ve dierent layout manager types? Which mangers use the
one argument add method, and which use the method in which the rst
argument is a String value and the second a component?
Exercises 241
Exercises
1. Add a menu bar to the Solitaire program described in Chapter 9. Then,
add two menu items, one to quit the application, and one to reset the
application for a new game.
2. Write code to create a panel having a 2 by 2 grid layout with 3 pixels
horizontal space and 5 pixels vertical space between components. Place
buttons labelled \one" to \four" in the panels of the grid. Place this panel
in the center of your frame.
3. After placing the panel from the last question into the center portion of
a window, add a small text box at the top. As each button is pressed,
display the button number in the text box.
4. Using a text box and a grid of buttons, create a simple calculator appli-
cation. Buttons correspond to digits and the four arithmetic functions +,
,, and =, as well as the equals sign.