slide1 n.
Skip this Video
Loading SlideShow in 5 Seconds..
Event Handling - 1.02 Yangjun Chen Dept. Business Computing University of Winnipeg PowerPoint Presentation
Download Presentation
Event Handling - 1.02 Yangjun Chen Dept. Business Computing University of Winnipeg

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

140 Vues Download Presentation
Télécharger la présentation

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

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

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

  2. 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

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

  4. 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

  5. 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). • F1through F12, LEFT, RIGHT, UP, DOWN, HOME, • END, PGUP, PGDNrefer 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 argfield will contain no useful information for mouse events.

  6. Event Hierarchy • When an event is generated, Java creates a new Eventobject • 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.

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

  8. Event Hierarchy appletFrame panel1 panel1 panel2 checkbox panel2 checkbox2 checkbox3 checkbox1 applet

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

  10. 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 must be overridden (writing your own method).

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

  12. 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.

  13. handleEvent 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

  14. handleEvent 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) { … … } }

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

  16. 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 • }

  17. 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.

  18. 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.

  19. 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.

  20. 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

  21. 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

  22. 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.

  23. 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) { … }

  24. 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; }

  25. 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.

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

  27. 00110011 11101111 00110010 10101011 & | 00100011 10111011 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

  28. 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 1001. • 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

  29. 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.

  30. 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.

  31. 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

  32. 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

  33. 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

  34. 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 • ... • } • }

  35. 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

  36. 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_ PAGE_DOWN SCROLL_ PAGE_DOWN SCROLL_ LINE_ down SCROLL_ ABSOLUTE SCROLL_ LINE_ UP