Handling Mouse and Keyboard Events

Similar documents
Advanced Java Programming (17625) Event Handling. 20 Marks

The AWT Event Model 9

GUI Event Handlers (Part I)

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

Dogodkovno vodeno programiranje

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

GUI Event Handling 11. GUI Event Handling. Objectives. What is an Event? Hierarchical Model (JDK1.0) Delegation Model (JDK1.1)

Interacción con GUIs

COURSE 7 PROGRAMMING III OOP. JAVA LANGUAGE

OBJECT ORIENTED PROGRAMMING. Java GUI part 1 Loredana STANCIU Room B616

SD Module-1 Advanced JAVA

SD Module-1 Advanced JAVA. Assignment No. 4

GUI in Java TalentHome Solutions

Išdėstymai. Lekt. dr. Pijus Kasparaitis m. m. pavasario semestras.

Chapter 1 GUI Applications

Graphical User Interfaces 2

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI

Graphical User Interfaces 2

Programming Languages and Techniques (CIS120)

Graphical User Interfaces 2

Unit 7: Event driven programming

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

BM214E Object Oriented Programming Lecture 13

Computer Science 210: Data Structures. Intro to Java Graphics

Programming Languages and Techniques (CIS120)

G51PRG: Introduction to Programming Second semester Applets and graphics

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

ECE 462 Object-Oriented Programming using C++ and Java. Key Inputs in Java Games

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

Outline. More on the Swing API Graphics: double buffering and timers Model - View - Controller paradigm Applets

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently.

GUI Event Handlers (Part II)

class BankFilter implements Filter { public boolean accept(object x) { BankAccount ba = (BankAccount) x; return ba.getbalance() > 1000; } }

Programming Languages and Techniques (CIS120)

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

Dr. Hikmat A. M. AbdelJaber

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Systems Programming Graphical User Interfaces

Computer Programming Java AWT Lab 18

CS 251 Intermediate Programming GUIs: Event Listeners

Packages: Putting Classes Together

Programming Languages and Techniques (CIS120)

Course: CMPT 101/104 E.100 Thursday, November 23, 2000

What Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { }

User interfaces and Swing

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan

Module 4 Multi threaded Programming, Event Handling. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

GUI (Graphic User Interface) Programming. Part 2 (Chapter 8) Chapter Goals. Events, Event Sources, and Event Listeners. Listeners

More Swing. CS180 Recitation 12/(04,05)/08

Event Driven Programming

ISO-2022-JP (JIS ) 1 2. (Windows95/98 MacOS ) Java UNICODE UNICODE. Java. .java.java.txt native2ascii. .java

Programming Languages and Techniques (CIS120)

Advanced Java Programming

MIT AITI Swing Event Model Lecture 17

Swing from A to Z Using Focus in Swing, Part 2. Preface

H212 Introduction to Software Systems Honors

Which of the following syntax used to attach an input stream to console?

Programming Mobile Devices J2SE GUI

Using Lambdas to Write Mixins in Java 8

AP Computer Science Unit 13. Still More Graphics and Animation.

Java Event Handling -- 1

COMPSCI 230. Software Design and Construction. Swing

Module 4 Multi threaded Programming, Event Handling. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

CSSE 220. Event Based Programming. Check out EventBasedProgramming from SVN

Introduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

Lecture 5: Java Graphics

Lecture 3: Java Graphics & Events

SAMPLE EXAM Exam 2 Computer Programming 230 Dr. St. John Lehman College City University of New York Thursday, 5 November 2009

Introduction to the JAVA UI classes Advanced HCI IAT351

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Component-Based Behavioural Modelling with High-Level Petri Nets

CS11 Java. Fall Lecture 4

ว ฒนพงศ ส ทธภ กด Java Programming ( )

GUI Programming: Swing and Event Handling

GUI 4.1 GUI GUI MouseTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; /* 1 */

Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition

HW#1: Pencil Me In Status!? How was Homework #1? Reminder: Handouts. Homework #2: Java Draw Demo. 3 Handout for today! Lecture-Homework mapping.

3 Events and Listeners

TYPES OF INTERACTORS Prasun Dewan Department of Computer Science University of North Carolina at Chapel Hill

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

กล ม API ท ใช. Programming Graphical User Interface (GUI) Containers and Components 22/05/60

Chapter 14: Applets and More

8/23/2014. Chapter Topics. Introduction to Applets. Introduction to Applets. Introduction to Applets. Applet Limitations. Chapter 14: Applets and More

Java AWT Windows, Text, & Graphics

Java for Interfaces and Networks (DT3010, HT10)

Programming Languages 2nd edition Tucker and Noonan"

CS 335 Graphics and Multimedia. Image Manipulation

Swing from A to Z Some Simple Components. Preface

Overloading Example. Overloading. When to Overload. Overloading Example (cont'd) (class Point continued.)

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

CS11 Java. Fall Lecture 3

CS2110. GUIS: Listening to Events

Assignment No 2. Year: Dept.: ComputerTech. Sanjivani Rural Education Society s Sanjivani KBP Polytechnic, Kopargaon

Transcription:

Handling Mouse and Keyboard Events 605.481 1 Java Event Delegation Model <interface> <interface> EventListener handleevent(eventobject handleevent(eventobject e); e); EventListenerObject source.addlistener(this); source.addlistener(this); handleevent(eventobject handleevent(eventobject e) e) { { : : : : register Broadcast EventObject EventSource List List eventlisteners; eventlisteners; addlistener(eventlistener addlistener(eventlistener l) l) { { eventlisteners.add(l); eventlisteners.add(l); notify(eventobject notify(eventobject e) e) { { for for each each eventlistener eventlistener l l { { l.handleevent(e); l.handleevent(e); 2 1

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 3 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 javax.swing.*; import java.awt.*; 4 public class ClickReporter extends JFrame { public ClickReporter() { super( ClickReporter ); setdefaultcloseoperation(jframe.dispose_on_close); getcontentpane().setbackground(color.yellow); getcontentpane().addmouselistener( new ClickListener()); 2

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 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 3

Handling Events with Separate Listener: General Case import javax.swing.*; import java.awt.*; public class CircleDrawer1 extends JFrame { public void CircleDrawer1() { super( CircleDrawer1 ); setdefaultcloseoperation(jframe.dispose_on_close); getcontentpane().setforeground(color.blue); getcontentpane().addmouselistener(new CircleListener()); 7 Separate Listener: General Case (Continued) import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CircleListener extends MouseAdapter { private int radius = 25; 8 public void mousepressed(mouseevent event) { JPanel app = (JPanel)event.getSource(); Graphics g = app.getgraphics(); g.filloval(event.getx()-radius, event.gety()-radius, 2*radius, 2*radius); 4

Separate Listener: General Case (Results) 9 Case 2: Implementing a Listener Interface import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CircleDrawer2 extends JFrame implements MouseListener { private int radius = 25; public CircleDrawer2() { super( CircleDrawer2 ); setdefaultcloseoperation(jframe.dispose_on_close); getcontentpane().setforeground(color.blue); getcontentpane().addmouselistener(this); 10 5

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 Case 3: Named Inner Classes import javax.swing.jframe; import java.awt.*; import java.awt.event.*; public class CircleDrawer3 extends JFrame { public CircleDrawer3() { super( CircleDrawer3 ); setdefaultcloseoperation(jframe.dispose_on_close); getcontentpane().setforeground(color.blue); getcontentpane().addmouselistener(new CircleListener()); 12 6

Named Inner Classes (Continued) Note: still part of class from previous slide private class CircleListener extends MouseAdapter { private int radius = 25; 13 public void mousepressed(mouseevent event) { Graphics g = getgraphics(); g.filloval(event.getx()-radius, event.gety()-radius, 2*radius, 2*radius); Case 4: Anonymous Inner Classes public class CircleDrawer4 extends JFrame { public CircleDrawer4() { super( CircleDrawer4 ); getcontentpane().setforeground(color.blue); getcontentpane().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 7

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 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 8

Standard AWT Event Listeners (Summary) Adapter Class Listener (If Any) Registration Method ActionListener addactionlistener AdjustmentListener addadjustmentlistener ComponentListener ComponentAdapter addcomponentlistener ContainerListener ContainerAdapter addcontainerlistener FocusListener FocusAdapter addfocuslistener ItemListener additemlistener KeyListener KeyAdapter addkeylistener MouseListener MouseAdapter addmouselistener MouseMotionListener MouseMotionAdapter addmousemotionlistener TextListener addtextlistener WindowListener WindowAdapter addwindowlistener 17 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 9

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 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 10

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 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 11

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

Example: Simple Whiteboard import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SimpleWhiteboard extends JFrame { protected int lastx=0, lasty=0; public SimpleWhiteBoard() { super( SimpleWhiteBoard ); setdefaultcloseoperation(jframe.dispose_on_close); getcontentpane().setbackground(color.white); getcontentpane().setforeground(color.blue); getcontentpane().addmouselistener(new PositionRecorder()); getcontentpane().addmousemotionlistener(new LineDrawer()); protected void record(int x, int y) { lastx = x; lasty = y; 25 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 13

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 Simple Whiteboard (Results) 28 14

Whiteboard: Adding Keyboard Events import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Whiteboard extends SimpleWhiteboard { protected FontMetrics fm; public Whiteboard() { super(); Font font = new Font("Serif", Font.BOLD, 20); getcontentpane().setfont(font); fm = getfontmetrics(font); addkeylistener(new CharDrawer()); 29 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 15

Whiteboard (Results) 31 Questions? 32 16

Further Reading Core Web Programming, Hall and Brown Chapter 11 Core Java, Volume I Fundamentals Horstmann and Cornell Chapter 8 Free Resources The Java Tutorial http://java.sun.com/docs/books/tutorial/uiswing/events/index.html Other links http://java.sun.com/developer/onlinetraining/programming/basicjava1/front.html#event http://java.sun.com/developer/onlinetraining/awt/contents.html#eventsx http://java.sun.com/developer/onlinetraining/gui/swing2/shortcourse.html#jfcevents 33 17