The getItem method in the ItemEvent class returns an Object object that represents the item that triggered the event.. The AdjustmentTest application tests this: /* * AdjustmentTest * De
Trang 1The 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
s o
l ut
n e
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
ItemEventsare triggered by Checkboxes, Choices, and Lists
Field or Method Description
int DESELECTED Signifies that the ItemEventoccurred because an item was
deselected
int SELECTED Signifies that the ItemEventoccurred because an item was
selected
ItemEvent.SELECTEDdepending on what type of state change is associated with this ItemEvent
Object getItem() Returns an Objectthat represents the item whose state changed
TA B L E 7 8 IT E MEV E N T FI E L D S A N D ME T H O D S
Trang 2Handling AdjustmentEvents
The AdjustmentListener interface listens for AdjustmentEvent s, 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
Trang 3public 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 Label s 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
s o
l ut
n e
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
FIGURE 7.15
You use the Adjustment-Listenerinterface
to determine when
aScrollbarvalue
is being changed
TA B L E 7 9 AD J U S T M E N TEV E N T FI E L D S A N D ME T H O D S
Handling TextEvents
TextEvent s 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
Trang 4invoked 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
Trang 5Handling MouseEvents
Your computer’s mouse triggers MouseEvent s 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 MouseEvent s.
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);
T R I C K
262
J a
s o
l ut
n e
FIGURE 7.16
This application copies your text as you write it and displays it below
Trang 6canvas.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
Trang 7public 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 curcur-rent 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
s o
l ut
n e
source component
TA B L E 7 1 0 MO U S EEV E N T ME T H O D S
Trang 8I 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
KeyEvent s 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 KeyEvent s 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
clicks (is pressed, and then released) on a component
cursor enters the source component’s area
cursor exits the source component’s area
button is pressed down
button is released
moves while within a component’s area
moves while the mouse button is down while within
a component’s area
TA B L E 7 1 1 MO U S ELI S T E N E R A N D
MO U S EMO T I O NLI S T E N E R ME T H O D S
Trang 9too 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.
H I N T
266
J a
s o
l ut
n e
FIGURE 7.17
Listening to MouseEvents allows you to know what the user is doing with the mouse
TA B L E 7 1 2 KE YLI S T E N E R ME T H O D S
Trang 10The KeyTest application tests the handling of KeyEvent s 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
such as Ctrl based on the given integer representation of the modifiers
the given key code
TA B L E 7 1 3 KE YEV E N T ME T H O D S
Trang 11released = 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
s o
l ut
n e
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!