© 2001-2003 Marty Hall, Larry Brown Web core programming 1 Handling Mouse and Keyboard Events.

Slides:



Advertisements
Similar presentations
Event handling and listeners What is an event? user actions and context event sources and listeners Why should my programs be event- driven? User interaction.
Advertisements

1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Event Handling.
Inner Classes in Java CMSC 432 Shon Vick. 2 Conceptual Structure package p 1 class A 1 class A 2... class A n... package n class A 1 class A 2... class.
Jan Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg.
Events and the AWT The objectives of this chapter are: To understand the principles of the Java 1.1 event model To understand how the event model is used.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
Mouse Events and Keyboard Events
Lecture 24 Applets. Introduction to Applets Applets should NOT have main method but rather init, stop, paint etc They should be run through javac compiler.
Event Handling n Events: an event is an object that describes a state change in a source. n Event Sources: A source is an object that generates an event.
Event-Driven Programming
1 Gui Programming (Part I) Graphical User Interfaces (Part I) l Introduction to events. l A Brief history. l Event sources and listeners. l The delegation.
Intermediate Java1 An example that uses inner classes Week Four Continued.
EVENTS CSC 171 FALL 2004 LECTURE 16. “Traditional” Input In console applications, user input is under control of the program The program asks the user.
GUI Event Handling Nithya Raman. What is an Event? GUI components communicate with the rest of the applications through events. The source of an event.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
28-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Event Handling – GUI Part II.
Mouse Events. Handling Mouse Events Java provides two listener interfaces to handle mouse events: MouseListener;  MouseListener;  MouseMotionListener.
Java – Mouse / Keyboard Events and Layout Managers INE2720 Web Application Software Development Essential Materials.
1 CSE 331 More Events (Mouse, Keyboard, Window, Focus, Change, Document...) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D.
Cs884(Prasad)java12AWT1 Abstract Windowing Toolkit Support for Graphical User Interface (Event-driven programming)
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Pravin Yannawar, DOCS, NMU Jalgaon. Basic Java : Event handling in AWT and Swing 2 Objectives of This Session Explain the Event handling mechanism & demonstrate.
UID – Event Handling and Listeners Boriana Koleva
Event Handling. 2 GUIs are event driven –Generate events when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc.
Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.
CMSC 341 Making Java GUIs Functional. 09/29/2007 CMSC 341 Events 2 More on Swing Great Swing demo at /demos/jfc/SwingSet2/SwingSet2Plugin.html.
Object Oriented Programming.  Interface  Event Handling.
Event Handling. The signals that a program receives from the operating system as a result of the actions are called events. A window based program is.
Index Event Handling Events Event Source Event Listener Event Classes Action Event Class Adjustment event Class Event Source Event Listener Interface Using.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
Events in JAVA Needed for Applets and GUI based programs. Applet uses GUI to interact with user. Most of the events are generated by Mouse, Keyboard.
Event Handling. User actions are called “events” – Low-level window events Window changes – Low-level component events Mouse events, Keyboard events,
Event-Driven Programming CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
CS Lecture 04 Mice Lynda Thomas
1 Event Handling – Lecture 4 Prepared by: Ahmad Ramin Rahimee Assistant Professor ICTI.
Laboratory Study November, Demonstrates Life Cycle of an Applet + Mouse Events + Scrolling.
2/17/2016 DEPT OF CSE 1 EVENT HANDLING. 2/17/2016 DEPT OF CSE 2 Event handling is at the core of successful applet programming There are several types.
EVENT-DRIVEN PROGRAMMING Subject:T0934 / Multimedia Programming Foundation Session:2 Tahun:2009 Versi:1/0.
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
Event Listeners ActionListener –button,list AdjustmentListener-scroll bar ComponentListener-when component hidden…. ContainerListener-comp added or removed.
CSI 3125, Preliminaries, page 1 Event Handling. CSI 3125, Preliminaries, page 2 Event Handling An Event Change in the state of an object is known as event.
Mouse Events GUI. Types of Events  Below, are some of the many kinds of events, swing components generate. Act causing EventListener Type User clicks.
UQC117S2 Graphics Programming Lecture 2 Event Handling Program as a sequence of instructions Event -driven program Need to detect the event and carry out.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
TENTH LECTURE Event and listener. Events and Listeners An event can be defined as a type of signal to the program that something has happened. The event.
Dept. of CSIE, National University of Tainan 10/21/2012 Responding to User Input.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Events and Event Handling
Chapter 14 Event-Driven Programming
Welcome To java
Lecture 8 Object Oriented Programming Using Java
Programming in Java, 2e Sachin Malhotra Saurabh Choudhary.
CHAPTER Reacting to the user.
Chapter 12 Event-Driven Programming
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Handling User Events with Swing
Event Handling Chapter 2 Objectives
Lecture 09 Applets.
Programming in Java Event Handling
GUI Event Handling Nithya Raman.
CSE Software Engineering Fall 1999 Updated by J. Brown
Unit I: Chapter 1 Event handling.
Java events.
Web Design & Development Lecture 12
Chapter 16 Event-Driven Programming
Events, Event Handlers, and Threads
Presentation transcript:

© Marty Hall, Larry Brown Web core programming 1 Handling Mouse and Keyboard Events

Handling Mouse and Keyboard Events2 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 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 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 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 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 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 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 Separate Listener: General Case (Results)

Handling Mouse and Keyboard Events10 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 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 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 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 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 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 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 Standard AWT Event Listeners (Summary)

Handling Mouse and Keyboard Events18 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 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 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 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 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 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 Simple Example: Spelling- Correcting Textfield KeyListener corrects spelling during typing ActionListener completes word on ENTER FocusListener gives subliminal hints

Handling Mouse and Keyboard Events25 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 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 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 Simple Whiteboard (Results)

Handling Mouse and Keyboard Events29 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 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 Whiteboard (Results)

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

© Marty Hall, Larry Brown Web core programming 33 Questions?

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