SlideShare a Scribd company logo
1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Handling Mouse and
Keyboard Events
Handling Mouse and Keyboard Events2 www.corewebprogramming.com
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 Events3 www.corewebprogramming.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
Handling Mouse and Keyboard Events4 www.corewebprogramming.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());
}
}
Handling Mouse and Keyboard Events5 www.corewebprogramming.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() + ").");
}
}
Handling Mouse and Keyboard Events6 www.corewebprogramming.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
Handling Mouse and Keyboard Events7 www.corewebprogramming.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());
}
}
Handling Mouse and Keyboard Events8 www.corewebprogramming.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);
}
}
Handling Mouse and Keyboard Events9 www.corewebprogramming.com
Separate Listener: General
Case (Results)
Handling Mouse and Keyboard Events10 www.corewebprogramming.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);
}
Handling Mouse and Keyboard Events11 www.corewebprogramming.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);
}
}
Handling Mouse and Keyboard Events12 www.corewebprogramming.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());
}
Handling Mouse and Keyboard Events13 www.corewebprogramming.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);
}
}
}
Handling Mouse and Keyboard Events14 www.corewebprogramming.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);
}
});
}
}
Handling Mouse and Keyboard Events15 www.corewebprogramming.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
Handling Mouse and Keyboard Events16 www.corewebprogramming.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
Handling Mouse and Keyboard Events17 www.corewebprogramming.com
Standard AWT Event Listeners
(Summary)
Adapter Class
Listener (If Any) Re
ActionListener addA
AdjustmentListener addA
ComponentListener ComponentAdapter addC
ContainerListener ContainerAdapter addC
FocusListener FocusAdapter addF
ItemListener addI
KeyListener KeyAdapter addK
MouseListener MouseAdapter addM
MouseMotionListener MouseMotionAdapter addM
TextListener addT
WindowListener WindowAdapter addW
gistration Method
ctionListener
djustmentListener
omponentListener
ontainerListener
ocusListener
temListener
eyListener
ouseListener
ouseMotionListener
extListener
indowListener
Handling Mouse and Keyboard Events18 www.corewebprogramming.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)
Handling Mouse and Keyboard Events19 www.corewebprogramming.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)
Handling Mouse and Keyboard Events20 www.corewebprogramming.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
Handling Mouse and Keyboard Events21 www.corewebprogramming.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
– Applies on release if no movement since press
• MouseMotionListener
– Handles mouse movement
• mouseMoved(MouseEvent event)
• mouseDragged(MouseEvent event)
Handling Mouse and Keyboard Events22 www.corewebprogramming.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
Handling Mouse and Keyboard Events23 www.corewebprogramming.com
Mouse Events: Details
• MouseListener and MouseMotionListener
share event types
• Location of clicks
– event.getX() and event.getY()
• 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.
Handling Mouse and Keyboard Events24 www.corewebprogramming.com
Simple Example: Spelling-
Correcting Textfield
• KeyListener corrects spelling during typing
• ActionListener completes word on ENTER
• FocusListener gives subliminal hints
Handling Mouse and Keyboard Events25 www.corewebprogramming.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;
}
Handling Mouse and Keyboard Events26 www.corewebprogramming.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());
}
}
...
Handling Mouse and Keyboard Events27 www.corewebprogramming.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);
}
}
}
Handling Mouse and Keyboard Events28 www.corewebprogramming.com
Simple Whiteboard (Results)
Handling Mouse and Keyboard Events29 www.corewebprogramming.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());
}
Handling Mouse and Keyboard Events30 www.corewebprogramming.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);
}
}
}
Handling Mouse and Keyboard Events31 www.corewebprogramming.com
Whiteboard (Results)
Handling Mouse and Keyboard Events32 www.corewebprogramming.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
33 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Questions?
Handling Mouse and Keyboard Events34 www.corewebprogramming.com
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, 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

More Related Content

Viewers also liked

Sublime - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700
Sublime - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700Sublime - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700
Sublime - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700Imóveis do RJ
 
Brochure AZ Holding - Credit Management
Brochure AZ Holding - Credit ManagementBrochure AZ Holding - Credit Management
Brochure AZ Holding - Credit ManagementCarmine Evangelista
 
Barra One - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700
Barra One - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700Barra One - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700
Barra One - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700Imóveis do RJ
 
Роль литературных вечеров досуга в ознакомлении дошкольников с художествен...
Роль  литературных  вечеров досуга в ознакомлении дошкольников  с художествен...Роль  литературных  вечеров досуга в ознакомлении дошкольников  с художествен...
Роль литературных вечеров досуга в ознакомлении дошкольников с художествен...themaximax
 
AZ Holding presents C.I.R.O. (Eng)
AZ Holding presents C.I.R.O. (Eng)AZ Holding presents C.I.R.O. (Eng)
AZ Holding presents C.I.R.O. (Eng)Carmine Evangelista
 
AZ Holding presentazione - Antifrode
AZ Holding presentazione - AntifrodeAZ Holding presentazione - Antifrode
AZ Holding presentazione - AntifrodeCarmine Evangelista
 
Caza Del Tesoro[1]
Caza Del Tesoro[1]Caza Del Tesoro[1]
Caza Del Tesoro[1]guest9c12e
 
Ardo Hansson Eesti ja euroala majandusest
Ardo Hansson Eesti ja euroala majandusestArdo Hansson Eesti ja euroala majandusest
Ardo Hansson Eesti ja euroala majandusestEesti Pank
 
ОЗНАКОМЛЕНИЕ ДЕТЕЙ-ДОШКОЛЬНИКОВ С ТЕХНИКОЙ КОМКОВАНИЯ
ОЗНАКОМЛЕНИЕ ДЕТЕЙ-ДОШКОЛЬНИКОВ С ТЕХНИКОЙ КОМКОВАНИЯОЗНАКОМЛЕНИЕ ДЕТЕЙ-ДОШКОЛЬНИКОВ С ТЕХНИКОЙ КОМКОВАНИЯ
ОЗНАКОМЛЕНИЕ ДЕТЕЙ-ДОШКОЛЬНИКОВ С ТЕХНИКОЙ КОМКОВАНИЯruster_c
 
Театрализованная деятельность, как метод всестороннего развития личности дошк...
Театрализованная деятельность, как метод всестороннего развития личности дошк...Театрализованная деятельность, как метод всестороннего развития личности дошк...
Театрализованная деятельность, как метод всестороннего развития личности дошк...ruster_c
 
Norte premium previa 5 letram marrom
Norte premium previa 5 letram marromNorte premium previa 5 letram marrom
Norte premium previa 5 letram marromverdadeimovel
 
Native plants for oregon’s coastal climates
Native plants for oregon’s coastal climatesNative plants for oregon’s coastal climates
Native plants for oregon’s coastal climatesOregon State University
 
Soluciones derivadas
Soluciones derivadasSoluciones derivadas
Soluciones derivadasMar Tuxi
 

Viewers also liked (16)

Sublime - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700
Sublime - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700Sublime - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700
Sublime - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700
 
Brochure AZ Holding - Credit Management
Brochure AZ Holding - Credit ManagementBrochure AZ Holding - Credit Management
Brochure AZ Holding - Credit Management
 
10 cool facts about canada
10 cool facts about canada10 cool facts about canada
10 cool facts about canada
 
Barra One - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700
Barra One - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700Barra One - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700
Barra One - Vendas em www-imoveisdorj-com-br ou (21) 3683-0700
 
Роль литературных вечеров досуга в ознакомлении дошкольников с художествен...
Роль  литературных  вечеров досуга в ознакомлении дошкольников  с художествен...Роль  литературных  вечеров досуга в ознакомлении дошкольников  с художествен...
Роль литературных вечеров досуга в ознакомлении дошкольников с художествен...
 
AZ Holding presents C.I.R.O. (Eng)
AZ Holding presents C.I.R.O. (Eng)AZ Holding presents C.I.R.O. (Eng)
AZ Holding presents C.I.R.O. (Eng)
 
AZ Holding presentazione - Antifrode
AZ Holding presentazione - AntifrodeAZ Holding presentazione - Antifrode
AZ Holding presentazione - Antifrode
 
Caza Del Tesoro[1]
Caza Del Tesoro[1]Caza Del Tesoro[1]
Caza Del Tesoro[1]
 
Anti Fraud
Anti FraudAnti Fraud
Anti Fraud
 
Ardo Hansson Eesti ja euroala majandusest
Ardo Hansson Eesti ja euroala majandusestArdo Hansson Eesti ja euroala majandusest
Ardo Hansson Eesti ja euroala majandusest
 
Orla 15/16
Orla 15/16Orla 15/16
Orla 15/16
 
ОЗНАКОМЛЕНИЕ ДЕТЕЙ-ДОШКОЛЬНИКОВ С ТЕХНИКОЙ КОМКОВАНИЯ
ОЗНАКОМЛЕНИЕ ДЕТЕЙ-ДОШКОЛЬНИКОВ С ТЕХНИКОЙ КОМКОВАНИЯОЗНАКОМЛЕНИЕ ДЕТЕЙ-ДОШКОЛЬНИКОВ С ТЕХНИКОЙ КОМКОВАНИЯ
ОЗНАКОМЛЕНИЕ ДЕТЕЙ-ДОШКОЛЬНИКОВ С ТЕХНИКОЙ КОМКОВАНИЯ
 
Театрализованная деятельность, как метод всестороннего развития личности дошк...
Театрализованная деятельность, как метод всестороннего развития личности дошк...Театрализованная деятельность, как метод всестороннего развития личности дошк...
Театрализованная деятельность, как метод всестороннего развития личности дошк...
 
Norte premium previa 5 letram marrom
Norte premium previa 5 letram marromNorte premium previa 5 letram marrom
Norte premium previa 5 letram marrom
 
Native plants for oregon’s coastal climates
Native plants for oregon’s coastal climatesNative plants for oregon’s coastal climates
Native plants for oregon’s coastal climates
 
Soluciones derivadas
Soluciones derivadasSoluciones derivadas
Soluciones derivadas
 

Similar to 7java Events

tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handlingteach4uin
 
Event handling
Event handlingEvent handling
Event handlingswapnac12
 
PROGRAMMING IN JAVA- unit 4-part II
PROGRAMMING IN JAVA- unit 4-part IIPROGRAMMING IN JAVA- unit 4-part II
PROGRAMMING IN JAVA- unit 4-part IISivaSankari36
 
12 High Level UI Event Handling
12 High Level UI Event Handling12 High Level UI Event Handling
12 High Level UI Event Handlingcorneliuskoo
 
cse581_03_EventProgramming.ppt
cse581_03_EventProgramming.pptcse581_03_EventProgramming.ppt
cse581_03_EventProgramming.ppttadudemise
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptxusvirat1805
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intentPERKYTORIALS
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Javababak danyal
 
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdfJEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdfMarlouFelixIIICunana
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart JfokusLars Vogel
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptsharanyak0721
 
Event handling63
Event handling63Event handling63
Event handling63myrajendra
 

Similar to 7java Events (20)

Java-Events
Java-EventsJava-Events
Java-Events
 
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing ButtonsJAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
 
tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handling
 
What is Event
What is EventWhat is Event
What is Event
 
Awt event
Awt eventAwt event
Awt event
 
09events
09events09events
09events
 
Event handling
Event handlingEvent handling
Event handling
 
PROGRAMMING IN JAVA- unit 4-part II
PROGRAMMING IN JAVA- unit 4-part IIPROGRAMMING IN JAVA- unit 4-part II
PROGRAMMING IN JAVA- unit 4-part II
 
12 High Level UI Event Handling
12 High Level UI Event Handling12 High Level UI Event Handling
12 High Level UI Event Handling
 
cse581_03_EventProgramming.ppt
cse581_03_EventProgramming.pptcse581_03_EventProgramming.ppt
cse581_03_EventProgramming.ppt
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 
B2. activity and intent
B2. activity and intentB2. activity and intent
B2. activity and intent
 
Gui
GuiGui
Gui
 
Unit 6 Java
Unit 6 JavaUnit 6 Java
Unit 6 Java
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Java
 
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdfJEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
JEDI Slides-Intro2-Chapter20-GUI Event Handling.pdf
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart Jfokus
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
 
14a-gui.ppt
14a-gui.ppt14a-gui.ppt
14a-gui.ppt
 
Event handling63
Event handling63Event handling63
Event handling63
 

More from Adil Jafri

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5Adil Jafri
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net BibleAdil Jafri
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming ClientsAdil Jafri
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran TochAdil Jafri
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10Adil Jafri
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx TutorialsAdil Jafri
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbAdil Jafri
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12Adil Jafri
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash TutorialAdil Jafri
 

More from Adil Jafri (20)

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5
 
Php How To
Php How ToPhp How To
Php How To
 
Php How To
Php How ToPhp How To
Php How To
 
Owl Clock
Owl ClockOwl Clock
Owl Clock
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net Bible
 
Tcpip Intro
Tcpip IntroTcpip Intro
Tcpip Intro
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
 
Jsp Tutorial
Jsp TutorialJsp Tutorial
Jsp Tutorial
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10
 
Javascript
JavascriptJavascript
Javascript
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx Tutorials
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand Ejb
 
Html Css
Html CssHtml Css
Html Css
 
Digwc
DigwcDigwc
Digwc
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12
 
Html Frames
Html FramesHtml Frames
Html Frames
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash Tutorial
 

Recently uploaded

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2DianaGray10
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...Product School
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...Product School
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutesconfluent
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Alison B. Lowndes
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsPaul Groth
 

Recently uploaded (20)

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Speed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in MinutesSpeed Wins: From Kafka to APIs in Minutes
Speed Wins: From Kafka to APIs in Minutes
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1UiPath Test Automation using UiPath Test Suite series, part 1
UiPath Test Automation using UiPath Test Suite series, part 1
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 

7java Events

  • 1. 1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Handling Mouse and Keyboard Events
  • 2. Handling Mouse and Keyboard Events2 www.corewebprogramming.com 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
  • 3. Handling Mouse and Keyboard Events3 www.corewebprogramming.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
  • 4. Handling Mouse and Keyboard Events4 www.corewebprogramming.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()); } }
  • 5. Handling Mouse and Keyboard Events5 www.corewebprogramming.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() + ")."); } }
  • 6. Handling Mouse and Keyboard Events6 www.corewebprogramming.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
  • 7. Handling Mouse and Keyboard Events7 www.corewebprogramming.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()); } }
  • 8. Handling Mouse and Keyboard Events8 www.corewebprogramming.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); } }
  • 9. Handling Mouse and Keyboard Events9 www.corewebprogramming.com Separate Listener: General Case (Results)
  • 10. Handling Mouse and Keyboard Events10 www.corewebprogramming.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); }
  • 11. Handling Mouse and Keyboard Events11 www.corewebprogramming.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); } }
  • 12. Handling Mouse and Keyboard Events12 www.corewebprogramming.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()); }
  • 13. Handling Mouse and Keyboard Events13 www.corewebprogramming.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); } } }
  • 14. Handling Mouse and Keyboard Events14 www.corewebprogramming.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); } }); } }
  • 15. Handling Mouse and Keyboard Events15 www.corewebprogramming.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
  • 16. Handling Mouse and Keyboard Events16 www.corewebprogramming.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
  • 17. Handling Mouse and Keyboard Events17 www.corewebprogramming.com Standard AWT Event Listeners (Summary) Adapter Class Listener (If Any) Re ActionListener addA AdjustmentListener addA ComponentListener ComponentAdapter addC ContainerListener ContainerAdapter addC FocusListener FocusAdapter addF ItemListener addI KeyListener KeyAdapter addK MouseListener MouseAdapter addM MouseMotionListener MouseMotionAdapter addM TextListener addT WindowListener WindowAdapter addW gistration Method ctionListener djustmentListener omponentListener ontainerListener ocusListener temListener eyListener ouseListener ouseMotionListener extListener indowListener
  • 18. Handling Mouse and Keyboard Events18 www.corewebprogramming.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)
  • 19. Handling Mouse and Keyboard Events19 www.corewebprogramming.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)
  • 20. Handling Mouse and Keyboard Events20 www.corewebprogramming.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
  • 21. Handling Mouse and Keyboard Events21 www.corewebprogramming.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 – Applies on release if no movement since press • MouseMotionListener – Handles mouse movement • mouseMoved(MouseEvent event) • mouseDragged(MouseEvent event)
  • 22. Handling Mouse and Keyboard Events22 www.corewebprogramming.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
  • 23. Handling Mouse and Keyboard Events23 www.corewebprogramming.com Mouse Events: Details • MouseListener and MouseMotionListener share event types • Location of clicks – event.getX() and event.getY() • 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.
  • 24. Handling Mouse and Keyboard Events24 www.corewebprogramming.com Simple Example: Spelling- Correcting Textfield • KeyListener corrects spelling during typing • ActionListener completes word on ENTER • FocusListener gives subliminal hints
  • 25. Handling Mouse and Keyboard Events25 www.corewebprogramming.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; }
  • 26. Handling Mouse and Keyboard Events26 www.corewebprogramming.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()); } } ...
  • 27. Handling Mouse and Keyboard Events27 www.corewebprogramming.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); } } }
  • 28. Handling Mouse and Keyboard Events28 www.corewebprogramming.com Simple Whiteboard (Results)
  • 29. Handling Mouse and Keyboard Events29 www.corewebprogramming.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()); }
  • 30. Handling Mouse and Keyboard Events30 www.corewebprogramming.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); } } }
  • 31. Handling Mouse and Keyboard Events31 www.corewebprogramming.com Whiteboard (Results)
  • 32. Handling Mouse and Keyboard Events32 www.corewebprogramming.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
  • 33. 33 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Questions?
  • 34. Handling Mouse and Keyboard Events34 www.corewebprogramming.com 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, 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