core
Web
programming
Handling Mouse and
Keyboard Events
2001-2003 Marty Hall, Larry Brown [Link]
Agenda
General event-handling strategy
Handling events with separate listeners
Handling events by implementing interfaces
Handling events with named inner classes
Handling events with anonymous inner
classes
The standard AWT listener types
Subtleties with mouse events
Examples
Handling Mouse and Keyboard Events
[Link]
General Strategy
Determine what type of listener is of interest
11 standard AWT listener types, described on later slide.
ActionListener, AdjustmentListener,
ComponentListener, ContainerListener,
FocusListener, ItemListener, KeyListener,
MouseListener, MouseMotionListener, TextListener,
WindowListener
Define a class of that type
Implement interface (KeyListener, MouseListener, etc.)
Extend class (KeyAdapter, MouseAdapter, etc.)
Register an object of your listener class
with the window
[Link](new MyListenerClass());
3
E.g., addKeyListener, addMouseListener
[Link]
Handling Mouse and Keyboard Events
Handling Events with a
Separate Listener: Simple Case
Listener does not need to call any methods
of the window to which it is attached
import [Link];
import [Link].*;
public class ClickReporter extends Applet {
public void init() {
setBackground([Link]);
addMouseListener(new ClickListener());
}
}
Handling Mouse and Keyboard Events
[Link]
Separate Listener: Simple Case
(Continued)
import [Link].*;
public class ClickListener extends MouseAdapter {
public void mousePressed(MouseEvent event) {
[Link]("Mouse pressed at (" +
[Link]() + "," +
[Link]() + ").");
}
}
Handling Mouse and Keyboard Events
[Link]
Generalizing Simple Case
What if ClickListener wants to draw a circle
wherever mouse is clicked?
Why cant it just call getGraphics to get a
Graphics object with which to draw?
General solution:
Call [Link] to obtain a reference to window or
GUI component from which event originated
Cast result to type of interest
Call methods on that reference
Handling Mouse and Keyboard Events
[Link]
Handling Events with Separate
Listener: General Case
import [Link];
import [Link].*;
public class CircleDrawer1 extends Applet {
public void init() {
setForeground([Link]);
addMouseListener(new CircleListener());
}
}
Handling Mouse and Keyboard Events
[Link]
Separate Listener: General
Case (Continued)
import [Link];
import [Link].*;
import [Link].*;
public class CircleListener extends MouseAdapter {
private int radius = 25;
public void mousePressed(MouseEvent event) {
Applet app = (Applet)[Link]();
Graphics g = [Link]();
[Link]([Link]()-radius,
[Link]()-radius,
2*radius,
2*radius);
}
}
8
Handling Mouse and Keyboard Events
[Link]
Separate Listener: General
Case (Results)
Handling Mouse and Keyboard Events
[Link]
Case 2: Implementing a
Listener Interface
import [Link];
import [Link].*;
import [Link].*;
public class CircleDrawer2 extends Applet
implements MouseListener {
private int radius = 25;
public void init() {
setForeground([Link]);
addMouseListener(this);
}
10
Handling Mouse and Keyboard Events
[Link]
Implementing a Listener
Interface (Continued)
public
public
public
public
void
void
void
void
mouseEntered(MouseEvent event) {}
mouseExited(MouseEvent event) {}
mouseReleased(MouseEvent event) {}
mouseClicked(MouseEvent event) {}
public void mousePressed(MouseEvent event) {
Graphics g = getGraphics();
[Link]([Link]()-radius,
[Link]()-radius,
2*radius,
2*radius);
}
}
11
Handling Mouse and Keyboard Events
[Link]
Case 3: Named Inner Classes
import [Link];
import [Link].*;
import [Link].*;
public class CircleDrawer3 extends Applet {
public void init() {
setForeground([Link]);
addMouseListener(new CircleListener());
}
12
Handling Mouse and Keyboard Events
[Link]
Named Inner Classes
(Continued)
Note: still part of class from previous slide
private class CircleListener
extends MouseAdapter {
private int radius = 25;
public void mousePressed(MouseEvent event) {
Graphics g = getGraphics();
[Link]([Link]()-radius,
[Link]()-radius,
2*radius,
2*radius);
}
}
}
13
Handling Mouse and Keyboard Events
[Link]
Case 4: Anonymous Inner
Classes
public class CircleDrawer4 extends Applet {
public void init() {
setForeground([Link]);
addMouseListener
(new MouseAdapter() {
private int radius = 25;
public void mousePressed(MouseEvent event) {
Graphics g = getGraphics();
[Link]([Link]()-radius,
[Link]()-radius,
2*radius,
2*radius);
}
});
}
}
14
Handling Mouse and Keyboard Events
[Link]
Event Handling Strategies:
Pros and Cons
Separate Listener
Advantages
Can extend adapter and thus ignore unused methods
Separate class easier to manage
Disadvantage
Need extra step to call methods in main window
Main window that implements interface
Advantage
No extra steps needed to call methods in main
window
Disadvantage
Must implement methods you might not care about
15
Handling Mouse and Keyboard Events
[Link]
Event Handling Strategies:
Pros and Cons (Continued)
Named inner class
Advantages
Can extend adapter and thus ignore unused methods
No extra steps needed to call methods in main
window
Disadvantage
A bit harder to understand
Anonymous inner class
Advantages
Same as named inner classes
Even shorter
Disadvantage
Much harder to understand
16
Handling Mouse and Keyboard Events
[Link]
Standard AWT Event Listeners
(Summary)
Adapter Class
(If Any)
Listener
ActionListener
AdjustmentListener
ComponentListener
ContainerListener
FocusListener
ItemListener
KeyListener
MouseListener
MouseMotionListener
TextListener
WindowListener
17
ComponentAdapter
ContainerAdapter
FocusAdapter
KeyAdapter
MouseAdapter
MouseMotionAdapter
WindowAdapter
Handling Mouse and Keyboard Events
Registration Method
addActionListener
addAdjustmentListener
addComponentListener
addContainerListener
addFocusListener
addItemListener
addKeyListener
addMouseListener
addMouseMotionListener
addTextListener
addWindowListener
[Link]
Standard AWT Event Listeners
(Details)
ActionListener
Handles buttons and a few other actions
actionPerformed(ActionEvent event)
AdjustmentListener
Applies to scrolling
adjustmentValueChanged(AdjustmentEvent event)
ComponentListener
Handles moving/resizing/hiding GUI objects
18
componentResized(ComponentEvent event)
componentMoved (ComponentEvent event)
componentShown(ComponentEvent event)
componentHidden(ComponentEvent event)
Handling Mouse and Keyboard Events
[Link]
Standard AWT Event Listeners
(Details Continued)
ContainerListener
Triggered when window adds/removes GUI controls
componentAdded(ContainerEvent event)
componentRemoved(ContainerEvent event)
FocusListener
Detects when controls get/lose keyboard focus
focusGained(FocusEvent event)
focusLost(FocusEvent event)
19
Handling Mouse and Keyboard Events
[Link]
Standard AWT Event Listeners
(Details Continued)
ItemListener
Handles selections in lists, checkboxes, etc.
itemStateChanged(ItemEvent event)
KeyListener
Detects keyboard events
keyPressed(KeyEvent event) -- any key pressed
down
keyReleased(KeyEvent event) -- any key released
keyTyped(KeyEvent event) -- key for printable char
released
20
Handling Mouse and Keyboard Events
[Link]
10
Standard AWT Event Listeners
(Details Continued)
MouseListener
Applies to basic mouse events
mouseEntered(MouseEvent event)
mouseExited(MouseEvent event)
mousePressed(MouseEvent event)
mouseReleased(MouseEvent event)
mouseClicked(MouseEvent event) -- Release without
drag
Applies on release if no movement since press
MouseMotionListener
Handles mouse movement
mouseMoved(MouseEvent event)
mouseDragged(MouseEvent event)
21
Handling Mouse and Keyboard Events
[Link]
Standard AWT Event Listeners
(Details Continued)
TextListener
Applies to textfields and text areas
textValueChanged(TextEvent event)
WindowListener
Handles high-level window events
windowOpened, windowClosing, windowClosed,
windowIconified, windowDeiconified,
windowActivated, windowDeactivated
windowClosing particularly useful
22
Handling Mouse and Keyboard Events
[Link]
11
Mouse Events: Details
MouseListener and MouseMotionListener
share event types
Location of clicks
[Link]() and [Link]()
Double clicks
Determined by OS, not by programmer
Call [Link]()
Distinguishing mouse buttons
Call [Link]() and compare to
MouseEvent.Button2_MASK for a middle click and
MouseEvent.Button3_MASK for right click.
Can also trap Shift-click, Alt-click, etc.
23
Handling Mouse and Keyboard Events
[Link]
Simple Example: SpellingCorrecting Textfield
KeyListener corrects spelling during typing
ActionListener completes word on ENTER
FocusListener gives subliminal hints
24
Handling Mouse and Keyboard Events
[Link]
12
Example: Simple Whiteboard
import [Link];
import [Link].*;
import [Link].*;
public class SimpleWhiteboard extends Applet {
protected int lastX=0, lastY=0;
public void init() {
setBackground([Link]);
setForeground([Link]);
addMouseListener(new PositionRecorder());
addMouseMotionListener(new LineDrawer());
}
protected void record(int x, int y) {
lastX = x; lastY = y;
}
25
Handling Mouse and Keyboard Events
[Link]
Simple Whiteboard (Continued)
private class PositionRecorder extends MouseAdapter {
public void mouseEntered(MouseEvent event) {
requestFocus(); // Plan ahead for typing
record([Link](), [Link]());
}
public void mousePressed(MouseEvent event) {
record([Link](), [Link]());
}
}
...
26
Handling Mouse and Keyboard Events
[Link]
13
Simple Whiteboard (Continued)
...
private class LineDrawer extends MouseMotionAdapter {
public void mouseDragged(MouseEvent event) {
int x = [Link]();
int y = [Link]();
Graphics g = getGraphics();
[Link](lastX, lastY, x, y);
record(x, y);
}
}
}
27
Handling Mouse and Keyboard Events
[Link]
Simple Whiteboard (Results)
28
Handling Mouse and Keyboard Events
[Link]
14
Whiteboard: Adding Keyboard
Events
import [Link];
import [Link].*;
import [Link].*;
public class Whiteboard extends SimpleWhiteboard {
protected FontMetrics fm;
public void init() {
[Link]();
Font font = new Font("Serif", [Link], 20);
setFont(font);
fm = getFontMetrics(font);
addKeyListener(new CharDrawer());
}
29
Handling Mouse and Keyboard Events
[Link]
Whiteboard (Continued)
...
private class CharDrawer extends KeyAdapter {
// When user types a printable character,
// draw it and shift position rightwards.
public void keyTyped(KeyEvent event) {
String s = [Link]([Link]());
getGraphics().drawString(s, lastX, lastY);
record(lastX + [Link](s), lastY);
}
}
}
30
Handling Mouse and Keyboard Events
[Link]
15
Whiteboard (Results)
31
Handling Mouse and Keyboard Events
[Link]
Summary
General strategy
Determine what type of listener is of interest
Check table of standard types
Define a class of that type
Extend adapter separately, implement interface,
extend adapter in named inner class, extend adapter
in anonymous inner class
Register an object of your listener class with the window
Call addXxxListener
Understanding listeners
Methods give specific behavior.
Arguments to methods are of type XxxEvent
Methods in MouseEvent of particular interest
32
Handling Mouse and Keyboard Events
[Link]
16
core
Web
programming
Questions?
33
2001-2003 Marty Hall, Larry Brown [Link]
Preview
Whiteboard had freehand drawing only
Need GUI controls to allow selection of other drawing
methods
Whiteboard had only temporary drawing
Covering and reexposing window clears drawing
After cover multithreading, well see solutions to this
problem
Most general is double buffering
Whiteboard was unshared
Need network programming capabilities so that two
different whiteboards can communicate with each other
34
Handling Mouse and Keyboard Events
[Link]
17