Tải bản đầy đủ (.pdf) (20 trang)

Java Programming for absolute beginner- P16 docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (433.82 KB, 20 trang )

The output for this application is shown in Figure 7.14. Within the itemState-
Changed(ItemEvent)
method, two string objects are built based on which event
occurred. The
getStateChange() method determines whether the item was
selected or deselected by comparing the returned value to
ItemEvent.SELECTED or
ItemEvent.DESELECTED. The program then obtains the value of the item depend-
ing on what type of component it is. The
getItem() method in the ItemEvent
class returns an Object object that represents the item that triggered the event.
For the
Checkbox and the Choice, this works out great because the object
returned is a string that can be added to the
"Event:" string. For the List, how-
ever, I had to use the code:
list.getItem(((Integer)e.getItem()).intValue())
258
J
a
v
a
P
r
o
g
r
am
m
i
n


g
f
o
r t
h
e A
b
s
o
l
ut
e B
e
gi
n
n
e
r
because e.getItem() returns the Integer index of the List item that was either
selected or deselected. I had to explicitly cast it to an
Integer object and call its
intValue() method, which returns an int type value of the Integer object. Then
I had to take that
int value and pass it into list.getItem(int) so that I could get
the
String value of the List item. Table 7.8 lists some of the more common Ite-
mEvent
fields and methods.
FIGURE 7.14
ItemEvents are

triggered by
Checkboxes,
Choices, and
Lists.
Field or Method Description
int DESELECTED Signifies that the ItemEvent occurred because an item was
deselected.
int SELECTED Signifies that the ItemEvent occurred because an item was
selected.
int getStateChange() Returns a value, either ItemEvent.DESELECTED or
ItemEvent.SELECTED depending on what type of state change is
associated with this
ItemEvent.
Object getItem() Returns an Object that represents the item whose state changed.
TABLE 7.8
I
TEM
E
VENT
F IELDS AND M ETHODS
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 258
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Handling AdjustmentEvents
The AdjustmentListener interface listens for AdjustmentEvents, which are trig-
gered by objects that are adjustable, such as the
Scrollbar component. Adjust-
mentListener
has only one method, adjustmentValueChanged(AdjustmentEvent),
which is invoked when the value of an adjustable object is changed, as you can

probably guess from the name of the method. The
AdjustmentTest application
tests this:
/*
* AdjustmentTest
* Demonstrates the AdjustmentListener Interface on a scroll bar
*/
import java.awt.*;
import java.awt.event.*;
public class AdjustmentTest extends GUIFrame
implements AdjustmentListener {
Scrollbar bar;
Label minimum, maximum, current;
public AdjustmentTest() {
super("AdjustmentListener Test");
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
int min = 0, max = 100, curr = 50;
setLayout(gridbag);
minimum = new Label(String.valueOf(min), Label.RIGHT);
gridbag.setConstraints(minimum, constraints);
add(minimum);
bar = new Scrollbar(Scrollbar.HORIZONTAL, curr, 1, min, max + 1);
constraints.ipadx = 200;
gridbag.setConstraints(bar, constraints);
bar.addAdjustmentListener(this);
add(bar);
maximum = new Label(String.valueOf(max));
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.ipadx = 0;

gridbag.setConstraints(maximum, constraints);
add(maximum);
current = new Label(String.valueOf(curr), Label.CENTER);
gridbag.setConstraints(current, constraints);
add(current);
setSize(300, 150);
setVisible(true);
}
259
C
h
a
p
t
e
r 7 A
d
v
a
n
c
e
d
G
U
I
:
L
a
y

o
u
t
M
a
n
a
g
e
r
s
a
n
d
E
v
e
n
t
H
a
n
d
l
i
n
g
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 259
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

public static void main(String args[]) {
new AdjustmentTest();
}
public void adjustmentValueChanged(AdjustmentEvent e) {
current.setText(String.valueOf(e.getValue()));
}
}
This application is fairly straightforward. It creates a Scrollbar and some Labels
that represent the
Scrollbar’s minimum, maximum, and current values. The
adjustmentValueChanged(AdjustmentEvent) method updates the current value
of the
Scrollbar by calling e.getValue(). You can see the output in Figure 7.15.
Table 7.9 shows some useful fields and methods of the
AdjustmentEvent class.
260
J
a
v
a
P
r
o
g
r
am
m
i
n
g

f
o
r t
h
e A
b
s
o
l
ut
e B
e
gi
n
n
e
r
Field or Method Description
int BLOCK_DECREMENT Block decrement adjustment type.
int BLOCK_INCREMENT Block increment adjustment type.
int TRACK Absolute tracking adjustment type.
int UNIT_DECREMENT Unit decrement adjustment type.
int UNIT_INCREMENT Unit increment adjustment type.
int getAdjustmentType() Returns the int representation of the adjustment type.
int getValue() Returns the int current value of the adjustable object.
FIGURE 7.15
You use the
Adjustment-
Listener
interface

to determine when
a
Scrollbar value
is being changed.
TABLE 7.9
A
DJUSTMENT
E
VENT
F IELDS AND M ETHODS
Handling TextEvents
TextEvents are generated by high-level objects such as text components. The
TextComponent class has the addTextListener(TextListener) method, and both
TextField and TextArea are subclasses of TextComponent. The TextListener inter-
face has only one method,
textValueChanged(TextEvent). This method is
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 260
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
invoked any time the value of the text is changed, such as when text is added or
deleted. The
TextTest application implements the TextListener interface to
copy what you are typing into a
TextField. Here is the source code for
TextTest.java:
/*
* TextTest
* Demonstrates the TextListener interface
*/
import java.awt.*;

import java.awt.event.*;
public class TextTest extends GUIFrame
implements TextListener {
TextField text;
TextField copyCat;
public TextTest() {
super("TextListener Test");
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
setLayout(gridbag);
constraints.gridwidth = GridBagConstraints.REMAINDER;
text = new TextField(25);
gridbag.setConstraints(text, constraints);
text.addTextListener(this);
add(text);
copyCat = new TextField(25);
copyCat.setEnabled(false);
gridbag.setConstraints(copyCat, constraints);
add(copyCat);
setSize(300, 150);
setVisible(true);
}
public static void main(String args[]) {
new TextTest();
}
public void textValueChanged(TextEvent e) {
copyCat.setText(text.getText());
}
}
This application simply creates two TextField objects, text and copyCat. text is

the
TextField that the user will be typing into. copyCat is a disabled TextField
that will mimic the value of text each time its text value changes. You can see
the
TextListenerTest application in Figure 7.16.
261
C
h
a
p
t
e
r 7 A
d
v
a
n
c
e
d
G
U
I
:
L
a
y
o
u
t

M
a
n
a
g
e
r
s
a
n
d
E
v
e
n
t
H
a
n
d
l
i
n
g
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 261
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Handling MouseEvents
Your computer’s mouse triggers MouseEvents. There are two types of mouse
events. There are mouse motion events that are triggered by moving your mouse

and regular mouse events that are triggered by clicking your mouse buttons or
by moving your mouse into or out of a listener’s area. These two types of events
have two listener classes:
MouseListener, which listens for mouse button trig-
gered events and entry and exit events, and
MouseMotionListener, which listens
for the motion (change in pointer location) of your mouse and also dragging
(mouse moved while button is down) events.
MouseInputListener of the javax.swing.event package, which is
not covered in this book, is a subinterface of both
MouseListener and
MouseMotionListener, so you can implement MouseInputListener
and add it using addMouseListener(MouseListener) or
addMouseMotionListener(MouseMotionListener), or both, to listen
to any of these types of
MouseEvents.
The MouseTest application implements both MouseListener and MouseMotion-
Listener
interfaces to capture MouseEvents. Here is the source code for
MouseTest.java:
/*
* MouseTest
* Demonstrates the MouseListener and MouseMotionListener interfaces
*/
import java.awt.*;
import java.awt.event.*;
public class MouseTest extends GUIFrame
implements MouseListener, MouseMotionListener {
Canvas canvas;
Label location, event;

public MouseTest() {
super("Mouse Event Test");
canvas = new Canvas();
canvas.setBackground(Color.white);
canvas.setSize(450, 450);
TRICK
262
J
a
v
a
P
r
o
g
r
am
m
i
n
g
f
o
r t
h
e A
b
s
o
l

ut
e B
e
gi
n
n
e
r
FIGURE 7.16
This application
copies your text as
you write it and
displays it below.
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 262
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
canvas.addMouseListener(this);
canvas.addMouseMotionListener(this);
add(canvas, BorderLayout.CENTER);
Panel infoPanel = new Panel();
infoPanel.setLayout(new GridLayout(0, 2, 10, 0));
location = new Label("Location:");
infoPanel.add(location);
event = new Label("Event:");
infoPanel.add(event);
add(infoPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
public static void main(String args[]) {

new MouseTest();
}
//The five MouseListener methods
public void mouseClicked(MouseEvent me) {
String text = "Event: Clicked Button ";
switch(me.getModifiers()) {
case (InputEvent.BUTTON1_MASK):
text += "1";
break;
case (InputEvent.BUTTON2_MASK):
text += "2";
break;
case (InputEvent.BUTTON3_MASK):
text += "3";
break;
default:
text += "?";
}
text += " (" + me.getClickCount() + "x)";
event.setText(text);
}
public void mouseEntered(MouseEvent me) {
event.setText("Event: Entered");
}
public void mouseExited(MouseEvent me) {
event.setText("Event: Exited");
}
public void mousePressed(MouseEvent me) {
event.setText("Event: Pressed");
}

263
C
h
a
p
t
e
r 7 A
d
v
a
n
c
e
d
G
U
I
:
L
a
y
o
u
t
M
a
n
a
g

e
r
s
a
n
d
E
v
e
n
t
H
a
n
d
l
i
n
g
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 263
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
public void mouseReleased(MouseEvent me) {
event.setText("Event: Released");
}
//The two MouseMotionListener methods
public void mouseMoved(MouseEvent me) {
Point p = me.getPoint();
location.setText("Location: (" + p.x + ", " + p.y + ")");
}

public void mouseDragged(MouseEvent me) {
Point p = me.getPoint();
event.setText("Event: Dragged");
location.setText("Location: (" + p.x + ", " + p.y + ")");
}
}
The MouseTest object adds itself as a MouseListener and a MouseMotionListener to
the
Canvas, canvas. It overrides the listener methods to display on-screen the cur-
rent location of the mouse cursor as well as the current event.
MouseEvent meth-
ods are summarized in Table 7.10, and
MouseListener and MouseMotionListener
methods are summarized in Table 7.11. I overrode the MouseListener methods as
follows: The
mouseClicked(MouseEvent) method updates the event Label as to
which button was clicked by testing the value returned by
getModifiers() against
the static variables
InputEvent.BUTTON1_MASK, InputEvent.BUTTON2_MASK, and
InputEvent.BUTTON3_MASK. This method also counts the clicks for the events. A
double-click, for example, will show up as (2x). This number is obtained by getting
the
getClickCount() method of the MouseEvent class, which returns an int value
of the number of times the mouse button was successively clicked. The
mouseEn-
tered(MouseEvent)
, mouseExited(MouseEvent), mousePressed(MouseEvent), and
mouseReleased(MouseEvent) methods just update the event Label, indicating
which event occurred.

264
J
a
v
a
P
r
o
g
r
am
m
i
n
g
f
o
r t
h
e A
b
s
o
l
ut
e B
e
gi
n
n

e
r
Method Description
int getClickCount() Returns the number of successive mouse clicks.
Point getPoint() Returns a Point that represents the cursor location relative to the
source component.
int getX() Returns the horizontal portion of the location point.
int getY() Returns the vertical portion of the location point.
TABLE 7.10
M
OUSE
E
VENT
M ETHODS
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 264
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
I updated the MouseMotionListener method mouseMoved(MouseEvent) to update
the current location of the mouse cursor, and the
mouseDragged(MouseEvent)
method to update the current event to indicate the mouse is being dragged and
also to update the current location of the mouse cursor. Figure 7.17 shows the
output where I double-clicked mouse button 1 at location (277, 151). The location
returned by
getLocation() is a Point object. The Point class maintains two pub-
lic variables
x and y, which represent a point. There are some methods associated
with the class, but basically, for your purposes, it’s just that simple.
Handling KeyEvents
KeyEvents are triggered by keyboard actions performed by the users. The KeyLis-

tener
interface defines three methods, shown in Table 7.12. The addKeyLis-
tener(KeyListener)
method is defined in the Component class, so all components
can process
KeyEvents. The KeyEvent class has an insane number of static integers
that represent each of the possible keys of different types of keyboards. There are
265
C
h
a
p
t
e
r 7 A
d
v
a
n
c
e
d
G
U
I
:
L
a
y
o

u
t
M
a
n
a
g
e
r
s
a
n
d
E
v
e
n
t
H
a
n
d
l
i
n
g
Method Listener Description
void mouseClicked(MouseEvent) MouseListener Invoked when a mouse
clicks (is pressed, and then
released) on a component.

void mouseEntered(MouseEvent) MouseListener Invoked when the mouse
cursor enters the source
component’s area.
void mouseExited(MouseEvent) MouseListener Invoked when the mouse
cursor exits the source
component’s area.
void mousePressed(MouseEvent) MouseListener Invoked when the mouse
button is pressed down.
void mouseReleased(MouseEvent) MouseListener Invoked when the mouse
button is released.
void mouseMoved(MouseEvent) MouseMotionListener Invoked when the mouse
moves while within a
component’s area.
void mouseDragged(MouseEvent) MouseMotionListener Invoked when the mouse
moves while the mouse
button is down while within
a component’s area.
TABLE 7.11
M
OUSE
L
ISTENER
AND
M
OUSE
M
OTION
L
ISTENER
M ETHODS

JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 265
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
too many to list here. Refer to the JDK 1.3 documentation of the KeyEvent class
for a full list. Basically, these constants start with the letters
VK (which stand for
virtual key codes) followed by an underscore and a string representation of the
key. For instance, the keyboard keys are represented by the constants
KeyEvent.VK_A through KeyEvent.VK_Z, and the arrow keys are KeyEvent.VK_UP,
KeyEvent.VK_DOWN, KeyEvent.VK_LEFT, and KeyEvent.VK_RIGHT. The more impor-
tant
KeyEvent methods are listed in Table 7.13.
The keyTyped(KeyEvent) method is only invoked by keys that generate valid
characters, such as alpha characters and numerical characters. Even the Esc
key generates a valid character. Experiment with the
KeyTest application and
see which keys do and do not update the “Last Typed:” field. Another thing to
note is that holding a key down can sometimes generate multiple key typed
events without ever generating a key release event if a keyboard is enabled with
auto-repeat.
HINT
266
J
a
v
a
P
r
o
g

r
am
m
i
n
g
f
o
r t
h
e A
b
s
o
l
ut
e B
e
gi
n
n
e
r
FIGURE 7.17
Listening to
MouseEvents
allows you to know
what the user is
doing with the
mouse.

Method Description
void keyPressed(KeyEvent) Invoked when a key is pressed down.
void keyReleased(KeyEvent) Invoked when a key is released.
void keyTyped(KeyEvent) Invoked when a key is typed.
TABLE 7.12
K
EY
L
ISTENER
M ETHODS
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 266
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
The KeyTest application tests the handling of KeyEvents. Basically, it adds a
KeyListener, which is itself, to a TextArea, textArea, and updates three labels
with either pressed, released, or typed events. It gets the text representation of
the key by first calling the
getKeyCode() method of the KeyEvent class and pass-
ing it into the
getKeyText(int) method. In the keyPressed(KeyEvent) method,
the
lastPressed variable is displayed when the keyTyped(KeyEvent) method is
called. This is done in the
keyPressed(KeyEvent) method instead of in the key-
Typed(KeyEvent)
method because key typed events always return VK_UNDEFINED
when getKeyCode() is called. Here is the source listing of KeyTest.java. Sample
output is shown in Figure 7.18.
/*
* KeyTest

* Demonstrates handling key events
*/
import java.awt.*;
import java.awt.event.*;
public class KeyTest extends GUIFrame
implements KeyListener {
TextArea textArea;
Label pressed, released, typed;
String lastPressedText;
public KeyTest() {
super("KeyListener Test");
textArea = new TextArea(10, 30);
textArea.addKeyListener(this);
add(textArea, BorderLayout.CENTER);
Panel infoPanel = new Panel();
infoPanel.setLayout(new GridLayout(3, 0, 0, 10));
pressed = new Label("Last Pressed: <none>");
267
C
h
a
p
t
e
r 7 A
d
v
a
n
c

e
d
G
U
I
:
L
a
y
o
u
t
M
a
n
a
g
e
r
s
a
n
d
E
v
e
n
t
H
a

n
d
l
i
n
g
Method Description
char getKeyChar() Returns the character associated with the key.
int getKeyCode() Returns an integer representation of the key.
String getKeyModifiersText(int) Returns a String representation of the modifier keys
such as Ctrl based on the given integer
representation of the modifiers.
String getKeyText(int) Returns a String representation of a key based on
the given key code.
TABLE 7.13
K
EY
E
VENT
M ETHODS
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 267
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
infoPanel.add(pressed);
released = new Label("Last Released: <none>");
infoPanel.add(released);
typed = new Label("Last Typed: <none>");
infoPanel.add(typed);
add(infoPanel, BorderLayout.SOUTH);
pack();

setVisible(true);
}
public static void main(String args[]) {
new KeyTest();
}
public void keyPressed(KeyEvent e) {
lastPressedText = e.getKeyModifiersText(e.getModifiers())
+ " " + KeyEvent.getKeyText(e.getKeyCode());
pressed.setText("Last Pressed: "
+ KeyEvent.getKeyText(e.getKeyCode()));
}
public void keyReleased(KeyEvent e) {
released.setText("Last Released: "
+ KeyEvent.getKeyText(e.getKeyCode()));
}
public void keyTyped(KeyEvent e) {
typed.setText("Last Typed: " + lastPressedText);
}
}
268
J
a
v
a
P
r
o
g
r
am

m
i
n
g
f
o
r t
h
e A
b
s
o
l
ut
e B
e
gi
n
n
e
r
FIGURE 7.18
Implementing the
KeyListener
interface lets you
know when the
users are using the
keyboard.
Getting Back to the AdvancedMadLib
Application

The AdvancedMadLib application uses much of what you have learned in this
chapter. It uses layout managers to lay out its components, including a
CardLay-
out
. It also uses event handling to cause events for buttons that are pressed, or
selections made from a
Choice menu. Let’s get ready to rumble!
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 268
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Creating the MadInputPanel Class
The MadInputPanel class is responsible for all user text input. It has three Panels,
which are laid out by the
CardLayout layout manager. Each Panel gets its own
type of input. One is for obtaining nouns, one is for obtaining verbs, and the last
one is for obtaining all other types of words. Each card has its own array of
TextFields: nFields for nouns, vFields for verbs, and oFields for other fields.
Each card lays out its components using a
GridBagLayout manager. This process
is facilitated by the private method
addComponent(Panel, Component); it is basi-
cally there to reduce the number of lines in the source code and keep it from get-
ting too confusing. It sets the
GridBagConstraints to the passed in component
and then adds the component to the passed in
Panel. It also has two public meth-
ods that traverse through the cards, called
previous() and next(). Another
method,
show(String), shows a specific card based on its String name—Nouns,

Verbs, or Other.
Similar to the
MadDialog class from the previous chapter, the MadInputPanel
class has a String[] getStringArray() method that returns the values of its
TextFields in the order that they should be inserted into the story. It also
implements it in a similar way. It creates a
Vector, copies it into an array of
Strings, and returns it to the caller. The source listing for MadInputPanel.java
is as follows:
/*
* MadInputPanel
* The AdvancedMadLib game's input panel.
* All input is accepted here
*/
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
public class MadInputPanel extends Panel {
protected GridBagLayout gridbag;
protected GridBagConstraints constraints;
protected CardLayout cards;
protected Panel nouns, verbs, others;
protected TextField[] nFields, vFields, oFields;
public MadInputPanel() {
super();
gridbag = new GridBagLayout();
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
cards = new CardLayout();
setLayout(cards);

269
C
h
a
p
t
e
r 7 A
d
v
a
n
c
e
d
G
U
I
:
L
a
y
o
u
t
M
a
n
a
g

e
r
s
a
n
d
E
v
e
n
t
H
a
n
d
l
i
n
g
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 269
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
//Nouns
nouns = new Panel();
nouns.setLayout(gridbag);
addComponent(nouns, new Label("Enter some nouns:"));
nFields = new TextField[8];
//put all noun fields in the second column
constraints.gridx = 1;
constraints.gridy = GridBagConstraints.RELATIVE;

for (int n=0; n < nFields.length; n++) {
nFields[n] = new TextField(20);
addComponent(nouns, nFields[n]);
}
add("Nouns", nouns);
//Verbs
verbs = new Panel();
verbs.setLayout(gridbag);
constraints.gridx = constraints.gridy = 0;
addComponent(verbs, new Label("Enter some verbs:"));
vFields = new TextField[8];
//put all verb Fields in the second column
constraints.gridx = 1;
constraints.gridy = GridBagConstraints.RELATIVE;
for (int v=0; v < vFields.length; v++) {
vFields[v] = new TextField(20);
addComponent(verbs, vFields[v]);
}
//add other field descriptions.
constraints.gridx = 2;
constraints.gridy = 4;
addComponent(verbs, new Label("(ends with \"ing\")"));
constraints.gridy = GridBagConstraints.RELATIVE;
addComponent(verbs, new Label("(ends with \"ing\")"));
addComponent(verbs, new Label("(past tense)"));
addComponent(verbs, new Label("(present tense)"));
add("Verbs", verbs);
//Other Fields
others = new Panel();
others.setLayout(gridbag);

constraints.gridx = GridBagConstraints.RELATIVE;
constraints.gridy = GridBagConstraints.RELATIVE;
addComponent(others, new Label("Enter affectionate nicknames:"));
oFields = new TextField[7];
//create Other text fields, but don't lay them out yet
for (int o=0; o < oFields.length; o++) {
oFields[o] = new TextField(20);
}
addComponent(others, oFields[0]);
constraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent(others, oFields[1]);
constraints.gridwidth = 1;
270
J
a
v
a
P
r
o
g
r
am
m
i
n
g
f
o
r t

h
e A
b
s
o
l
ut
e B
e
gi
n
n
e
r
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 270
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
addComponent(others, new Label("Enter adjectives:"));
addComponent(others, oFields[2]);
constraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent(others, oFields[3]);
constraints.gridwidth = 1;
addComponent(others, new Label("Enter a preposition:"));
constraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent(others, oFields[4]);
constraints.gridwidth = 1;
addComponent(others, new Label("Enter a body part:"));
constraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent(others, oFields[5]);
constraints.gridwidth = 1;

addComponent(others, new Label("Enter a location:"));
addComponent(others, oFields[6]);
add("Other", others);
}
private void addComponent(Panel p, Component c) {
gridbag.setConstraints(c, constraints);
p.add(c);
}
public void previous() {
cards.previous(this);
}
public void next() {
cards.next(this);
}
public void show(String panel) {
cards.show(this, panel);
}
public String[] getStringArray() {
String[] s;
Vector v = new Vector();
v.add(vFields[0].getText()); v.add(vFields[0].getText());
v.add(vFields[0].getText()); v.add(oFields[0].getText());
v.add(vFields[1].getText()); v.add(oFields[2].getText());
v.add(nFields[0].getText());
v.add(vFields[0].getText()); v.add(vFields[0].getText());
v.add(vFields[0].getText()); v.add(oFields[0].getText());
v.add(vFields[2].getText()); v.add(oFields[5].getText());
v.add(vFields[4].getText());
v.add(vFields[4].getText()); v.add(oFields[6].getText());
v.add(vFields[3].getText()); v.add(oFields[1].getText());

v.add(nFields[1].getText()); v.add(oFields[3].getText());
v.add(nFields[2].getText());
v.add(vFields[3].getText()); v.add(oFields[1].getText());
v.add(vFields[6].getText()); v.add(vFields[5].getText());
v.add(vFields[3].getText()); v.add(oFields[1].getText());
271
C
h
a
p
t
e
r 7 A
d
v
a
n
c
e
d
G
U
I
:
L
a
y
o
u
t

M
a
n
a
g
e
r
s
a
n
d
E
v
e
n
t
H
a
n
d
l
i
n
g
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 271
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
v.add(oFields[4].getText()); v.add(nFields[3].getText());
v.add(vFields[3].getText()); v.add(oFields[1].getText());
v.add(nFields[4].getText()); v.add(nFields[5].getText());

v.add(vFields[3].getText()); v.add(oFields[1].getText());
v.add(nFields[6].getText()); v.add(vFields[7].getText());
v.add(nFields[7].getText());
v.add(vFields[3].getText()); v.add(oFields[1].getText());
v.add(vFields[0].getText()); v.add(vFields[0].getText());
v.add(vFields[0].getText()); v.add(oFields[0].getText());
v.add(vFields[1].getText()); v.add(oFields[2].getText());
v.add(nFields[0].getText());
v.add(vFields[0].getText()); v.add(vFields[0].getText());
v.add(vFields[0].getText()); v.add(oFields[0].getText());
v.add(vFields[2].getText()); v.add(oFields[5].getText());
v.add(vFields[4].getText());
v.add(vFields[4].getText()); v.add(oFields[6].getText());
s = new String[v.size()];
v.copyInto(s);
return s;
}
}
Creating the AdvancedMadLib Application
The AdvancedMadLib application is the heart of this game. It extends GUIFrame
and uses the default layout manager, BorderLayout. It creates a MadInputPanel
object, inputPanel, and adds it at BorderLayout.CENTER. It also creates a Panel,
navPanel, which it adds the prev, next, and showStory buttons to. It also adds a
Choice called inputChoice. To the prev Button, an ActionListener is added so
that when it is clicked, the previous card of
inputPanel is displayed. Oppositely,
to the
next Button, an ActionListener is added so that when it is clicked the
next card is shown by calling its
next() method. The inputChoice menu is set up

with items that represent the names of
inputPanel’s cards. An ItemListener is
added to it so that when an
Item is chosen, the corresponding card is shown by
calling:
inputPanel.show((String)e.getItem());
The showStory button calls up the Dialog, storyDialog. Before calling up the
storyDialog window, the private createStory() method builds the story using
an array of
String segments that represent the segments of the story. It merges
these segments with the segments returned by the
getStringArray() method of
the
MadInputPanel class. Once the story is displayed, you can change the values
of the text and redisplay the story as many times as you want. Here is the source
listing for
AdvancedMadLib.java:
272
J
a
v
a
P
r
o
g
r
am
m
i

n
g
f
o
r t
h
e A
b
s
o
l
ut
e B
e
gi
n
n
e
r
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 272
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
/*
* AdvancedMadLib
* A MadLib Application that demonstrates layout managers and events
*/
import java.awt.*;
import java.awt.event.*;
public class AdvancedMadLib extends GUIFrame {
Panel navPanel;

MadInputPanel inputPanel;
Button prev, next, showStory;
Choice inputChoice;
Dialog storyDialog;
TextArea story;
public AdvancedMadLib() {
super("Create your own Song");
//Card Panel (contains other panels in a CardLayout)
inputPanel = new MadInputPanel();
add(inputPanel, BorderLayout.CENTER);
//Navigation Panel
navPanel = new Panel();
navPanel.setLayout(new GridLayout(0, 4, 10, 0));
prev = new Button("<- Prev");
prev.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
inputPanel.previous();
}
});
navPanel.add(prev);
inputChoice = new Choice();
inputChoice.add("Nouns");
inputChoice.add("Verbs");
inputChoice.add("Other");
inputChoice.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
inputPanel.show((String)e.getItem());
}
});
navPanel.add(inputChoice);

next = new Button("Next ->");
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
inputPanel.next();
}
});
navPanel.add(next);
showStory = new Button("Show/Refresh Story");
273
C
h
a
p
t
e
r 7 A
d
v
a
n
c
e
d
G
U
I
:
L
a
y

o
u
t
M
a
n
a
g
e
r
s
a
n
d
E
v
e
n
t
H
a
n
d
l
i
n
g
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 273
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

showStory.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
createStory();
storyDialog.setVisible(true);
}
});
navPanel.add(showStory);
add(navPanel, BorderLayout.SOUTH);
storyDialog = new Dialog(this, "Your Song");
storyDialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
storyDialog.setVisible(false);
}
});
story = new TextArea("", 27, 50);
story.setEditable(false);
storyDialog.add(story);
storyDialog.pack();
pack();
setVisible(true);
}
public static void main(String args[]) {
new AdvancedMadLib();
}
private void createStory() {
String song = "";
String[] segs = {", ", ", ", " my ", "\nDon't ", " a ", " ",
"\n", ", ", ", ", " my ", "\nJust ", " your pretty ",
"\nI'll be ", " you again \nI'll be ", " you in ",
"\n\nDon't ", " to me oh ",

"\nYour ", "'s in a ", " ",
", yeah \nDon't ", " to me oh ",
"\nShould have ", " it a-",
" on\nDon't ", " to me oh ",
"\nI don't know it was ", " your ",
"\nDon't ", " to me oh ",
"\nDead-end ", " for a dead-end ",
"\nDon't ", " to me oh ",
"\nNow your ", " ", " on the ",
"\nDon't ", " to me oh ",
"\n\n", ", ", ", ", " my ", "\nDon't ", " a ", " ",
"\n", ", ", ", ", " my ", "\nJust ", " your pretty ",
"\nI'll be ", " you again \nI'll be ", " you in "};
String[] s = inputPanel.getStringArray();
for (int i = 0; i < segs.length; i++) {
song += s[i] + segs[i];
}
274
J
a
v
a
P
r
o
g
r
am
m
i

n
g
f
o
r t
h
e A
b
s
o
l
ut
e B
e
gi
n
n
e
r
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 274
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
song += s[s.length - 1];
story.setText(song);
}
}
Summary
In this chapter, you learned all about layout managers, including FlowLayout,
GridLayout, BorderLayout, GridBagLayout, and CardLayout. You also learned how
to handle GUI events using the

java.awt.event package. You can now handle
ActionEvents, WindowEvents, FocusEvents, ItemEvents, AdjustmentEvents, Tex-
tEvent
s, MouseEvents, and KeyEvents. In the next chapter, you learn all about
applets.
275
C
h
a
p
t
e
r 7 A
d
v
a
n
c
e
d
G
U
I
:
L
a
y
o
u
t

M
a
n
a
g
e
r
s
a
n
d
E
v
e
n
t
H
a
n
d
l
i
n
g
CHALLENGES
1. Create a Frame that does not close normally by using the
windowClosing(WindowEvent) method, but instead, closes when you click a
Button labeled Close.
2. Create an application that has multiple
Buttons with different labels for each

of them. When any one of those
Buttons is clicked, a TextField is updated
with the text of that one
Button. Also include a TextArea that appends the
text displayed in the
TextField to its text by listening for TextEvents. The end
result will be that the
TextArea will contain an audit trail of all of the button
clicks, in the order they were clicked. The
TextField displays the most
recently clicked button. Lay out these components as you desire, but use a
GridBagLayout manager.
3. Create a numerical keypad that uses
Buttons to update an uneditable
TextField by appending the clicked number to the end of its current num-
ber. Use a
BorderLayout for the Frame. At BorderLayout.NORTH, place the
TextField. In the center, create a panel that uses a GridLayout to lay out But-
ton
s 1 through 9 in a three by three grid. At BorderLayout.SOUTH, create
another
Panel that has the zero key and also a “clear” key that deletes the
current number in the
TextField.
JavaProgAbsBeg-07.qxd 2/25/03 8:53 AM Page 275
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
This page intentionally left blank
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

With the Internet as widely used as it is today, one of the
more exciting features of Java is its use as a tool for Internet
development. You can embed Java right into a Web docu-
ment by writing an applet and adding some HTML to include
that applet. In this chapter, you learn all about applets—how
to create them, how to write the HTML to make use of them,
and all about security restrictions and other differences
between applets and applications. This chapter covers the
following topics:
• Understand applet basics
• Learn the difference between applets and applications
• Use the Applet class
• Include an applet in an HTML Web page
• Write programs that can run as either an applet or an
application
• Display images and play sounds
W
r
i
t
i
n
g
A
p
p
l
e
t
s

8
CHAPTER
JavaProgAbsBeg-08.qxd 2/25/03 8:54 AM Page 277
TEAM LinG - Live, Informative, Non-cost and Genuine!
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×