0% found this document useful (0 votes)
165 views27 pages

The Awt/Swing Class Hierarchy: Jframe Jframe Paint Jframe

The document discusses the AWT and Swing frameworks in Java. It describes how: 1) The AWT provides components for creating graphical user interfaces but they depend on the underlying operating system. Swing was introduced to make components look the same across platforms. 2) Both AWT and Swing components inherit from classes like Component, Container, Window and Frame. This allows code reuse and polymorphism where child classes can override parent methods. 3) Layout managers in AWT are used to position components within a container. There are different layout managers that arrange components in different ways. The container handles interaction with the layout manager.

Uploaded by

Yawi Hotari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
165 views27 pages

The Awt/Swing Class Hierarchy: Jframe Jframe Paint Jframe

The document discusses the AWT and Swing frameworks in Java. It describes how: 1) The AWT provides components for creating graphical user interfaces but they depend on the underlying operating system. Swing was introduced to make components look the same across platforms. 2) Both AWT and Swing components inherit from classes like Component, Container, Window and Frame. This allows code reuse and polymorphism where child classes can override parent methods. 3) Layout managers in AWT are used to position components within a container. There are different layout managers that arrange components in different ways. The container handles interaction with the layout manager.

Uploaded by

Yawi Hotari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

13 The AWT and Swing

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.

13.1 The AWT/Swing Class Hierarchy


From the very rst, we have said that class JFrame represents the Java notion
of an application window, a two-dimensional graphical surface that is shown
on the display device and through which the user interacts with a computer
program. All our applications have been formed by inheriting from JFrame,
overriding various methods, such as the paint method for repainting the window.
In actuality, much of the behavior provided by class JFrame is inherited from
parent classes (see Figure 13.1). Examining each of these abstractions in turn
215
216 THE AWT AND SWING

Figure 13.1 The AWT class hierarchy.

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 de ned 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 de ned 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

repaint(Graphics) Schedule component for repainting


paint(Graphics) Repaint component appearance
addMouseListener(MouseListener) Add a mouse listener for
component
addKeyListener(KeyListener) Add a keypress listener for
component
In the AWT library graphical elements such as buttons, checkboxes, scroll bars,
and the like are declared as types of components. We will see shortly that the
Swing library has moved the Swing versions of these components (JButton and
the like) further down the class hierarchy.
A Container is a type of component that can nest other components within
it. A container is the way that complex graphical interfaces are constructed.
A container maintains a list of the components it manipulates, as well as a
layout manager to determine how the components should be displayed. Methods
de ned in class Container include the following:
setLayout (LayoutManager) Set layout manager for display
add (Component), remove (Component) Add or remove component from
display
A Window is a type of Container. A window is a two-dimensional drawing
surface that can be displayed on an output device. A window can be stacked
on top of other windows and can be moved either to the front or back of the
visible windows. Methods de ned in class Window include the following:
show( ) Make the window visible
toFront( ) Move window to front
toBack( ) Move window to back
A Frame is a type of window with a title bar, a menu bar, a border, a cursor,
and other properties. Methods de ned in class Frame include:
setTitle(String), getTitle( ) Set or get title
setCursor(int) Set cursor
setResizable( ) Make the window resizable
setMenuBar(MenuBar) Set menu bar for window
Finally, the Swing class JFrame is a subclass of the earlier AWT class Frame.
A JFrame will maintain a Container, called the contentPane , that will hold all
the graphical elements of the window. In addition, the method overrides several
of the methods inherited from parent classes.
getContentPane() Return container for window
218 THE AWT AND SWING

Figure 13.2 Two views of a component.

If we consider a typical application, such as the CannonWorld application of


Chapter 6, we see that it uses methods from a number of di erent levels of the
class hierarchy:
getContentPanel( ) Inherited from class JFrame
setTitle(String) Inherited from class Frame
setSize(int, int) Inherited from class Component
show( ) Inherited from class Window
repaint( ) Inherited from class Component
paint( ) Inherited from Component, overridden in application class
The power of the AWT, indeed the power of any framework, comes through
the use of a polymorphic variable, that is, a variable declared as a parent type
with a value from a child class. When the method show in class Window is
invoked, it calls the method setVisible in class Component. This method calls
repaint, which in turn calls paint. The code for the algorithm used by setVisible
and repaint resides in class Component. When it is being executed, the framework
\thinks" that it is dealing only with an instance of Component. However, in
actuality the method paint that is being executed is the version that has been
overridden in the application class. Thus, there are two views of the method
being executed, as described in Figure 13.2.
The code in the parent classes (Component, Container, Window, Frame and
JFrame) can all be written without reference to any particular application.
Thus, this code can be easily carried from one application to the next. To
specialize the design framework to a new application it is only necessary to
override the appropriate methods (such as paint or event listeners) to de ne
13.2 The Layout Manager 219

Figure 13.3 Relationships between Layout Manager Components

application-speci c behavior. Thus, the combination of inheritance, overriding,


and polymorphism permits design and software reuse on a grand scale.

13.2 The Layout Manager


The idea of a layout manager, which is the technique used by the AWT to assign
the locations of components within a container, is an excellent illustration of
the combination of polymorphic techniques of composition and inheritance. The
layout manager is charged with assigning positions on the surface of a container
to the components held in that container. There are a variety of standard layout
managers, each of which will place components in slightly di erent ways. The
programmer developing a graphical user interface creates an instance of a layout
manager and hands it to a container. Generally, the task of creation is the
only direct interaction the programmer will have with the layout manager, as
thereafter all commands will be handled by the container itself.
The connections between the application class, the container, and the layout
manager illustrate yet again the many ways that inheritance, composition, and
interfaces can be combined (Figure 13.3). The application class may inherit
from the container (as is usually the case when an application is formed using
inheritance from class Frame in the AWT) or it may hold the container as a
component (as is usually the case when an application is formed from JFrame
using the Swing). In either case the container itself, however, holds the layout
manager as a data eld, as part of the internal state of the container. But in
actual fact, the variable that holds the layout manager is polymorphic. While
the Container thinks that it is maintaining a value of type LayoutManager, in
fact it will be holding a value from some other type, such as GridLayout, that is
implementing the LayoutManager interface.
There are three di erent mechanisms at work here: inheritance, composition,
and implementation of an interface. Each is serving a slightly di erent purpose.
Inheritance is the is-a relation that links the application class to the parent
220 THE AWT AND SWING

Figure 13.4 Locations recognized by Border Layout Manager.

window class. This allows the code written in the AWT class Window to
perform application-speci c 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 di erent 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.)

13.2.1 Layout Manager Types


There are ve standard types of layout managers: BorderLayout, GridLayout, Card-
Layout, FlowLayout, and GridBagLayout. The BorderLayout manager can manage
no more than ve di erent components. This is the default layout manager
for applications constructed by subclassing from JFrame. The ve locations are
shown in Figure 13.4. They correspond to the left and right, top and bottom,
and center of the display. Not all ve locations need be lled. If a location is
not used, the space is allocated to the remaining components.
When a border layout manager is employed, the rst argument in the add
method is used to specify which position a component is lling in a collection.
(With JFrame we must rst use the method getContentPane in order to access
the container holding the window contents.)
getContentPane().add("North", new JButton("quit"));
getContentPane().add("Center", colorField);
13.2 The Layout Manager 221

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 speci es 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));

p.add (new ColorButton(Color.black, "black"));


p.add (new ColorButton(Color.blue, "blue"));

A FlowLayout manager places components in rows left to right, top to bottom.


Unlike the layout created by a GridLayout manager, the components managed
by a ow layout manager need not all have the same size. When a component
cannot be completely placed on a row without truncation, a new row is created.
The ow manager is the default layout manager for the class JPanel (as opposed
to JFrame, where the default manager is a BorderLayout).
A CardLayout manager stacks components vertically. Only one component is
visible at any one time. The components managed by a card layout manager
can be named (using the string argument to the add method). Subsequently, a
named component can be made the visible component. This is one of the few
instances where the programmer would have direct interaction with the layout
manager.
CardLayout lm = new CardLayout( );
JPanel p = new JPanel (lm);
p.add ("One", new JLabel ("Number One"));
p.add ("Two", new JLabel ("Number Two"));
p.add ("Three", new JLabel ("Number Three"));
.
.
.
lm.show (p, "Two"); // show component \Two"

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

Figure 13.5 The Swing class hierarchy.

13.3 User Interface Components


The variety of user interface components in the Java and Swing frameworks
are again a good illustration of the power of polymorphism provided both
through inheritance and interfaces. In the Swing extensions of the AWT, all
the user interface components are subclasses of the parent class JComponent
(Figure 13.5). Containers assume only that the elements they will hold are
instances of subclasses of class Component. In fact, the values they maintain are
polymorphic and represent more specialized values, such as buttons or scroll
bars. Thus, the design of the user interface construction system depends upon
the mechanisms of inheritance, polymorphism, and substitutability.

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.

JLabel lab = new JLabel("score: 0 to 0");


getContentPane().add ("South", lab); // put label on bottom of window

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 noti ed 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 di erent 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;

public ColorButton (Color c, String name) {


super (name); // create the button
ourColor = c; // save the color value
addActionListener (this); // add ourselves as listener
}

public void actionPerformed (ActionEvent e) {


// set color for middle panel
setFromColor (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 de ne 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);
}

public void actionPerformed (ActionEvent e) { pressed( ); }

public abstract void pressed ( );


}

To create a button using this abstraction, the programmer must create a


subclass and override the method pressed. This, however, can be done easily
using a class de nition expression (see Section 10.5.3). The following, for
example, creates a button that when pressed will halt the application.
JPanel p = new JPanel( );

p.add (new ButtonAdapter("Quit"){


public void pressed ( ) { System.exit(0); }});

13.3.3 Scroll Bars


A JScrollBar is a slider, used to specify integer values over a wide range.
Scroll bars can be displayed in either a horizontal or a vertical direction. The
maximum and minimum values can be speci ed, as well as the line increment
(the amount the scroll bar will move when it is touched in the ends), and the
page increment (the amount it will move when it is touched in the background
area between the slider and the end). Like a button, interaction is provided for
a scroll bar by de ning a listener that will be noti ed when the scroll bar is
modi ed.
The case study at the end of this chapter uses a technique similar to the
one described earlier in the section on buttons. Figure 13.13 o ers a a snapshot
of this application, which includes three vertical scroll bars. The class ColorBar
represents a scroll bar for maintaining colors. The constructor for the class
creates a vertical scroll bar with an initial value of 40 and a range between 0
and 255. The background color for the scroll bar is set using a given argument.
Finally, the object itself is made a listener for scroll bar events. When the scroll
bar is changed, the method adjustmentValueChanged will be executed. Typically,
within this method the current value of the scroll bar would be accessed using
13.3 User Interface Components 225

Figure 13.6 A window with two text components.

getValue( ). In this particular application, a bank of three scroll bars will be


created, and the value of all three will be recovered in a shared method named
setFromBar.
private class ColorBar
extends JScrollBar implements AdjustmentListener {
public ColorBar (Color c) {
super (JScrollBar.VERTICAL, 40, 0, 0, 255);
setBackground (c);
addAdjustmentListener (this);
}

public void adjustmentValueChanged (AdjustmentEvent e) {


// method setFromBar will get scroll bar
// value using getValue( );
setFromBar ( );
}
}

13.3.4 Text Components


A text component is used to display editable text. There are two varieties of
text components, JTextField and JTextArea. The rst is a xed-size block, while
the second uses scroll bars to display a larger block of text, not all of which
might be viewable at any one time. Figure 13.5 illustrates these two types of
items.
The text in a text component can be set or accessed by the program using
the methods setText(String) and getText( ). Additional text can be added to the
text area using the method append(String). Various other methods can be used
to indicate whether or not the text is editable and to select a subportion of the
226 THE AWT AND SWING

Figure 13.7 A window with a checkbox.

text. A TextListener can be attached to a text component. The listener must


implement the TextListener interface:
interface TextListener extends EventListener {
public void textValueChanged (TextEvent e);
}

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.*;

class CheckTest extends JFrame {


private JCheckBox cb = new JCheckBox ("the checkbox is off");

public static void main (String [ ] args)


{ CheckTest world = new CheckTest( ); world.show( ); }

public CheckTest ( ) {
setTitle("Check box example"); setSize(300, 70);
cb.addItemListener (new CheckListener( ));
getContentPane().add ("Center", cb);
}

private class CheckListener implements ItemListener {

public void itemStateChanged (ItemEvent e) {


13.3 User Interface Components 227

if (cb.isSelected( ))
cb.setText ("The checkbox is on");
else cb.setText ("The checkbox is off");
}
}
}

13.3.6 Radio Button Groups, Choices, and Lists


Three types of interface components are typically employed to allow the user
to select one item from a large number of possibilities. The rst is a group of
connected buttons, called a ButtonGroup, that has the property that only one
can be set at any one time. Such a collection is sometimes called a radio button
group, since their behavior is similar to the way buttons in car radios work.
The second form is termed a JComboBox. A JComboBox object displays only
one selection, but when the user clicks the mouse in the selection area, a pop-
up menu appears that allows the choice to be changed to a di erent selection.
A third possibility is termed a JList. A JList is similar to a JComboBox, however
several possibilities out of the range can be displayed at one time.
Figure 13.7 illustrates all three possibilities. The code to produce this
example is shown in Figure 13.9.
A ButtonGroup group should be used when the number of alternatives is
small. A JComboBox or a JList should be used if the number of alternatives is

Figure 13.8 Three selection possibilities: radio button Checkbox group, Choice object,
and a List.
228 THE AWT AND SWING

public class ChoiceTest extends JFrame {


public static void main (String [ ] args)
{ ChoiceTest world = new ChoiceTest( ); world.show( ); }

private String [ ] choices = {"One", "Two", "Three", "Four",


"Five", "Six", "Seven", "Eight", "Nine", "Ten"};
private JLabel display = new JLabel( );
private JComboBox theChoice = new JComboBox(choices);
private JList theList = new JList(choices);
private ButtonGroup theGroup = new ButtonGroup();
private ItemListener theListener = new ItemListener() {
public void itemStateChanged (ItemEvent e) { setDisplay( ); }};

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);
}

private void setDisplay ( ) {


display.setText( (String) theList.getSelectedValue() +
theGroup.getSelection().getActionCommand() +
theChoice.getSelectedItem());
}

private JPanel makeRadioButtons( ) {


JPanel p = new JPanel (new GridLayout(5,2));
for (int i = 0; i < 10; i++) {
JRadioButton jb = new JRadioButton(choices[i]);
theGroup.add(jb); p.add(jb);
jb.setActionCommand(choices[i]);
jb.addItemListener(theListener);
}
return p;
}
}

Figure 13.9 Alternative ways to display choices.


13.4 Panels 229

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 speci es 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 di er 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.

13.5 Case Study: A Color Display


A simple test program will illustrate how panels and layout managers are used
in developing user interfaces. The application will also illustrate the use of scroll

Figure 13.10 A ScrollPane test.


13.5 Case Study: A Color Display 231

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

public class BigCanvas extends JFrame {


public static void main ( String [ ] args) {
BigCanvas world = new BigCanvas( );
world.show( );
}

private Polygon poly = new Polygon( );


private JPanel jp = new JPanel();
private MouseKeeper mouseListener = new MouseKeeper();

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);
}

public void paint (Graphics g) {


super.paint(g);
Graphics gr = jp.getGraphics( );
gr.drawPolygon (poly);
}

private class MouseKeeper


extends MouseAdapter implements AdjustmentListener {
public void mousePressed (MouseEvent e) {
poly.addPoint (e.getX( ), e.getY( ));
repaint( );
}

public void adjustmentValueChanged (AdjustmentEvent e)


{ repaint( ); }
}
}

Figure 13.11 Test program for scrollpanes.


232 THE AWT AND SWING

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 prede ned 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 speci ed 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 prede ned 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 modi ed 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

class ColorTest extends JFrame {


static public void main (String [ ] args)
{ ColorTest world = new ColorTest( ); world.show( ); }

private JTextField colorDescription = new JTextField( );


private JPanel colorField = new JPanel( );
private Color current = Color.black;
private JScrollBar redBar = new ColorBar(Color.red);
private JScrollBar greenBar = new ColorBar(Color.green);
private JScrollBar blueBar = new ColorBar(Color.blue);

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);
}

private void setFromColor (Color c) {


current = c; colorField.setBackground (current);
redBar.setValue(c.getRed( )); greenBar.setValue(c.getGreen( ));
blueBar.setValue(c.getBlue( ));
colorDescription.setText(c.toString( ));
}

private void setFromBar ( ) {


int r = redBar.getValue( ); int g = greenBar.getValue( );
int b = blueBar.getValue( ); setFromColor (new Color(r, g, b));
}

private JPanel makeColorButtons ( ) { ... }


private JPanel makeScrollBars ( ) { ... }
private class BrightenButton extends JButton implements ActionListener ...
private class ColorButton extends JButton implements ActionListener ...
private class ColorBar extends JScrollBar implements AdjustmentListener ...
}

Figure 13.12 The class ColorTest.


234 THE AWT AND SWING

Figure 13.13 Snapshot of ColorTest application.

index = i;
addActionListener(this);
}

public void actionPerformed (ActionEvent e) {


if (index == 0)
setFromColor (current.brighter( ));
else
setFromColor (current.darker( ));
}
}

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 prede ned 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

p.add (new ColorButton(Color.orange, "orange"));


p.add (new ColorButton(Color.pink, "pink"));
p.add (new ColorButton(Color.red, "red"));
p.add (new ColorButton(Color.white, "white"));
p.add (new ColorButton(Color.yellow, "yellow"));
p.add (new BrightenButton(0));
p.add (new BrightenButton(1));
p.add (new ButtonAdapter("Quit"){
public void pressed( ) { System.exit(0); }});
return p;
}

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);

Because a JDialog is a type of Window, graphical components can be placed


in the dialog area, just as in a JFrame or JPanel. The default layout manager
for a dialog is BorderLayout, the same as with JFrame.
The most common methods used with a dialog are not actually de ned in the
class JDialog but are inherited from parent classes. These include the following:
setSize(int, int) Set window size
show( ) Display window
setVisible(false) Remove window from display
setTitle(String), getTitle( ) Set or get title of window
236 THE AWT AND SWING

Figure 13.14 Dialog example window.

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.

13.6.1 Example Program for Dialogs


An example program will illustrate the creation and manipulation of dialogs.
The application shown in Figure 13.15, on page 226, creates a window with
a checkbox, a button, and a text area. The application window, as well as an
example dialog box window, is shown in Figure 13.14. The checkbox allows the
user to specify either a modal or modeless dialog box should be created. The
button creates the dialog, while the text area records button presses performed
by the dialog.
The method makeDialog creates the dialog box. The size of the box is set
at 100 by 100 pixels, and four buttons are placed on the box. Three buttons
simply type text into the display when pressed, while the last button will hide
the dialog. For a modal dialog hiding the dialog is the same as dismissing the
dialog box, and it returns control to the method that created the dialog.

13.7 The Menu Bar


A Swing menu bar is a graphical component, it is declared as a sub-class
of JComponent. Both menu bars and menus act like containers. A menu bar
contains a series of menus, and each menu contains a series of menu items.
An instance of JMenuBar can be attached to a Frame using the method
setJMenuBar:
13.7 The Menu Bar 237

class DialogTest extends JFrame {


static public void main (String [ ] args)
{ DialogTest world = new DialogTest( ); world.show( ); }

private JTextArea display = new JTextArea( );


private JCheckBox cb = new JCheckBox("Modal Dialog?");

public DialogTest( ) {
setTitle ("Dialog Test Program");
setSize (300, 220);

getContentPane().add ("West", cb);


getContentPane().add ("East", new Makebutton( ));
getCOntentPane().add ("South", display);
}

private class Makebutton extends ButtonAdapter {


public Makebutton ( ) { super ("Make Dialog"); }
public void pressed ( ) { makeDialog (cb.isSelected( )); }
}

private void makeDialog (boolean modalFlag) {


final JDialog dlg = new JDialog (this, modalFlag);
dlg.setSize (100, 100);
dlg.add ("North", new CountButton(1));
dlg.add ("West", new CountButton(2));
dlg.add ("East", new CountButton(3));
dlg.add ("South", new ButtonAdapter("Hide") {
public void pressed ( ) { dlg.setVisible(false); }});
dlg.show( );
}

private class CountButton extends ButtonAdapter {


public CountButton (int val) { super ("" + val); }
public void pressed ( ) {
display.append("Button " + getLabel( ) + " pressed\n");}
}
}

Figure 13.15 Example program for creating dialogs.


238 THE AWT AND SWING

.
.
.
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 noti ed when the menu item is selected.
.
.
.
JMenuItem quitItem = new JMenuItem ("Quit");
quitItem.addActionListener (new QuitListener( ));
helpMenu.add (quitItem);
.
.
.

A number of techniques can be used to create special purpose menus, such


as tear-o menus, cascading menus, and so on. However, these will not be
described here.

13.7.1 A Quit Menu Facility


On many platforms it is sometimes dicult to stop a running Java application.
For this reason, it is useful to de ne a general purpose \Quit" menu bar facility.
The class QuitItem (Figure 13.16, on page 228) creates a listener that will
halt the running application when the associated menu item is selected. By
overloading the constructor, we make it trivial to add this functionality to any
application.
The constructor for QuitItem can be given a JMenuItem as argument. In this
case it merely attaches itself as a listener to the menu item. Alternatively, it
can be given a JMenu, in which case it creates a menu item labeled \Quit." Or
it can be given a JMenuBar, in which case it creates a new menu labeled \Quit"
that contains only the quit menu item. Finally, the constructor can be given an
13.7 The Menu Bar 239

class QuitItem implements ActionListener {

public QuitItem (JFrame application) {


JMenuBar mBar = new JMenuBar( );
application.setJMenuBar (mBar);
JMenu menu = new JMenu("Quit");
mBar.add (menu);
JMenuItem mItem = new JMenuItem("Quit");
mItem.addActionListener (this);
menu.add (mItem);
}

public QuitItem (JMenuBar mBar) {


JMenu menu = new JMenu("Quit");
mBar.add (menu);
JMenuItem mItem = new JMenuItem("Quit");
mItem.addActionListener (this);
menu.add (mItem);
}

public QuitItem (JMenu menu) {


JMenuItem mItem = new JMenuItem("Quit");
mItem.addActionListener (this);
menu.add (mItem);
}

public QuitItem (JMenuItem mItem)


{ mItem.addActionListener (this); }

public void actionPerformed (ActionEvent e)


{ System.exit(0); }
}

Figure 13.16 A general purpose QuitItem class.

application as argument, in which case it creates a new menu bar containing


only the one menu that contains only the single quit item. Using the application
constructor, a quit menu selection can be added to an application by placing
only a single line in the constructor for the application:
class ColorTest extends Frame {
.
.
.
public ColorTest ( ) {
240 THE AWT AND SWING

.
.
.
// add quit menu item to application
new QuitItem (this);
.
.
.
}
}

13.8 Chapter Summary


The Abstract Windowing Toolkit, or AWT, is the portion of the Java library
used for the creation of graphical user interfaces. The design of the AWT is
an excellent illustration of the power of object-oriented techniques. The Swing
library is an extension to the AWT that allows graphical user interfaces to
have the same look and feel across di erent platforms. In this chapter we have
described the various AWT and Swing components, and the way in which they
are used to develop user interfaces.

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 de ned?
5. How is a container di erent from other types of components?
6. What is the di erence 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 di erent 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

11. What two roles are being combined in a ButtonAdapter?


12. Show how the class ColorButton could have been written using a Button-
Adapter.
13. What is the di erence between a TextArea and a TextField?
14. What are the three di erent types of components that allow the user to
select one item out of many possibilities?
15. What is a JPanel?
16. What are the 13 prede ned values provided by class Color?
17. What do the three numerical values that de ne a color represent?
18. In what ways is a MenuBar similar to a Component? In what ways is it
di erent?

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.

You might also like