Jan. 2004 1
Event Handling - 1.02
Yangjun Chen
Dept. Business ComputingUniversity of Winnipeg
Jan. 2004 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
Jan. 2004 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 Eventclass.
• 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. 2004 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
Jan. 2004 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).
• 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 ofpublic 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. 2004 6
Event Hierarchy• When an event is generated, Java creates a new
Event objectand 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, theparent component.
Jan. 2004 7
Event Hierarchy- Eventually, the event will be handled by one of the
objects in theGUI, or it would never be handled and simply expire
with noresponse.
• 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 wheneverpossible, but this isn’t possible all the time or
wanted even.- Suppose the parent has access to information that the
child doesnot, then it makes sense that the parent will handle the
event.
Jan. 2004 8
Event Hierarchy
panel1
panel2
applet
checkbox
appletFrame
panel1 panel2
checkbox1 checkbox2 checkbox3
Jan. 2004 9
Event HierarchyEvent queue
… ...
nextBttn previousBttn
<< >>
Applet
nextBttnpreviousBttn
panel
Applet
previousBttn nextBttn panel
Jan. 2004 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 areprocessed.
• 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).
Jan. 2004 11
handleEvent()• Notice that handleEvent is made public so that
the system canaccess 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. 2004 12
handleEvent()• The return from a handleEvent method
determines whathappens to the event when the method exits
(when you arefinished with it)- If handleEvent(e) returns true , then event e will die in
thismethod 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 classimmediately above the object in the class
hierarchy.- Is this different from the GUI hierarchy?
• If handleEvent fails to return true, Java will try again bylooking at the target’s helper methods like
mouseDown oraction.
Jan. 2004 13
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);
elsereturn false;
return true;} // end of action method
} // end of class
handleEvent
Jan. 2004 14
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. 2004 15
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, ChoiceList, MenuItem, TextField
e.id == Event.ACTION_EVENTe.id == Event.KEY_PRESS…...
Jan. 2004 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}
Jan. 2004 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.
Jan. 2004 18
Helper Methods• All of these helper methods return a boolean
value just like thehandleEvent 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 theobject’s name with the dot operator.
• The arg field is the most complex of them all because itdepends on the type of event. For the
ACTION_EVENTs inbuttons, choices, lists, or menu items, the arg
field is a stringrepresenting the label or name of the selected
item.
Jan. 2004 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 fieldis the index of the list element that was selected.
• Another important field is the target field. This field can beused to categorize the event by using the boolean
operatorinstanceof .- instanceof takes an operand on either side, the left
side is avariable 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. 2004 20
Helper Methodspublic 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 listsString c = (String) arg; // get the list item’s nameif (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. 2004 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 chosenelse 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. 2004 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 thatgenerated the event.
Jan. 2004 23
Keyboard Events
• To capture a keyboard event in the 1.02 model, use thekeyDown() method:- public boolean keyDown( Event e, int key) { … }
• The key pressed is passed to the keyDown() method as the keyargument, which is of type int. It is a Unicode
representationof 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. 2004 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;
}
Jan. 2004 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 fourmodifiers, in the order, SHIFT_MASK, ALT_MASK,META_MASK, CTRL_MASK.
Jan. 2004 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.
Jan. 2004 27
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
0011001111101111&
00100011
0011001010101011|
10111011
Jan. 2004 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 ormore modifiers
• Using the masks that were defined previously, we would haveEvent.SHIFT_MASK|Event.CTRL_MASKequal 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
Jan. 2004 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 amodifier key is present: controlDown(),
metaDown(),shiftDown(). There is no method to test for the
Alt key,masks must be used for that.
Jan. 2004 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 theright 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 onthe applet, the coordinates will be output.
Jan. 2004 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
Jan. 2004 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
Jan. 2004 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
Jan. 2004 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- clickcase 2: // double- clickcase 3: // triple- click
...}
}
Jan. 2004 35
Focus Events• There are two helper methods for Focus events:
- gotFocus, lostFocus, • Focus events are generated when a component
has receivedinput focus (i. e. when a user has clicked in a text
field)• This can be useful to implement a user interface
that allows theuser to use the Tab key to move from one
component to the next, or to allow keyboard equivalents to button presses
Jan. 2004 36
Scroll Events• To catch events that occur in scrollbars, you must
use thehandleEvent 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_ UPSCROLL_ LINE_ down SCROLL_ ABSOLUTE
SCROLL_ PAGE_DOWN SCROLL_ PAGE_DOWN