SlideShare a Scribd company logo
core


                          programming

    Handling Mouse and
     Keyboard Events


1    © 2001-2003 Marty Hall, Larry Brown http://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


2       Handling Mouse and Keyboard Events   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());
3
              • E.g., addKeyListener, addMouseListener
     Handling Mouse and Keyboard Events       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());
      }
    }



4    Handling Mouse and Keyboard Events   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() + ").");
      }
    }




5    Handling Mouse and Keyboard Events   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



6    Handling Mouse and Keyboard Events      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());
      }
    }




7    Handling Mouse and Keyboard Events   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);
        }
    }
8       Handling Mouse and Keyboard Events   www.corewebprogramming.com
Separate Listener: General
    Case (Results)




9   Handling Mouse and Keyboard Events   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);
       }




10    Handling Mouse and Keyboard Events   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);
         }
     }


11       Handling Mouse and Keyboard Events                 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());
       }




12    Handling Mouse and Keyboard Events   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);
              }
         }
     }
13       Handling Mouse and Keyboard Events   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);
                         }
                  });
         }
     }
14       Handling Mouse and Keyboard Events         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

15    Handling Mouse and Keyboard Events        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
16    Handling Mouse and Keyboard Events       www.corewebprogramming.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         addM ouseListener
     MouseMotionListener                  MouseMotionAdapter   addM ouseMotionListener
     TextListener                                              addTextListener
     WindowListener                       WindowAdapter        addWindowListener




17   Handling Mouse and Keyboard Events                        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)

18    Handling Mouse and Keyboard Events       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)




19    Handling Mouse and Keyboard Events         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




20    Handling Mouse and Keyboard Events           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)
21    Handling Mouse and Keyboard Events        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




22    Handling Mouse and Keyboard Events         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.
23    Handling Mouse and Keyboard Events   www.corewebprogramming.com
Simple Example: Spelling-
     Correcting Textfield
     • KeyListener corrects spelling during typing
     • ActionListener completes word on ENTER
     • FocusListener gives subliminal hints




24    Handling Mouse and Keyboard Events   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;
       }
25     Handling Mouse and Keyboard Events   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());
         }
     }
     ...




26   Handling Mouse and Keyboard Events   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);
           }
         }
     }




27       Handling Mouse and Keyboard Events   www.corewebprogramming.com
Simple Whiteboard (Results)




28   Handling Mouse and Keyboard Events   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());
       }



29     Handling Mouse and Keyboard Events   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);
             }
         }
     }




30       Handling Mouse and Keyboard Events   www.corewebprogramming.com
Whiteboard (Results)




31   Handling Mouse and Keyboard Events   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
32    Handling Mouse and Keyboard Events                 www.corewebprogramming.com
core


                          programming

              Questions?


33   © 2001-2003 Marty Hall, Larry Brown http://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


34    Handling Mouse and Keyboard Events            www.corewebprogramming.com

More Related Content

What's hot

A split screen-viable UI event system - Unite Copenhagen 2019
A split screen-viable UI event system - Unite Copenhagen 2019A split screen-viable UI event system - Unite Copenhagen 2019
A split screen-viable UI event system - Unite Copenhagen 2019
Unity Technologies
 
Creating Ext GWT Extensions and Components
Creating Ext GWT Extensions and ComponentsCreating Ext GWT Extensions and Components
Creating Ext GWT Extensions and Components
Sencha
 
Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVA
Srajan Shukla
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
Ayesha Kanwal
 
Unity 13 space shooter game
Unity 13 space shooter gameUnity 13 space shooter game
Unity 13 space shooter game
吳錫修 (ShyiShiou Wu)
 
Unity3 d devfest-2014
Unity3 d devfest-2014Unity3 d devfest-2014
Unity3 d devfest-2014
Vincenzo Favara
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
OXUS 20
 
The java swing_tutorial
The java swing_tutorialThe java swing_tutorial
The java swing_tutorial
sumitjoshi01
 
Android accelerometer sensor tutorial
Android accelerometer sensor tutorialAndroid accelerometer sensor tutorial
Android accelerometer sensor tutorial
info_zybotech
 
Hack2the future Microsoft .NET Gadgeteer
Hack2the future Microsoft .NET GadgeteerHack2the future Microsoft .NET Gadgeteer
Hack2the future Microsoft .NET Gadgeteer
Lee Stott
 
Session 12 - Overview of taps, multitouch, and gestures
Session 12 - Overview of taps, multitouch, and gestures Session 12 - Overview of taps, multitouch, and gestures
Session 12 - Overview of taps, multitouch, and gestures
Vu Tran Lam
 
Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Unity Technologies
 
AWTEventModel
AWTEventModelAWTEventModel
AWTEventModel
Arjun Shanka
 

What's hot (13)

A split screen-viable UI event system - Unite Copenhagen 2019
A split screen-viable UI event system - Unite Copenhagen 2019A split screen-viable UI event system - Unite Copenhagen 2019
A split screen-viable UI event system - Unite Copenhagen 2019
 
Creating Ext GWT Extensions and Components
Creating Ext GWT Extensions and ComponentsCreating Ext GWT Extensions and Components
Creating Ext GWT Extensions and Components
 
Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVA
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
 
Unity 13 space shooter game
Unity 13 space shooter gameUnity 13 space shooter game
Unity 13 space shooter game
 
Unity3 d devfest-2014
Unity3 d devfest-2014Unity3 d devfest-2014
Unity3 d devfest-2014
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
 
The java swing_tutorial
The java swing_tutorialThe java swing_tutorial
The java swing_tutorial
 
Android accelerometer sensor tutorial
Android accelerometer sensor tutorialAndroid accelerometer sensor tutorial
Android accelerometer sensor tutorial
 
Hack2the future Microsoft .NET Gadgeteer
Hack2the future Microsoft .NET GadgeteerHack2the future Microsoft .NET Gadgeteer
Hack2the future Microsoft .NET Gadgeteer
 
Session 12 - Overview of taps, multitouch, and gestures
Session 12 - Overview of taps, multitouch, and gestures Session 12 - Overview of taps, multitouch, and gestures
Session 12 - Overview of taps, multitouch, and gestures
 
Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019Building a turn-based game prototype using ECS - Unite Copenhagen 2019
Building a turn-based game prototype using ECS - Unite Copenhagen 2019
 
AWTEventModel
AWTEventModelAWTEventModel
AWTEventModel
 

Viewers also liked

Chapter11 graphical components
Chapter11 graphical componentsChapter11 graphical components
Chapter11 graphical components
Arifa Fatima
 
Course File c++
Course File c++Course File c++
Course File c++
emailharmeet
 
Animal Handling Program
Animal Handling ProgramAnimal Handling Program
Animal Handling Program
DRx.Yogesh Chaudhari
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
Tanmay Baranwal
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
PRN USM
 
Arrays C#
Arrays C#Arrays C#
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
Eduardo Bergavera
 

Viewers also liked (7)

Chapter11 graphical components
Chapter11 graphical componentsChapter11 graphical components
Chapter11 graphical components
 
Course File c++
Course File c++Course File c++
Course File c++
 
Animal Handling Program
Animal Handling ProgramAnimal Handling Program
Animal Handling Program
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Arrays C#
Arrays C#Arrays C#
Arrays C#
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and OutputChapter 12 - File Input and Output
Chapter 12 - File Input and Output
 

Similar to Java-Events

7java Events
7java Events7java Events
7java Events
Adil Jafri
 
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
MarlouFelixIIICunana
 
What is Event
What is EventWhat is Event
What is Event
Asmita Prasad
 
Event handling63
Event handling63Event handling63
Event handling63
myrajendra
 
Awt event
Awt eventAwt event
Awt event
Vijay Kumar
 
Advance ui development and design
Advance ui  development and design Advance ui  development and design
Advance ui development and design
Rakesh Jha
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
sharanyak0721
 
Gu iintro(java)
Gu iintro(java)Gu iintro(java)
Gu iintro(java)
Satish Verma
 
Gui
GuiGui
Java
JavaJava
AWT
AWT AWT
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
Jyothishmathi Institute of Technology and Science Karimnagar
 
Java awt
Java awtJava awt
14a-gui.ppt
14a-gui.ppt14a-gui.ppt
14a-gui.ppt
DrDGayathriDevi
 
The java rogramming swing _tutorial for beinners(java programming language)
The java rogramming swing _tutorial for beinners(java programming language)The java rogramming swing _tutorial for beinners(java programming language)
The java rogramming swing _tutorial for beinners(java programming language)
Daroko blog(www.professionalbloggertricks.com)
 
openFrameworks 007 - events
openFrameworks 007 - eventsopenFrameworks 007 - events
openFrameworks 007 - events
roxlu
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
usvirat1805
 
Flash Lite & Touch: build an iPhone-like dynamic list
Flash Lite & Touch: build an iPhone-like dynamic listFlash Lite & Touch: build an iPhone-like dynamic list
Flash Lite & Touch: build an iPhone-like dynamic list
Small Screen Design
 
EventBus for Android
EventBus for AndroidEventBus for Android
EventBus for Android
greenrobot
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
Jussi Pohjolainen
 

Similar to Java-Events (20)

7java Events
7java Events7java Events
7java Events
 
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
 
What is Event
What is EventWhat is Event
What is Event
 
Event handling63
Event handling63Event handling63
Event handling63
 
Awt event
Awt eventAwt event
Awt event
 
Advance ui development and design
Advance ui  development and design Advance ui  development and design
Advance ui development and design
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
 
Gu iintro(java)
Gu iintro(java)Gu iintro(java)
Gu iintro(java)
 
Gui
GuiGui
Gui
 
Java
JavaJava
Java
 
AWT
AWT AWT
AWT
 
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
 
Java awt
Java awtJava awt
Java awt
 
14a-gui.ppt
14a-gui.ppt14a-gui.ppt
14a-gui.ppt
 
The java rogramming swing _tutorial for beinners(java programming language)
The java rogramming swing _tutorial for beinners(java programming language)The java rogramming swing _tutorial for beinners(java programming language)
The java rogramming swing _tutorial for beinners(java programming language)
 
openFrameworks 007 - events
openFrameworks 007 - eventsopenFrameworks 007 - events
openFrameworks 007 - events
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 
Flash Lite & Touch: build an iPhone-like dynamic list
Flash Lite & Touch: build an iPhone-like dynamic listFlash Lite & Touch: build an iPhone-like dynamic list
Flash Lite & Touch: build an iPhone-like dynamic list
 
EventBus for Android
EventBus for AndroidEventBus for Android
EventBus for Android
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 

More from Arjun Shanka

Asp.net w3schools
Asp.net w3schoolsAsp.net w3schools
Asp.net w3schools
Arjun Shanka
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
Arjun Shanka
 
Sms several papers
Sms several papersSms several papers
Sms several papers
Arjun Shanka
 
System simulation 06_cs82
System simulation 06_cs82System simulation 06_cs82
System simulation 06_cs82Arjun Shanka
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
Arjun Shanka
 
javainheritance
javainheritancejavainheritance
javainheritance
Arjun Shanka
 
javarmi
javarmijavarmi
javarmi
Arjun Shanka
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
Arjun Shanka
 
hibernate
hibernatehibernate
hibernate
Arjun Shanka
 
javapackage
javapackagejavapackage
javapackage
Arjun Shanka
 
javaarray
javaarrayjavaarray
javaarray
Arjun Shanka
 
swingbasics
swingbasicsswingbasics
swingbasics
Arjun Shanka
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
Arjun Shanka
 
struts
strutsstruts
struts
Arjun Shanka
 
javathreads
javathreadsjavathreads
javathreads
Arjun Shanka
 
javabeans
javabeansjavabeans
javabeans
Arjun Shanka
 
72185-26528-StrutsMVC
72185-26528-StrutsMVC72185-26528-StrutsMVC
72185-26528-StrutsMVC
Arjun Shanka
 
javanetworking
javanetworkingjavanetworking
javanetworking
Arjun Shanka
 
javaiostream
javaiostreamjavaiostream
javaiostream
Arjun Shanka
 

More from Arjun Shanka (20)

Asp.net w3schools
Asp.net w3schoolsAsp.net w3schools
Asp.net w3schools
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Sms several papers
Sms several papersSms several papers
Sms several papers
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
System simulation 06_cs82
System simulation 06_cs82System simulation 06_cs82
System simulation 06_cs82
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
javainheritance
javainheritancejavainheritance
javainheritance
 
javarmi
javarmijavarmi
javarmi
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
hibernate
hibernatehibernate
hibernate
 
javapackage
javapackagejavapackage
javapackage
 
javaarray
javaarrayjavaarray
javaarray
 
swingbasics
swingbasicsswingbasics
swingbasics
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
struts
strutsstruts
struts
 
javathreads
javathreadsjavathreads
javathreads
 
javabeans
javabeansjavabeans
javabeans
 
72185-26528-StrutsMVC
72185-26528-StrutsMVC72185-26528-StrutsMVC
72185-26528-StrutsMVC
 
javanetworking
javanetworkingjavanetworking
javanetworking
 
javaiostream
javaiostreamjavaiostream
javaiostream
 

Recently uploaded

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Zilliz
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 

Recently uploaded (20)

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
Introducing Milvus Lite: Easy-to-Install, Easy-to-Use vector database for you...
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 

Java-Events

  • 1. core programming Handling Mouse and Keyboard Events 1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
  • 2. 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 2 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 3. 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()); 3 • E.g., addKeyListener, addMouseListener Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 4. 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()); } } 4 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 5. 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() + ")."); } } 5 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 6. 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 6 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 7. 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()); } } 7 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 8. 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); } } 8 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 9. Separate Listener: General Case (Results) 9 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 10. 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); } 10 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 11. 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); } } 11 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 12. 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()); } 12 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 13. 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); } } } 13 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 14. 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); } }); } } 14 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 15. 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 www.corewebprogramming.com
  • 16. 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 www.corewebprogramming.com
  • 17. 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 addM ouseListener MouseMotionListener MouseMotionAdapter addM ouseMotionListener TextListener addTextListener WindowListener WindowAdapter addWindowListener 17 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 18. 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) 18 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 19. 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 www.corewebprogramming.com
  • 20. 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 www.corewebprogramming.com
  • 21. 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 www.corewebprogramming.com
  • 22. 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 www.corewebprogramming.com
  • 23. 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. 23 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 24. Simple Example: Spelling- Correcting Textfield • KeyListener corrects spelling during typing • ActionListener completes word on ENTER • FocusListener gives subliminal hints 24 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 25. 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; } 25 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 26. 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()); } } ... 26 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 27. 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); } } } 27 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 28. Simple Whiteboard (Results) 28 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 29. 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()); } 29 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 30. 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); } } } 30 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 31. Whiteboard (Results) 31 Handling Mouse and Keyboard Events www.corewebprogramming.com
  • 32. 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 www.corewebprogramming.com
  • 33. core programming Questions? 33 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
  • 34. 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 34 Handling Mouse and Keyboard Events www.corewebprogramming.com