0% found this document useful (0 votes)
90 views

09 Event Handling

Servlets, JSP, Struts, JSF / MyFaces, Hibernate, Ajax, GWT, java 5, java 6, etc. Ruby / Rails coming soon. Developed and taught by well-known author and developer.

Uploaded by

api-3811552
Copyright
© Attribution Non-Commercial (BY-NC)
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)
90 views

09 Event Handling

Servlets, JSP, Struts, JSF / MyFaces, Hibernate, Ajax, GWT, java 5, java 6, etc. Ruby / Rails coming soon. Developed and taught by well-known author and developer.

Uploaded by

api-3811552
Copyright
© Attribution Non-Commercial (BY-NC)
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/ 19

© 2007 Marty Hall

Handling Mouse and


Keyboard Events
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/java5.html

Customized J2EE Training: http://courses.coreservlets.com/


Servlets, JSP, Struts, JSF/MyFaces, Hibernate, Ajax, GWT, Java 5, Java 6, etc. Ruby/Rails coming soon.
2 Developed and taught by well-known author and developer. At public venues or onsite at your location.

© 2007 Marty Hall

For live Java training, please see training courses


at http://courses.coreservlets.com/. Servlets, JSP,
Struts, JSF/MyFaces, Ajax, GWT, Java 5 or 6, and
custom courses. Ruby/Rails coming soon.
Taught by the author of Core Servlets and JSP, More Servlets
and JSP, and this tutorial. Available at public venues, or
customized versions
Customized J2EE can be held
Training: on-site at your organization.
http://courses.coreservlets.com/
Contact [email protected]
Servlets, JSP, Struts, JSF/MyFaces, Hibernate, Ajax, GWT, Java 5, Javafor details.
6, etc. Ruby/Rails coming soon.
3 Developed and taught by well-known author and developer. At public venues or onsite at your location.
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

4 J2EE training: http://courses.coreservlets.com

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
– w.addXxxListener(new MyListenerClass());
• E.g., addKeyListener, addMouseListener
5 J2EE training: http://courses.coreservlets.com
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 java.applet.Applet;
import java.awt.*;

public class ClickReporter extends Applet {


public void init() {
setBackground(Color.YELLOW);
addMouseListener(new ClickListener());
}
}

6 J2EE training: http://courses.coreservlets.com

Separate Listener: Simple Case


(Continued)
import java.awt.event.*;

public class ClickListener extends MouseAdapter {


public void mousePressed(MouseEvent event) {
System.out.println("Mouse pressed at (" +
event.getX() + "," +
event.getY() + ").");
}
}

7 J2EE training: http://courses.coreservlets.com


Generalizing Simple Case
• What if ClickListener wants to draw a circle
wherever mouse is clicked?
• Why can’t it just call getGraphics to get a
Graphics object with which to draw?
• General solution:
– Call event.getSource to obtain a reference to window or
GUI component from which event originated
– Cast result to type of interest
– Call methods on that reference

8 J2EE training: http://courses.coreservlets.com

Handling Events with Separate


Listener: General Case
import java.applet.Applet;
import java.awt.*;

public class CircleDrawer1 extends Applet {


public void init() {
setForeground(Color.BLUE);
addMouseListener(new CircleListener());
}
}

9 J2EE training: http://courses.coreservlets.com


Separate Listener: General
Case (Continued)
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class CircleListener extends MouseAdapter {


private int radius = 25;

public void mousePressed(MouseEvent event) {


Applet app = (Applet)event.getSource();
Graphics g = app.getGraphics();
g.fillOval(event.getX()-radius,
event.getY()-radius,
2*radius,
2*radius);
}
10 } J2EE training: http://courses.coreservlets.com

Separate Listener: General


Case (Results)

11 J2EE training: http://courses.coreservlets.com


Case 2: Implementing a
Listener Interface
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class CircleDrawer2 extends Applet


implements MouseListener {
private int radius = 25;

public void init() {


setForeground(Color.BLUE);
addMouseListener(this);
}

12 J2EE training: http://courses.coreservlets.com

Implementing a Listener
Interface (Continued)
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
public void mouseReleased(MouseEvent event) {}
public void mouseClicked(MouseEvent event) {}

public void mousePressed(MouseEvent event) {


Graphics g = getGraphics();
g.fillOval(event.getX()-radius,
event.getY()-radius,
2*radius,
2*radius);
}
}

13 J2EE training: http://courses.coreservlets.com


Adapters vs. Interfaces:
Method Signature Errors
• What if you goof on the method signature?
– public void mousepressed(MouseEvent e)
– public void mousePressed()
• Interfaces
– Compile time error
• Adapters
– No compile time error, but nothing happens at run time
when you press the mouse
• Solution for adapters (and overriding in
Java 5 in general): @Override annotation
– Whenever you think you are overriding a method, put
"@Override" on the line above the start of the method.
• If that method is not actually overriding an inherited
method, you get a compile-time error.
14 J2EE training: http://courses.coreservlets.com

@Override Example
public class CircleDrawer1 extends Applet {
@Override
public void init() {
setForeground(Color.BLUE);
addMouseListener(new CircleListener());
}
}

public class CircleListener extends MouseAdapter {


private int radius = 25;
@Override
public void mousePressed(MouseEvent event) {
Applet app = (Applet)event.getSource();
Graphics g = app.getGraphics();
g.fillOval(event.getX()-radius,
event.getY()-radius,
2*radius,
2*radius);
}
}
15 J2EE training: http://courses.coreservlets.com
Case 3: Named Inner Classes
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class CircleDrawer3 extends Applet {


public void init() {
setForeground(Color.BLUE);
addMouseListener(new CircleListener());
}

16 J2EE training: http://courses.coreservlets.com

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();
g.fillOval(event.getX()-radius,
event.getY()-radius,
2*radius,
2*radius);
}
}
17 } J2EE training: http://courses.coreservlets.com
Case 4: Anonymous Inner
Classes
public class CircleDrawer4 extends Applet {
public void init() {
setForeground(Color.BLUE);
addMouseListener
(new MouseAdapter() {
private int radius = 25;

public void mousePressed(MouseEvent event) {


Graphics g = getGraphics();
g.fillOval(event.getX()-radius,
event.getY()-radius,
2*radius,
2*radius);
}
});
}
18 } J2EE training: http://courses.coreservlets.com

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

19 J2EE training: http://courses.coreservlets.com


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

20 J2EE training: http://courses.coreservlets.com

Standard AWT Event Listeners


(Summary)
Adapter Class
Listener (If Any) Registration Method
ActionListener addActionListener
AdjustmentListener addAdjustmentListener
ComponentListener ComponentAdapter addComponentListener
ContainerListener ContainerAdapter addContainerListener
FocusListener FocusAdapter addFocusListener
ItemListener addItemListener
KeyListener KeyAdapter addKeyListener
MouseListener MouseAdapter addMouseListener
MouseMotionListener MouseMotionAdapter addMouseMotionListener
TextListener addTextListener
WindowListener WindowAdapter addWindowListener

21 J2EE training: http://courses.coreservlets.com


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
• componentResized(ComponentEvent event)
• componentMoved (ComponentEvent event)
• componentShown(ComponentEvent event)
• componentHidden(ComponentEvent event)

22 J2EE training: http://courses.coreservlets.com

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)

23 J2EE training: http://courses.coreservlets.com


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

24 J2EE training: http://courses.coreservlets.com

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. Do not use this for mousePressed!
– Applies on release if no movement since press
• MouseMotionListener
– Handles mouse movement
• mouseMoved(MouseEvent event)
• mouseDragged(MouseEvent event)
• MouseInputListener
– Combines MouseListener and MouseMotionListener
• In javax.swing.event package, not java.awt.event
• You have to call both addMouseListener and
addMouseMotionListener, so it does not save much
25 J2EE training: http://courses.coreservlets.com
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

26 J2EE training: http://courses.coreservlets.com

Mouse Events: Details


• MouseListener and MouseMotionListener
share event types
• Location of clicks
– event.getX() and event.getY()
– You can also use the MouseInfo class for mouse position
• Double clicks
– Determined by OS, not by programmer
– Call event.getClickCount()
• Distinguishing mouse buttons
– Call event.getModifiers() 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.
27 J2EE training: http://courses.coreservlets.com
Simple Example: Spelling-
Correcting Textfield
• KeyListener corrects spelling during typing
• ActionListener completes word on ENTER
• FocusListener gives subliminal hints

28 J2EE training: http://courses.coreservlets.com

Example: Simple Whiteboard


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class SimpleWhiteboard extends Applet {


protected int lastX=0, lastY=0;

public void init() {


setBackground(Color.WHITE);
setForeground(Color.BLUE);
addMouseListener(new PositionRecorder());
addMouseMotionListener(new LineDrawer());
}

protected void record(int x, int y) {


lastX = x; lastY = y;
29 } J2EE training: http://courses.coreservlets.com
Simple Whiteboard (Continued)

private class PositionRecorder extends MouseAdapter {


public void mouseEntered(MouseEvent event) {
requestFocus(); // Plan ahead for typing
record(event.getX(), event.getY());
}

public void mousePressed(MouseEvent event) {


record(event.getX(), event.getY());
}
}
...

30 J2EE training: http://courses.coreservlets.com

Simple Whiteboard (Continued)

...
private class LineDrawer extends MouseMotionAdapter {
public void mouseDragged(MouseEvent event) {
int x = event.getX();
int y = event.getY();
Graphics g = getGraphics();
g.drawLine(lastX, lastY, x, y);
record(x, y);
}
}
}

31 J2EE training: http://courses.coreservlets.com


Simple Whiteboard (Results)

32 J2EE training: http://courses.coreservlets.com

Whiteboard: Adding Keyboard


Events
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class Whiteboard extends SimpleWhiteboard {


protected FontMetrics fm;

public void init() {


super.init();
Font font = new Font("Serif", Font.BOLD, 20);
setFont(font);
fm = getFontMetrics(font);
addKeyListener(new CharDrawer());
}

33 J2EE training: http://courses.coreservlets.com


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 = String.valueOf(event.getKeyChar());
getGraphics().drawString(s, lastX, lastY);
record(lastX + fm.stringWidth(s), lastY);
}
}
}

34 J2EE training: http://courses.coreservlets.com

Whiteboard (Results)

35 J2EE training: http://courses.coreservlets.com


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

36 J2EE training: http://courses.coreservlets.com

© 2007 Marty Hall

Questions?

Customized J2EE Training: http://courses.coreservlets.com/


Servlets, JSP, Struts, JSF/MyFaces, Hibernate, Ajax, GWT, Java 5, Java 6, etc. Ruby/Rails coming soon.
37 Developed and taught by well-known author and developer. At public venues or onsite at your location.
Preview of Later Topics
• 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, we’ll 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

38 J2EE training: http://courses.coreservlets.com

You might also like