0% found this document useful (0 votes)
3 views38 pages

JavaGui 11 Chap1

The document provides an overview of the Abstract Windowing Toolkit (AWT) in Java for building graphical user interfaces (GUIs), detailing its components, event handling, and drawing methods. It covers the hierarchy of components, the Graphics class, and the importance of the paint method for rendering graphics. Additionally, it introduces practical examples, such as a scribbler demo, and discusses various control classes like Labels, Buttons, and Checkboxes.

Uploaded by

balaji.pvb
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)
3 views38 pages

JavaGui 11 Chap1

The document provides an overview of the Abstract Windowing Toolkit (AWT) in Java for building graphical user interfaces (GUIs), detailing its components, event handling, and drawing methods. It covers the hierarchy of components, the Graphics class, and the importance of the paint method for rendering graphics. Additionally, it introduces practical examples, such as a scribbler demo, and discusses various control classes like Labels, Buttons, and Checkboxes.

Uploaded by

balaji.pvb
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

Java GUIs

Chapter 1

The Abstract Windowing Toolkit

Rev. 1.1 [Link] 1-1


Copyright © 1999 William W. Provost
Java GUIs

The Abstract Windowing Toolkit

Objectives

After completing this unit you will be able to:


• Describe the use of the Abstract Windowing Toolkit
in building graphical user interfaces in Java.
• Implement a simple GUI using AWT objects and do
some simple event handling and drawing.
• Enumerate the AWT control classes and describe the
function, event sets and usage of each.
• Add a set of menus to an application’s frame window,
and implement handlers for the menu items.

Rev. 1.1 [Link] 1-2


Copyright © 1999 William W. Provost
Java GUIs

The Abstract Windowing Toolkit

• Historically, the first attempt to abstract the


behaviors and requirements of graphical user
interfaces (GUIs) in Java was the Abstract Windowing
Toolkit, or AWT.
• This body of code is held in the [Link] package and
subpackages thereof.
• The AWT is a library of classes that model graphics
and windowing functionality, including windows,
dialogs, menus, form controls and graphics.
− Many of the AWT classes map to native code and native
representations through peers.
− Therefore, in keeping with the overall philosophy of the Java
architecture, you can write GUI code once by modeling it in
AWT and run it anywhere, since the classes’ visual
representations will fall in with the standard look and feel of
the target platform.

• The JDK now includes a much more sophisticated


library called the Java Foundation Classes, or JFC
(and often still called by its code name, Swing).
− Most of these controls do not require native code to run,
since they assume the responsibilities that native code in the
AWT handlers, for instance drawing a particular widget in a
particular style.
− It is important to understand AWT first since JFC leverages
AWT concepts and classes.

Rev. 1.1 [Link] 1-3


Copyright © 1999 William W. Provost
Java GUIs

The Graphics Class

• The Graphics class encapsulates the concept of a


context in which one can render graphics.
− Generally (and for our purposes in this chapter) this means
drawing on an allocated piece of the screen.
− A more recent addition to the Core API, Graphics2D,
extends Graphics to more fully describe other contexts, such
as pieces of a page or document for printing, and to offer a
richer API for managing graphical rendering.

• We will see how an instance of Graphics can be


derived in a moment.
• Once there is such a reference, you can proceed to
draw in the represented context.
− Use methods like drawRect, drawLine, drawOval to draw
geometrically.
− Use methods like drawImage to render bitmapped graphics.
− Use methods like drawString to graphically represent text.

Rev. 1.1 [Link] 1-4


Copyright © 1999 William W. Provost
Java GUIs

The Component Hierarchy

• Windows, dialogs, and control widgets are


modeled in AWT in a hierarchy of classes
inheriting Component:

Rev. 1.1 [Link] 1-5


Copyright © 1999 William W. Provost
Java GUIs

Components

• The Component class encapsulates all the basic


qualities of a top-level or child window.
− It holds attributes for the position and size of the window.
− It offers methods for checking and manipulating some basic
aspects of a window, some of which will be re-implemented
by subclasses, some of which will only be useful for some of
the subclasses.
− Enabled/disabled state is managed at this level.
− Also at this level you control showing/hiding the element.

• All Component instances have some graphical


representation.
− Some of the component subclasses manage this for you and
provide higher-level functionality – these are the control
classes like Button, List, and TextField.
− Some do not do any rendering whatsoever, and must be
further subclassed to define their appearance.

• All Component instances can generate events


representing user actions.
− The event sets vary by subclass, and we will identify these as
we enumerate the subclasses, especially the control classes.
− Event handling in general is a fairly complex subject, enough
so that we will study it in a separate chapter later in this
module.

Rev. 1.1 [Link] 1-6


Copyright © 1999 William W. Provost
Java GUIs

Drawing on a Component

• You can obtain a graphics context based on a


Component reference at any time, and proceed to
draw on the component’s allocated screen space.
− Call getGraphics to derive a Graphics object reference.
− Any drawing that you do will be live to the component, if it
is currently showing.
Graphics context = getGraphics ();

• Any drawing you do proactively in method code will


be directly represented on the graphical element.
− However, Component has no way of duplicating your
drawing steps on demand.
− Instead, there is a system by which you can implement a
method to draw or redraw the element on demand.

Rev. 1.1 [Link] 1-7


Copyright © 1999 William W. Provost
Java GUIs

Painting a Component

• When a graphical element is obscured by another


window, and then revealed again, the windowing
system (per platform) will tell the element to redraw
itself.
− The Component class models this with a method paint,
which it calls in response to such notifications.
− Implement paint to replace any missing pieces of the
representation.

• Only drawing steps implemented in the paint method


will be executed whenever they might be needed.
• This leads to a standard strategy for graphical
representation in general: do all your drawing in the
paint method.
− This means that you must store as state elements (fields) the
information required to draw the element at any time.
− Then your paint implementation will use these data
structures, of whatever nature, to robustly represent the
graphical element.

Rev. 1.1 [Link] 1-8


Copyright © 1999 William W. Provost
Java GUIs

Scribbler Demo

• We will work through a demonstration of graphics


rendering based on a scribbler component, which will
allow the user to draw on its surface with the mouse.
• Do your work in Demos\Scribble; the completed
demo code is in Examples\Scribble\Step1.
• The starter code includes two classes:
− A frame class Scribbler that has an application method to
instantiate and show itself
− A panel class ScribblePanel that will hold the drawing and
event-handling code for the scribbling functionality

• Build and run the application in its starting form.


You will get a well-formed top-level window, but no
real use from it.

Rev. 1.1 [Link] 1-9


Copyright © 1999 William W. Provost
Java GUIs

Starter Code

• Look at the definition of the ScribblePanel class.


− The class implements event-handling interfaces
MouseListener and MouseMotionListener; we will use
these without worrying too much about them until we study
event handling in chapter 3.
− Each event-handling method is invoked in response to a
different mouse-related event.
− We will be concerned with two of these methods:
mouseDragged and mousePressed.
class ScribblePanel
extends Panel
implements MouseMotionListener,
MouseListener
{
...
public void mouseDragged (MouseEvent ev)
{
}
...
public void mousePressed (MouseEvent ev)
{
}
}

Rev. 1.1 [Link] 1-10


Copyright © 1999 William W. Provost
Java GUIs

Drawing with the Mouse

• First add fields to the class to keep the most recent


mouse coordinates: call these xLast and yLast:
private int xLast = 0;
private int yLast = 0;

• Now implement mouseDragged to draw a line in


response to the mouse dragging action.
− Get a Graphics object reference by calling getGraphics.
− Draw the line from (xLast, yLast) to the current position as
expressed in ([Link] (), [Link] ()).
− Store the new coordinates as the starting point for the next
line.
public void mouseDragged (MouseEvent ev)
{
Graphics self = getGraphics ();
[Link] (xLast, yLast,
[Link] (), [Link] ());
xLast = [Link] ();
yLast = [Link] ();
}

Rev. 1.1 [Link] 1-11


Copyright © 1999 William W. Provost
Java GUIs

Starting a Line

• Build and test your code: you will find that the
drawing works, but that each line starts from the
previous one regardless of when the mouse button
was pressed, and the first line starts by drawing a
segment from the upper-left corner.

• Implement mousePressed to initialize xLast and yLast


without drawing.
public void mousePressed (MouseEvent ev)
{
xLast = [Link] ();
yLast = [Link] ();
}

• Build and test and you should get a well-behaved


scribbler.

Rev. 1.1 [Link] 1-12


Copyright © 1999 William W. Provost
Java GUIs

Shortcomings

• Try running Scribbler and obscuring it.


− Cover all or part of the window with another window, and
then either move that window out of the way or bring the
scribbler window to the top.
− You will see that it fails to redraw the sections that were
obscured earlier.

• This is an example of the trouble you can get into if


you try to draw directly on the component context.
− The windowing system and AWT rely on the implementation
of the paint method to represent the graphical element.
− To implement paint to represent user actions gone by
requires more work, because you must capture a record of
those actions in object fields.
Rev. 1.1 [Link] 1-13
Copyright © 1999 William W. Provost
Java GUIs

Lab 1A

A Better Scribble

In this lab you will enhance an existing application that provides a


scribble pad. The starter code (which is the completion of this
chapter’s demo) has some obvious deficiencies in the way in which
it draws itself, which you will fix. You will capture user actions
(mouse dragging) in a data structure, and you will implement the
paint method to use that structure to draw the user’s drags in a
more robust way.

Suggested Time: 30 minutes

Rev. 1.1 [Link] 1-14


Copyright © 1999 William W. Provost
Java GUIs

Containers

• The Container class is a subclass of Component with


one important feature: it also holds a collection of
Components.
• This is the means by which AWT models parent-child
window hierarchies.
− Any Container subclass can have any number of child
Components.
− Since Containers are also Components, the parent-child
relationship can be nested to arbitrary depth.

Rev. 1.1 [Link] 1-15


Copyright © 1999 William W. Provost
Java GUIs

Panels

• Probably the most commonly used Container type is


the Panel.
− Panels have no graphical representation of their own except
that they erase their backgrounds to a business-forms grey.
− They are used to hold other controls, and at runtime are
essentially invisible.

• We will study GUI layout management in the next


chapter.
− We will see that layouts of AWT interfaces are not based on
hardcoded position and size dimensions, but on policies by
which child windows are placed in a container given
available space.
− These policies must often be mixed at various scopes within
what the user sees as a single window.
− Thus it is seldom workable to simply include all the child
controls directly in a window class and manage them from
there.
− This is the major motivation for the use of panels: to break a
window’s or dialog’s controls into a hierarchy of groups
based on their required layout policies.

Rev. 1.1 [Link] 1-16


Copyright © 1999 William W. Provost
Java GUIs

Top-Level Containers

• The other Container subclasses map to one sort or


another of top-level user interaction.
• The Window class provides the base for such
elements.
• The subclass Dialog models a modal or modeless
dialog box.
• The subclass Frame models a top-level window.
− This class is usually subclassed as an application’s main
window.
− Frame class code allocates a thread to handle user events;
any events received are then delegated to child controls as
necessary.
− This is why the following application does not shut down
before it can show the window: remember that the JVM will
not shut down until there are no more non-daemon threads
running.
public static void main(String args[])
{
Frame mainWindow = new Scribbler ();
[Link]();

// Application’s main thread dies at this point,


// but the frame’s own thread is still running.
}

Rev. 1.1 [Link] 1-17


Copyright © 1999 William W. Provost
Java GUIs

Controls

• We will take a brief look at each of the main control


classes in AWT.
• For each control class, we’ll cover the following:
− The basic role of the class in a GUI
− A summary of the events that this control can fire (again,
we’ll be studying event handling more thoroughly in chapter
3)
− The primary usage of the class from Java code, including
how to build it and how to query it’s state

• Note that all Components can fire many kinds of


events, including mouse events, focus events,
keyboard events, and events relating to the
functioning of the component as a window.
• We will point out only the event sets with some
unique relevance to a given control class.

Rev. 1.1 [Link] 1-18


Copyright © 1999 William W. Provost
Java GUIs

Labels

• The Label class models static text on a form or dialog.


• It fires no events other than those which are standard
for all component types.
• Build a label by providing the text to be shown, or by
providing a size (a width in characters):
new Label (“Quantity:”);
Label labelStatus = new Label (40);

• You can get or set the text in the control at any time,
so labels do not have to be entirely static.
[Link] (“She’s breaking up!”);

Rev. 1.1 [Link] 1-19


Copyright © 1999 William W. Provost
Java GUIs

Buttons

• The Button class models a pushbutton.


• It fires the ActionEvent when clicked.
• Build a button by providing its caption:
Button bnBuy = new Button ("Buy");

Rev. 1.1 [Link] 1-20


Copyright © 1999 William W. Provost
Java GUIs

Checkboxes

• The Checkbox class models check boxes and radio


buttons.
− When used alone a Checkbox instance will render and
behave as a checkbox.
− When used in conjuntion with a CheckboxGroup it will
render and behave as a radio button.

• A checkbox will fire the ItemEvent when its state


changes.
• Build a checkbox by providing its caption, and
optionally its initial state as a boolean:
Checkbox checkMD = new Checkbox
(“MD resident (no sales tax)”);

• Check the state of the checkbox with the getState


method; the checkbox is either checked (true) or
unchecked (false).

Rev. 1.1 [Link] 1-21


Copyright © 1999 William W. Provost
Java GUIs

Radio Buttons Using CheckboxGroup

• A Checkbox instance will behave as a radio button


when added to a CheckboxGroup.
− Only one element in a CheckboxGroup can be checked at a
time.
− The checkbox group manages this in collaboration with the
checkboxes.

• The CheckboxGroup does not fire any events.


• The checkboxes still fire ItemEvents, but only when
being set to the checked state. Existing code that relies
on events on any state change will see different
behavior if the checkboxes are converted to radio
buttons.
• Build radio buttons by first building a
CheckboxGroup, then building the Checkboxes with
reference to it.
CheckboxGroup group = new CheckboxGroup ();
[Link] (new Checkbox
("Normal ground", group, true));
[Link] (new Checkbox
("2-day air", group, false));
[Link] (new Checkbox
("Overnight", group, false));

Rev. 1.1 [Link] 1-22


Copyright © 1999 William W. Provost
Java GUIs

TextFields

• Single-line text editing is managed in TextField


controls.
• This class subclasses TextComponent for much of its
functionality.
• A TextField fires two types of events:
− The TextEvent every time the text in the control changes
− The ActionEvent when the return key is pressed while it has
the input focus

• Build a text field by providing the starting text, or a


size in characters, or both:
new TextField (“Default text”);
new TextField (40);
new TextField (“Start small”, 80);

• Get the text using the [Link] method.


• The TextField class provides methos to get and set
selection and caret information for the associated
control.

Rev. 1.1 [Link] 1-23


Copyright © 1999 William W. Provost
Java GUIs

TextAreas

• The TextArea class models a control with editable


multiline text.
• It also subclasses TextComponent.
• It fires only TextEvents; the return key is used to
insert linefeed characters into the control’s text.
• Build a text area by providing starting text and/or
height and width in lines and characters:
new TextArea (“Default text”);
new TextArea (4, 40);
new TextArea (“Start small”, 8, 80);

Rev. 1.1 [Link] 1-24


Copyright © 1999 William W. Provost
Java GUIs

Lists

• The List class models a listbox that can contain


strings.
• The same class is used to represent either single- or
multiple-selection modes, based on a parameter to the
constructor.
• A List fires two events:
− The ItemEvent when items in the list are selected
− The ActionEvent when an item is doubleclicked

• Build a List with no arguments, or with a number of


rows, or with a number of rows and a boolean which,
if true, makes the list support multiple selections. Use
the add method to populate the list:
List listProducts = new List (4, true);
// multiple-select
[Link] ("Lawn mower");
[Link] ("Weed whacker");
[Link] ("Fertilizer");
[Link] ("Hoe");
[Link] ("Spade");
[Link] ("Hose");

Rev. 1.1 [Link] 1-25


Copyright © 1999 William W. Provost
Java GUIs

Choice Controls

• The Choice class models a chooser control or


dropdown listbox.
• It fires the ItemEvent when the selected item changes.
• Build a Choice using the default constructor, and use
the add method to populate it with options:
Choice gifts = new Choice ();
[Link] ("Cheap alarm clock");
[Link] ("Cheap watch");
[Link] ("Cheap wallet");

Rev. 1.1 [Link] 1-26


Copyright © 1999 William W. Provost
Java GUIs

A Simple Form

• Here is the main window of the Form application in


Examples\Form, which incorporates example code
from the previous pages on various control classes.
• This is rendered on a Windows32 workstation.

• We will defer further study of building more complex


GUIs until the following chapters on layout
management and events.

Rev. 1.1 [Link] 1-27


Copyright © 1999 William W. Provost
Java GUIs

Menu Classes

• AWT models menus with a hierarchy of classes, most


deriving from MenuComponent:

Rev. 1.1 [Link] 1-28


Copyright © 1999 William W. Provost
Java GUIs

MenuItems

• The MenuItem class models an item on a menu that


has the following features:
− It has a string label.
− It fires the ActionEvent when chosen.
− It can be associated with a keyboard shortcut.

• Build a MenuItem by providing a label and possibly a


shortcut.
• The shortcut is represented by an instance of
MenuShortcut, which holds a key identifier and
possibly modifiers such as SHIFT, ALT, CTRL.
MenuItem thisColor = new MenuItem (“Red”);

Rev. 1.1 [Link] 1-29


Copyright © 1999 William W. Provost
Java GUIs

Menus

• The Menu class models an entire menu of choices,


each of which is represented by a MenuItem.
• Menu both subclasses and collects on MenuItem, a
relationship which may remind you of that between
Container and Component.
• This of course allows for parent-child hierarchies to
be developed: a menu can hold other menus which
hold menu items.
• Build a Menu and add MenuItems to it. Use the
addSeparator method to add a visual separator
between items.
Menu colorMenu = new Menu ("Color");
for (int c = 0;
c < [Link];
++c)
{
MenuItem thisColor = new MenuItem
([Link][c]);
[Link] (thisColor);
}

• The subclass PopupMenu models popup behavior.

Rev. 1.1 [Link] 1-30


Copyright © 1999 William W. Provost
Java GUIs

MenuBars

• The MenuBar class models a top-level menu that can


be associated with a Frame.
− You need a MenuBar instance to which to connect various
Menus and MenuItems.
− You can then call the Frame’s setMenuBar method to
emplace the entire structure.
− Menu bars also provide the handling for keyboard shortcuts,
however they may be assigned to child menus and items.
MenuBar bar = new MenuBar ();
[Link] (mainMenu);
[Link] (colorMenu);
setMenuBar (bar);

Rev. 1.1 [Link] 1-31


Copyright © 1999 William W. Provost
Java GUIs

Lab 1B

A Smarter Scribble

In this lab you will enhance an existing application that provides a


scribble pad. You will add features to the application via a new
menu bar, including the ability to erase the pad, and selection of
line color.

Suggested Time: 30 minutes

Rev. 1.1 [Link] 1-32


Copyright © 1999 William W. Provost
Java GUIs

Summary

• The Abstract Windowing Toolkit provides a model


for building portable graphical user interfaces.
• The Component-Container relationship models
hierarchies of parent and child windows.
• The control classes model various widgets and
window types for building application forms and
dialogs.
• Menus are modeled in a simple fashion with the
MenuComponent hierarchy.
• To complete the picture, more or less literally, we will
need to understand how to effectively place these
various elements onscreen, which is the subject of the
next chapter.
• Once we have a good visual presentation, we will
want to make the GUI do something useful, which
means handling user events, which is the subject of
the third chapter of this module.

Rev. 1.1 [Link] 1-33


Copyright © 1999 William W. Provost
Java GUIs

Lab 1A

A Better Scribble

Introduction

In this lab you will enhance an existing application that provides a scribble pad. The
starter code (which is the completion of this chapter’s demo) has some obvious
deficiencies in the way in which it draws itself, which you will fix. You will capture user
actions (mouse dragging) in a data structure, and you will implement the paint method to
use that structure to draw the user’s drags in a more robust way.

Suggested Time: 30 minutes

Directories: Labs\JavaMod4Lab1A (do your work here)


Examples\Scribble\Step1 (backup copy of starter files)
Examples\Scribble\Step2 (answer)

Files: [Link]

Packages: [Link]

Instructions
1. Review the existing application code. The single source file holds a public frame
class and a non-public panel class, where most of the action occurs. Build and test
the starter application. Try drawing a few lines with the mouse. Then drag another
window over the scribble pad, and take it away again. You will notice that the
uncovered region of the pad is left blank, which is not the way windowed applications
are supposed to behave. Close the running application.

2. Look at the event handlers implemented by ScribblePanel. In mouseDragged a new


line is drawn, using a Graphics context derived on the fly, and the coordinates of the
drag are saved as the starting point for the next line. In mousePressed the
coordinates are set but no line is drawn. Simple enough, but when repainting is
necessary all this is lost, because no record is kept of the drawing and no paint
implementation is in place to use such a record.

3. Add a private member drawings to ScribblePanel, of type LinkedList. This will


actually be a list of lists of points. Remember to initialize it to a new instance! You
will also need to add an import directive to the source file at this point, for package
[Link].

Rev. 1.1 [Link] 1-34


Copyright © 1999 William W. Provost
Java GUIs

4. Add another private member currentDrawing, also of type LinkedList. This will
refer to the most recent list in drawings, so that it will not be necessary to seek to the
tail of that list each time a new point has to be added. Initialize currentDrawing to
null.

5. Remove the definitions for fields xLast and yLast.

6. Reimplement mousePressed to assign currentDrawing to a new LinkedList


instance, and to add it to drawings. Then call mouseDragged directly, providing the
event parameter received by this method.

7. Reimplement mouseDragged to create an instance of Point (package [Link],


which is already imported) on the coordinates found in the event object. Add this
point to currentDrawing, then call repaint. You may want to build at this point to
check your work. If you run the resulting application, it should behave just fine but
you won’t see any drawing on the screen yet.

8. Now add an override of the paint method: void, taking a Graphics parameter. The
logic here is fairly straightforward: for each list in drawings, set up a lastPoint
object that begins its life as null, then iterate through the points in the drawing. For
all but the first point in the drawing, draw a line from lastPoint to the current point,
and save off the current point as lastPoint every time. (There are several approaches
to the flow control here, choose whatever looping construct and boundary conditions
suit you.) Rebuild and test, and you should see that the application draws properly,
and now can withstand being obscured and shown again, since it will always redraw
on demand.

Rev. 1.1 [Link] 1-35


Copyright © 1999 William W. Provost
Java GUIs

Lab 1B

A Smarter Scribble

Introduction

In this lab you will enhance an existing application that provides a scribble pad. You will
add features to the application via a new menu bar, including the ability to erase the pad,
and selection of line color.

Suggested Time: 30 minutes

Directories: Labs\JavaMod4Lab1 (do your work here)


Examples\Scribble\Step2 (backup copy of starter files)
Examples\Scribble\Step3 (answer)

Files: [Link]

Packages: [Link]

Instructions
1. Now you will add a menu bar to the Scribbler frame. In the constructor, create a
MenuItem with the text “Erase”. Create a Menu called “Action” and add the menu
item to it. Create a MenuBar, add the menu to that, and add it to the frame using
setMenuBar. Build and test – you should see the menu in place but of course
nothing happens when you make a choice.

2. There is a handler for the erase method already stubbed out in the ScribblePanel
class. Add a new instance of it as an ActionListener to the erase menu item (the
strange syntax is what’s required to create an instance of an inner class from outside
the enclosing object):
[Link] ([Link] EraseHandler ());

3. Find the EraseHandler class and implement actionPerformed to erase the drawings.
This simply means clearing out the drawings collection (call the method clear), and
resetting currentDrawing to null. Then call repaint. (Remember that this is
possible because inner objects automatically have visibility to their outer object’s
fields and methods.) Rebuild and test, and you should see the erase menu item
working.

Rev. 1.1 [Link] 1-36


Copyright © 1999 William W. Provost
Java GUIs

4. Now add a color selection menu to the menu bar. Create a new Menu in the
Scribbler constructor. The color names that the ScribblePanel can understand,
along with the corresponding Colors, are already primed into the starter code. There
is also a stub handler, so now create a new instance of ColorHandler (same syntax as
for the EraseHandler) and hold that one instance locally. Loop over the static array
[Link] and for each, create a MenuItem, add the handler as an
ActionListener, and add the item to the menu. Then add the menu to the menu bar.
Rebuild and test to see that your menu is in place.

5. Add a private member lineColor to ScribblePanel, type Color. Initialize it to


[Link].

6. In the paint method, before any other code, call the graphics object’s setColor
method, passing lineColor. (You can test this much by initializing the color to
something other than black; when you test you should get your chosen line color.)

7. Implement [Link] to set the new color. Since many menu


items are firing events to this one handler, you must first determine which menu item
you are dealing with. Get the event source, convert to a menu item, and get the label
of that item into a local string:
String colorName = ((MenuItem) [Link] ()).getLabel ();

8. To complete the method implementation, iterate again over colorNames (you won’t
need to qualify it with the class name this time) and compare each element to the
menu label you’ve derived. When you get a hit, use the index to get a color out of the
colors array and assign it to lineColor. Call repaint to show the new color. Build
and test.

Rev. 1.1 [Link] 1-37


Copyright © 1999 William W. Provost
Java GUIs

Rev. 1.1 [Link] 1-38


Copyright © 1999 William W. Provost

You might also like