Jan. 20041 Event Handling - 1.02 Yangjun Chen Dept. Business Computing University of Winnipeg.

Slides:



Advertisements
Similar presentations
CS7026 jQuery Events. What are Events?  jQuery is tailor-made to respond to events in an HTML page.  Events are actions that can be detected by your.
Advertisements

Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
1 Fac.Scienze – Università di Trento Programmazione 2 - Marco Ronchetti Events Gestione degli eventi.
Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
Jan Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg.
A graphical user interface (GUI) is a pictorial interface to a program. A good GUI can make programs easier to use by providing them with a consistent.
CS 178: Programming with Multimedia Objects Aditya P. Mathur Professor of Computer Sciences Purdue University, West Lafayette Sept 9, 2004 Last update:
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Aalborg Media Lab 23-Jun-15 Software Design Lecture 6 “Conditionals and Loops”
Event Handling. In this class we will cover: Keyboard Events Mouse Events Focus Events Action Interface Multicasting.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
Chapter Day 9. © 2007 Pearson Addison-Wesley. All rights reserved4-2 Agenda Day 8 Questions from last Class?? Problem set 2 posted  10 programs from.
Io package as Java’s basic I/O system continue’d.
Visual Basic Fundamental Concepts. Integrated Development Enviroment Generates startup form for new project on which to place controls. Features toolbox.
20-753: Fundamentals of Web Programming Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 16: Java Applets & AWT Fundamentals of Web Programming.
Introduction to Graphical User Interfaces. Objectives * Students should understand what a procedural program is. * Students should understand what an.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Welcome to CIS 083 ! Events CIS 068.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Typing Application Introducing Keyboard Events, Menus, Dialogs and the Dictionary.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
KeyListener and Keyboard Events Another type of listener listens for keyboard entry – the KeyListener which generates KeyEvents –to implement KeyListener,
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
Java Programming: Guided Learning with Early Objects
Cs884(Prasad)java12AWT1 Abstract Windowing Toolkit Support for Graphical User Interface (Event-driven programming)
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 - Graphical User Interface Concepts: Part.
CS 112 Department of Computer Science George Mason University CS 112 Department of Computer Science George Mason University Final Review Lecture 14.
Copyright © Curt Hill First Window Builder Program Easy GUIs in Eclipse.
7/3/00SEM107- © Kamin & ReddyClass 11 - Events - 1 Class 11 - Events r A couple of odds & ends m Component sizes  switch statement r Event types r Catching.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
Omer Boyaci.  GUIs are event driven.  When the user interacts with a GUI component, the interaction—known as an event—drives the program to perform.
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
Java Applets: GUI Components, Events, Etc. Ralph Westfall June, 2010.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Copyright © Curt Hill More Components Varying the input of Dev-C++ Windows Programs.
Object Oriented Programming.  Interface  Event Handling.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6 – Graphical User Interfaces Java Foundations: Introduction to Programming.
Index Event Handling Events Event Source Event Listener Event Classes Action Event Class Adjustment event Class Event Source Event Listener Interface Using.
Java Programming, 2E Introductory Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
Object-Oriented Application Development Using VB.NET 1 Chapter 10 VB.NET GUI Components Overview.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CIT 590 Intro to Programming Lecture 13. Some Eclipse shortcuts CTRL + SHIFT + F – format file (proper indentation etc). Please do this before you submit.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Chapter 6: Events in Java 1.0 Model –Event class –selecting component to handle –handleEvent method –helper methods (action, keyUp, mouseUp, etc.) 1.1.
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.
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.
Controlling Program Flow with Decision Structures.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
1 Java and AWT CPS 470 Spring 1998 Laura Campbell.
Jaeki Song ISQS6337 JAVA Lecture 10 Applets. Jaeki Song ISQS6337 JAVA Applet Applets run within the Web browser environment –Applets bring dynamic interaction.
Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.
Implement User Input Windows Development Fundamentals LESSON 2.4A.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
CSC 205 Programming II Lecture 5 AWT - I.
Visual Basic Fundamental Concepts
Responding to Events Event Handling in Java
Programming in Java Event Handling
Miscellaneous Topics #6: Polygons GUI Components and Event Handlers
Chap 7. Building Java Graphical User Interfaces
Graphical User Interfaces -- Introduction
Event Driven Programming
Introduction to Computing Using Java
AWT Components and Containers
Introduction to Event Handling
Constructors, GUI’s(Using Swing) and ActionListner
Presentation transcript:

Jan Event Handling Yangjun Chen Dept. Business Computing University of Winnipeg

Jan Outline: 1.02 Events Events in Java 1.02 The Event Class The Event Hierarchy Event Handling -handleEvent() -helper methods Keyboard Events Mouse Events Other Events

Jan Event Driven Programming Events can be generated by a lot of things: – moving the mouse, scrolling, clicking on buttons, a key press, etc. These events have to be recognized and handled by the program. Java provides methods for handling these events in the Event class. All events don’t have to be handled by you, for example, painting is an event that you don’t have to deal with. There are two event models in Java: Java 1.0 model and Java 1.1 model. - We will discuss the Java 1.0 event model and then Java 1.1.

Jan Event Class This class contains a large collection of class constants. – They are used to describe the nature of the event. –other constants provide additional information about the events. There are 27 class constants. They are used to represent different events:-Buttons, Checkboxes, Choices, Lists, MenuItems, and TextFields -Key presses - KEY_ PRESS, KEY_ RELEASE... -Mouse actions - MOUSE_ UP, MOUSE_ DOWN... -List selections - LIST_ SELECT, LIST_ DESELECT -Scrollbar actions - SCROLL_ LINE_ UP... -Window actions - WINDOW_ DESTROY... -File related events - LOAD_ FILE, SAVE_ FILE -Input focus events - GOT_ FOCUS, LOST_ FOCUS

Jan Event Class These names are declared to be public static final. – What does this mean? There are four constants describing multikey combinations (SHIFT_ MASK, ALT_ MASK, META_ MASK, CTRL_ MASK). F1 through F12, LEFT, RIGHT, UP, DOWN, HOME, END, PGUP, PGDN refer to other keys In addition to these class constants, the event class has a set of public instance variables that provide more information about the event. The important ones are shown below: -Object arg - miscellaneous information (i.e., label string) -int id - what kind of event it is (i. e. class constant) -Object target - the object that generated this event Not all these fields apply to all events. -The arg field will contain no useful information for mouse events.

Jan Event Hierarchy When an event is generated, Java creates a new Event object and places it into an event queue. -Event queue: a list of events waiting to be handled When the event is at the front of the list, Java will decide which object will get to handle the event first. -Ex. If a mouse click happens above a Checkbox, the ACTION_ EVENT event will be generated, so the Checkbox will be the first object to get that event. -The Checkbox might have a handleEvent() method that will handle or respond to the event. -Now, if the Checkbox didn’t have a method to handle this event, the event gets passed up to the next most appropriate object, the parent component.

Jan Event Hierarchy -Eventually, the event will be handled by one of the objects in the GUI, or it would never be handled and simply expire with no response. It’s important to note the path along which an event is transferred, from an object to its parent, is not up the class hierarchy but up the containment hierarchy or GUI hierarchy. Normally, an object should handle its own events whenever possible, but this isn’t possible all the time or wanted even. -Suppose the parent has access to information that the child does not, then it makes sense that the parent will handle the event.

Jan Event Hierarchy panel1 panel2 applet checkbox appletFrame panel1panel2 checkbox1 checkbox2checkbox3

Jan Event Hierarchy Event queue …... nextBttn previousBttn << >> Applet nextBttn previousBttn panel Applet previousBttn nextBttn panel

Jan Event Models Events are generated and flow through the system in roughly the same manner for both event models. The difference between the two models is how the events are processed. In the 1.02 event model, events flow through the program and are handled by a method called handleEvent() while in 1.1 event model the concept of listeners is used. handEvent() is defined within the Component class and mustbe overridden (writing your own method).

Jan handleEvent() Notice that handleEvent is made public so that the system can access it when needed. public boolean handleEvent( Event e) { if (e.id == Event.WINDOW_ DESTROY) { System.exit( 0); return true; } else return super.handleEvent( e); }

Jan handleEvent() The return from a handleEvent method determines what happens to the event when the method exits (when you are finished with it) -If handleEvent(e) returns true, then event e will die in this method and not propagated any further. -If false is returned, the event e will be passed up the visual hierarchy so that the parent object’s own handleEvent method can handle the event. super.handleEvent(e) will pass the event to the class immediately above the object in the class hierarchy. -Is this different from the GUI hierarchy? If handleEvent fails to return true, Java will try again by looking at the target’s helper methods like mouseDown or action.

Jan public class CardTest extends Applet{ Button nextBttn = new Button(“>>”); Button previoursBttn = new Button(“<<“); …... public boolean action( Event e, Object arg) { if (e. target == nextBttn) cdLayout. next( cardPanel); else if (e. target == previousBttn) cdLayout. previous( cardPanel); else return false; return true; } // end of action method } // end of class handleEvent

Jan public class CardTest extends Applet{ Button nextBttn = new Button(“>>”); B1 previoursBttn = new B1(“<<“); …... } // end of class class B1 extends Button { … public boolean action(Event e, Object arg) { … } handleEvent

Jan handleEvent(Event e) helper methods action(Event e, Object arg) keyDown(Event e, int key) … mouseDown(Event e, int x, int y) … gotFocus(Event e) ACTION_EVENT MOUSE_DOWN KEY_PRESS GOT_FOCUS Button, Checkbox, Choice List, MenuItem, TextField e.id == Event.ACTION_EVENT e.id == Event.KEY_PRESS …...

Jan Helper Methods These are also known as convenience methods because they are often more convenient to use than the handleEvent method. For instance, an ACTION_ EVENT is generated by a Button, Checkbox, Choice, List, MenuItem, or TextField object. Use the helper method action() which responds only to ACTION_ EVENTS. The action method takes two arguments, the event to be handled and another that has different meanings, depending on the event. public boolean action( Event e, Object arg) { // handler for one of the above mentioned objects }

Jan Helper Methods Other helper methods: -public boolean keyDown(Event e, int key) -public boolean keyUp(Event e, int key) These are invoked by key events with the key argument containing the code of the key pressed -public boolean mouseDown(Event e, int x, int y) -public boolean mouseDrag(Event e, int x, int y) -public boolean mouseExit(Event e, int x, int y) -public boolean mouseMove(Event e, int x, int y) -public boolean mouseUp(Event e, int x, int y) Invoked by the corresponding mouse events with x and y specifying the coordinates where the pointer was during the event, measured in the Component’s local coordinate system.

Jan Helper Methods All of these helper methods return a boolean value just like the handleEvent method. Now that we have an event, how do we know what type of event it is? As mentioned earlier, each Event has associated with it a list of fields that provide further information about the event. They are all public fields, so they can be referenced using the object’s name with the dot operator. The arg field is the most complex of them all because it depends on the type of event. For the ACTION_EVENTs in buttons, choices, lists, or menu items, the arg field is a string representing the label or name of the selected item.

Jan Helper Methods If an ACTION_EVENT was generated from a checkbox, the arg field would be a boolean value representing the new state of the checkbox. In a LIST_SELECT or LIST_DESELECT event, the arg field is the index of the list element that was selected. Another important field is the target field. This field can be used to categorize the event by using the boolean operator instanceof. -instanceof takes an operand on either side, the left side is a variable representing an object, the right side is a class name. It returns true if the variable is an instance of that type or an instance of a subclass of that type.

Jan Helper Methods public boolean action( Event e, Object arg) { if (e. target instanceof List) { // Once we get here, we know the event was triggered // within one of our three lists String c = (String) arg; // get the list item’s name if (e. target == sandwiches) System. out. println(“ Sandwich chosen: ” + c); else if( e. target == drinks) System. out. println(“ Drink chosen: ” + c); else if( e. target == sides) System. out. println(“ Side order chosen: ” +c); } // end of if block for List object

Jan Helper Methods // The event wasn’t triggered in a list, so we see if it came // from the superSize checkbox, the order button, // or the sizes chosen else if (e. target == superSize) System.out.println(“ Supersize box clicked!”); else if (e. target == order) System.out.println(“ Order button clicked!”); else if (e. target == sizes) System. out. println(“ Size choice clicked!”); return true; // We’ve handled all possible action events, // so kill the event } // end of action method

Jan Helper Methods This program deals with possible events that can happen in three List objects, a Checkbox object, a Button object, and a Choice object. To check if the event was one of the list objects, we first check to see if the event was an instance of a List type: -e. target instanceof List If it is an instance of a List object, then it is tested to see which list generated the event. Otherwise, we continue and find the appropriate object that generated the event.

Jan Keyboard Events To capture a keyboard event in the 1.02 model, use the keyDown() method: -public boolean keyDown( Event e, int key) { … } The key pressed is passed to the keyDown() method as the key argument, which is of type int. It is a Unicode representation of the key pressed. To use the key as a character, it must be cast to type char: -keypressed =( char) key; As with mouse clicks, each key down event has a corresponding key up event. -public boolean keyUp( Event e, int key) { … }

Jan Keyboard Events Example: To check the key constants of RIGHT, UP, DOWN, etc -if (key == Event. UP) { … } Because the values that these class variables hold are constants, a switch statement can be used to test for them. public boolean keyDown( Event e, int key) { System. out. println(“ ASCII value: ” +key); System. out. println(“ Character: ” + (char) key); return true; }

Jan Masks The modifier masks SHIFT_MASK, ALT_MASK, META_MASK, CTRL_MASK are used with key events to determine if a modifier key was pressed. When a key event is generated, the modifier key, if present, will set certain bits in the event’s modifiers field. Once a handler has control of an event, the modifier field can be tested to determine if any modifiers were pressed. To inspect these modifiers, we go back to the logical operators & and |. For example, suppose we use four bits to represent these four modifiers, in the order, SHIFT_MASK, ALT_MASK, META_MASK, CTRL_MASK.

Jan Masks We would then have these combinations or “masks” representing the modifiers pressed: no modifiers -1000Shift key pressed Alt key pressed Meta key pressed Ctrl key pressed Other combinations are possible, for example: -1101indicates that Shift- Alt- Ctrl keys were pressed. Using these masks we can extract a single bit from the modifiers field.

Jan Logical Operations Revisited AND function: -results in a 1 if both bits that are being ANDed together are 1 -example: OR function: -results in 1 if either or both of the arguments are 1 -example & |

Jan Masks So if e is an Event, the expression -e.modifiers & Event.ALT_MASK will result in 0 if the Alt key has not been pressed. We can use the OR operator to test for the presence of two or more modifiers Using the masks that were defined previously, we would have Event.SHIFT_MASK|Event.CTRL_MASK equal to the pattern So to test for the presence of either modifier: if (( e. modifiers&( Event. SHIFT_ MASK| Event. CTRL_MASK))!= 0) // One or both modifier keys were pressed else // neither was pressed

Jan Masks To check both modifiers simultaneously, we would write: if ((( e.modifiers & Event. SHIFT_ MASK) != 0) && (( e.modifiers & Event. CTRL_ MASK) != 0)) // Both modifier keys were pressed else // One wasn’t pressed or neither was pressed The Event class has methods that allow you to determine if a modifier key is present: controlDown(), metaDown(), shiftDown(). There is no method to test for the Alt key, masks must be used for that.

Jan Mouse Events Clicking the mouse will generate two events in the 1.02 AWT: a mouse down and a mouse up event. Handling mouse events are easy, you just have to override the right methods that were shown previously. Example: public boolean mouseDown( Event e, int x, int y) { System. out. println(“ Mouse down at “+ x+”,”+ y); return true; } By including this in your applets, every time the user clicks on the applet, the coordinates will be output.

Jan Spots Applet import java. awt. Graphics; import java. awt. Color; import java. awt. Event; public class Spots extends java. applet. Applet { final int MAXSPOTS = 10; int xspots[] = new int[ MAXSPOTS]; int yspots[] = new int[ MAXSPOTS]; int currspots = 0; public void init() { setBackground( Color. white); }//end of init() method

Jan Spots Applet public boolean mouseDown( Event e, int x, int y) { if (currspots < MAXSPOTS) { addspot( x, y); return true; } else { System. out. println(“ Too many spots!!”); return false; } } // end of the mouseDown method

Jan Spots Applet void addspot( int x, int y) { xspots[ currspots] = x; yspots[ currspots] = y; currspots++; repaint(); } // end of addspot method public void paint( Graphics g) { g. setColor( Color. blue); for (int i= 0; i< currspots; i++) { g. fillOval( xspots[ i] - 10, yspots[ i] - 10, 20, 20); } } // end of paint method } // end of class

Jan Double Clicks The Java Event class provides a variable clickCount to track double- or triple- clicks. clickCount is an integer that represents the number of consecutive clicks that have occurred. You can test this value by the following code: public boolean mouseDown( Event e, int x, int y) { switch (e. clickCount) { case 1: // single- click case 2: // double- click case 3: // triple- click... }

Jan Focus Events There are two helper methods for Focus events: -gotFocus, lostFocus, Focus events are generated when a component has received input focus (i. e. when a user has clicked in a text field) This can be useful to implement a user interface that allows the user to use the Tab key to move from one component to the next, or to allow keyboard equivalents to button presses

Jan Scroll Events To catch events that occur in scrollbars, you must use the handleEvent method. You would then trap each of the constants: -SCROLL_ LINE_ UP, SCROLL_ LINE_ DOWN, -SCROLL_ PAGE_ UP, SCROLL_ PAGE_ DOWN, and -SCROLL_ ABSOLUTE To trap: SCROLL_ LINE_ UP SCROLL_ LINE_ down SCROLL_ ABSOLUTE SCROLL_ PAGE_DOWN