Docsity

Java Event Handling: Handling Mouse and Keyboard Events, Study notes of Java Programming

Toggle sidebar
bg1
© 2014 Marty Hall
Customized Java EE Training: http://courses.coreservlets.com/
Java 7, Java 8, JSF 2.2, PrimeFaces, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Handling Mouse and
Keyboard Events
2
Originals of slides and source code for examples: http://courses.coreservlets.com/Course-Materials/java.html
Also see the Java 8 tutorial – http://www.coreservlets.com/java-8-tutorial/
and customized Java training courses (onsite or at public venues) – http://courses.coreservlets.com/java-training.html
© 2014 Marty Hall
Customized Java EE Training: http://courses.coreservlets.com/
Java 7, Java 8, JSF 2.2, PrimeFaces, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Taught by lead author of Core Servlets & JSP, co-author of
Core JSF (4th Ed), & this tutorial. Available at public venues, or
customized versions can be held on-site at your organization.
•Courses developed and taught by Marty Hall
–JSF 2.2, PrimeFaces, servlets/JSP, Ajax, jQuery, Android development, Java 7 or 8 programming, custom mix of topics
–Courses available in any state or country. Maryland/DC area companies can also choose afternoon/evening courses.
•Courses developed and taught by coreservlets.com experts (edited by Marty)
–Spring, Hibernate/JPA, GWT, Hadoop, HTML5, RESTful Web Ser vices
Contact [email protected] for details
For live Java-related training,
Marty is also available for consulting and development support
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19

Partial preview of the text

Download Java Event Handling: Handling Mouse and Keyboard Events and more Study notes Java Programming in PDF only on Docsity!

© 2014 Marty Hall

Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2.2, PrimeFaces, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Handling Mouse and

Keyboard Events

2

Originals of slides and source code for examples: http://courses.coreservlets.com/Course-Materials/java.html Also see the Java 8 tutorial – http://www.coreservlets.com/java-8-tutorial/ and customized Java training courses (onsite or at public venues) – http://courses.coreservlets.com/java-training.html

© 2014 Marty Hall

Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2.2, PrimeFaces, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Taught by lead author of Core Servlets & JSP , co-author of

Core JSF (4th^ Ed), & this tutorial. Available at public venues, or

customized versions can be held on-site at your organization.

  • Courses developed and taught by Marty Hall
    • JSF 2.2, PrimeFaces, servlets/JSP, Ajax, jQuery, Android development, Java 7 or 8 programming, custom mix of topics
    • Courses available in any state or country. Maryland/DC area companies can also choose afternoon/evening courses.
  • Courses developed and taught by coreservlets.com experts (edited by Marty)
    • Spring, Hibernate/JPA, GWT, Hadoop, HTML5, RESTful Web Services Contact [email protected] for details

For live Java-related training, email [email protected]

Marty is also available for consulting and development support

Topics in This Section

  • General asynchronous event-handling strategy
  • Event-handling options
    • Handling events with separate listeners
    • Handling events by implementing interfaces
    • Handling events with named inner classes
    • Handling events with anonymous inner classes
    • Preview: handling events with Java 8 lambdas
  • The standard AWT listener types
  • Subtleties with mouse events
  • Examples

4

Techniques are Widely

Applicable

  • Handler for mouse/keyboard events
    • Separate classes
    • Main class implementing interface
    • Named inner classes
    • Anonymous inner classes
    • Lambdas
  • Handler for GUI controls (buttons, sliders, etc.)
    • Same options with same pros/cons
  • “Handler” (code to run in background) for multithreaded programming - Same options with same pros/cons
  • “Handler” (code to compare elements) for array sorting - Same options with same pros/cons

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());

8

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() + ").");

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

10

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());

© 2014 Marty Hall

Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2.2, PrimeFaces, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Implementing a Listener

Interface

14

Review of Interfaces: Syntax

• Shape interface

public interface Shape { public double getArea(); // No body, just specification }

• Circle class

public class Circle implements Shape { public double getArea() { some real code } }

• Note

  • You can implement many interfaces
    • public class MyClass implements Foo, Bar, Baz { … }

Review of Interfaces: Benefits

  • Class can be treated as interface type
    • public interface Shape { public double getArea(); }
    • public class Circle implements Shape { … }
    • public class Rectangle implements Shape { … }

Shape[] shapes =

{ new Circle(…), new Rectangle(…) … };

double sum = 0;

for(Shape s: shapes) {

sum = sum + s.getArea(); // All Shapes have getArea

16

Source Code for MouseListener

and MouseAdapter (Simplified)

public interface MouseListener { public void mouseClicked(MouseEvent e); public void mousePressed(MouseEvent e); public void mouseReleased(MouseEvent e); public void mouseEntered(MouseEvent e); public void mouseExited(MouseEvent e); }

public abstract class MouseAdapter implements MouseListener { public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }

Adapters vs. Interfaces: Method Signature Errors

  • What if you goof on the method signature?
    • public void mousepressed(MouseEvent e)
    • public void mousePressed()
  • Interfaces
    • Compile time error
  • Adapters
    • No compile time error, but nothing happens at run time when you press the mouse
  • Solution for adapters (and overriding in Java 5+ in general): @Override annotation - Whenever you think you are overriding a method, put “@Override” on the line above the start of the method. - If that method is not actually overriding an inherited

method, you get a compile-time error.

20

@Override Examples

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

public class CircleListener extends MouseAdapter { private int radius = 25; @Override public void mousePressed(MouseEvent event) { Applet app = (Applet)event.getSource(); Graphics g = app.getGraphics(); g.fillOval(event.getX()-radius, event.getY()-radius, 2radius, 2radius); } }

© 2014 Marty Hall

Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2.2, PrimeFaces, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Using Inner Classes

(Named & Anonymous)

22

Summary of Inner Classes

  • Class can be defined inside another class
    • Methods in the inner class can access all methods and instance

variables of surrounding class

  • Even private methods and variables
  • Example public class OuterClass { private int count = …;

public void foo(…) { InnerClass inner = new InnerClass(); inner.bar(); }

private class InnerClass { public void bar() { doSomethingWith(count); } }

23 }

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, 2radius, 2radius); } }); } (^26) }

© 2014 Marty Hall

Customized Java EE Training: http://courses.coreservlets.com/ Java 7, Java 8, JSF 2.2, PrimeFaces, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.

Summary of

Approaches

Event Handling Strategies:

Pros and Cons

  • Separate Listener
    • Advantages
      • Can extend adapter and thus ignore unused methods
      • Can pass arguments to class constructor
      • Separate class is more reusable
    • 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
      • Hard to have multiple different versions since you cannot

28 pass arguments to listener

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
      • Can define constructor and pass arguments
    • Disadvantage
      • A bit harder to understand
  • Anonymous inner class
    • Advantages
      • Same as named inner classes
      • Even shorter
    • Disadvantage
      • Harder to understand

29 • Not reusable

Standard AWT Event Listeners

(Summary)

32

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

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)

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)

34

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

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; (^38) }

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()); } } ...

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); } } }

40

Simple Whiteboard (Results)