Anda di halaman 1dari 6

Events

An event is an object that describes a state change in a source. It can be generated as a consequence of a
person interacting with the elements in a graphical user interface. As example pressing a button, entering a
character via the keyboard, selecting an item in a list, and clicking the mouse.
Event Sources
A source is an object that generates an event. This occurs when the internal state of that object changes in
some way. ources may generate more than one type of event. A source must register listeners in order for
the listeners to receive notifications about a specific type of event. !ach type of event has its own
registration method.
"ere is the general form#
public void addType$istener%Type$istener el&
Type is the name of the event and el is a reference to the event listener.
'or example, registers a keyboard event listener is called addKeyListener( ). (egisters a mouse motion
listener is called addMouseMotionListener( ).
)hen an event occurs, all registered listeners are notified and receive a copy of the event object. This is
known as multicasting the event. In all cases, notifications are sent only to listeners that register to receive
them.
A source must also provide a method that allows a listener to unregister an interest in a specific type of
event. The general form of such a method is this#
public void removeType$istener%Type$istener el&
'or example,
removeKeyListener( ).
Event Listeners
A listener is an object that is notified when an event occurs. It has two major requirements.
'irst, it must have been registered with one or more sources to receive notifications about specific types of
events. econd, it must implement methods to receive and process these notifications. The methods that
receive and process events are defined in a set of interfaces found in java.awt.event. 'or example, the
MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged
or moved.
Sources of Events
!vent ource *escription
+utton ,enerates action events when the button is pressed.
-heckbox ,enerates item events when the check box is selected or
deselected.
-hoice ,enerates item events when the choice is changed.
$ist ,enerates action events when an item is double.clicked/
generates
item events when an item is selected or deselected.
0enu Item ,enerates action events when a menu item is selected/
generates item
events when a checkable menu item is selected or deselected.
crollbar ,enerates adjustment events when the scroll bar is
manipulated.
Text components ,enerates text events when the user enters a character.
)indow ,enerates window events when a window is activated, closed,
deactivated, deiconified, iconified, opened, or quit.
!vent $istener Interfaces
the delegation event model has two parts# sources and listeners. $isteners are created by implementing one
or more of the interfaces defined by the java.awt.event package. )hen an event occurs, the event source
invokes the appropriate method defined by the listener and provides an event object as its argument.
Action$istener Interface
This interface defines the actionPerformed( ) method that is invoked when an action event occurs. Its
general form is shown here#
void action1erformed%Action!vent ae&
-omponent$istener Interface
This interface defines four methods that are invoked when a component is resi2ed,
moved, shown, or hidden. Their general forms are shown here#
void component(esi2ed%-omponent!vent ce&
void component0oved%-omponent!vent ce&
void componenthown%-omponent!vent ce&
void component"idden%-omponent!vent ce&
'ocus$istener Interface
This interface defines two methods. )hen a component obtains keyboard focus,
focusGained( ) is invoked. )hen a component loses keyboard focus, focusLost( )
is called. Their general forms are shown here#
void focus,ained%'ocus!vent fe&
void focus$ost%'ocus!vent fe&
3ey$istener Interface
This interface defines three methods. The keyPressed( ) and keyReleased( ) methods
are invoked when a key is pressed and released, respectively. The keyy!ed( ) method
is invoked when a character has been entered.
'or example, if a user presses and releases the A key, three events are generated in
sequence# key pressed, typed, and released. If a user presses and releases the "40!
key, two key events are generated in sequence# key pressed and released.
The general forms of these methods are shown here#
void key1ressed%3ey!vent ke&
void key(eleased%3ey!vent ke&
void keyTyped%3ey!vent ke&
0ouse$istener Interface
This interface defines five methods. If the mouse is pressed and released at the
same point, mouse"licked( ) is invoked. )hen the mouse enters a component, the
mouseEntered( ) method is called. )hen it leaves, mouseE#ited( ) is called. The
mousePressed( ) and mouseReleased( ) methods are invoked when the mouse is
pressed and released, respectively.
The general forms of these methods are shown here#
void mouse-licked%0ouse!vent me&
void mouse!ntered%0ouse!vent me&
void mouse!xited%0ouse!vent me&
void mouse1ressed%0ouse!vent me&
void mouse(eleased%0ouse!vent me&
0ouse0otion$istener Interface
This interface defines two methods. The mouse$ra%%ed( ) method is called multiple
times as the mouse is dragged. The mouseMoved( ) method is called multiple times as
the mouse is moved. Their general forms are shown here#
void mouse*ragged%0ouse!vent me&
void mouse0oved%0ouse!vent me&
"andling 0ouse !vents
To handle mouse events, you must implement the MouseListener and the MouseMotionListener
interfaces. %5ou may also want to implement Mouse&'eelListener, but we won6t be doing so, here.& The
following applet demonstrates the process. It displays the current coordinates of the mouse in the applet6s
status window. !ach time a button is pressed, the word 7*own8 is displayed at the location of the mouse
pointer. !ach time the button is released, the word 79p8 is shown. If a button is clicked, the message
70ouse clicked8 is displayed in the upper.left corner of the applet display area. As the mouse enters or
exits the applet window, a message is displayed in the upper.left corner of the applet display area. )hen
dragging the mouse, a : is shown, which tracks with the mouse pointer as it is dragged. ;otice that the two
variables,
mouse( and mouse), store the location of the mouse when a mouse pressed, released,
or dragged event occurs. These coordinates are then used by !aint( ) to display output
at the point of these occurrences.
import java.awt.:/
import java.awt.event.:/
import java.applet.:/
<:
=applet code>?0ouse!vents? width>@AA height>BAAC
=<appletC
:<
public class 0ouse!vents extends Applet implements 0ouse$istener, 0ouse0otion$istener D
tring msg > ??/
int mouseE > A, mouse5 > A/ << coordinates of mouse
public void init%& D
add0ouse$istener%this&/
add0ouse0otion$istener%this&/
F
<< "andle mouse clicked.
public void mouse-licked%0ouse!vent me& D
<< save coordinates
mouseE > A/
mouse5 > BA/
msg > ?0ouse clicked.?/
repaint%&/
F
<< "andle mouse entered.
public void mouse!ntered%0ouse!vent me& D
<< save coordinates
mouseE > A/
mouse5 > BA/
msg > ?0ouse entered.?/
repaint%&/
F
<< "andle mouse exited.
public void mouse!xited%0ouse!vent me& D
<< save coordinates
mouseE > A/
mouse5 > BA/
msg > ?0ouse exited.?/
repaint%&/
F
<< "andle button pressed.
public void mouse1ressed%0ouse!vent me& D
<< save coordinates
mouseE > me.getE%&/
mouse5 > me.get5%&/
msg > ?*own?/
repaint%&/
F
<< "andle button released.
public void mouse(eleased%0ouse!vent me& D
<< save coordinates
mouseE > me.getE%&/
mouse5 > me.get5%&/
msg > ?9p?/
repaint%&/
F
<< "andle mouse dragged.
public void mouse*ragged%0ouse!vent me& D
<< save coordinates
mouseE > me.getE%&/
mouse5 > me.get5%&/
msg > ?:?/
showtatus%?*ragging mouse at ? G mouseE G ?, ? G mouse5&/
repaint%&/
F
<< "andle mouse moved.
public void mouse0oved%0ouse!vent me& D
<< show status
showtatus%?0oving mouse at ? G me.getE%& G ?, ? G me.get5%&&/
F
<< *isplay msg in applet window at current E,5 location.
public void paint%,raphics g& D
g.drawtring%msg, mouseE, mouse5&/
F
F
$et6s look closely at this example. The MouseEvents class extends *!!let and implements both the
MouseListener and MouseMotionListener interfaces. These two interfaces contain methods that receive
and process the various types of mouse events. ;otice that the applet is both the source and the listener for
these events. This works because "om!onent, which supplies the addMouseListener( ) and
addMouseMotionListener( ) methods, is a superclass of *!!let. +eing both the source and the listener for
events is a common situation for applets. Inside init( ), the applet registers itself as a listener for mouse
events. This is done by using addMouseListener( ) and addMouseMotionListener( ), which, as
mentioned,
are members of "om!onent. They are shown here#
void add0ouse$istener%0ouse$istener ml&
void add0ouse0otion$istener%0ouse0otion$istener mml&
"ere, ml is a reference to the object receiving mouse events, and mml is a reference to the
object receiving mouse motion events. In this program, the same object is used for both.
The applet then implements all of the methods defined by the MouseListener and
MouseMotionListener interfaces. These are the event handlers for the various mouse
events. !ach method handles its event and then returns.
"andling 3eyboard !vents
To handle keyboard events, you use the same general architecture as that shown in the mouse event
example in the preceding section. The difference, of course, is that you
will be implementing the KeyListener interface. +efore looking at an example, it is useful to review how
key events are generated. )hen a key is pressed, a KE)+PRESSE$ event is generated. This results in a
call to
the keyPressed( ) event handler. )hen the key is released, a KE)+RELE*SE$ event
is generated and the keyReleased( ) handler is executed. If a character is generated by
the keystroke, then a KE)+)PE$ event is sent and the keyy!ed( ) handler is invoked.
Thus, each time the user presses a key, at least two and often three events are generated.
If all you care about are actual characters, then you can ignore the information passed by
the key press and release events. "owever, if your program needs to handle special keys,
such as the arrow or function keys, then it must watch for them through the keyPressed( )
handler.
<< *emonstrate the key event handlers.
import java.awt.:/
import java.awt.event.:/
import java.applet.:/
<:
=applet code>?imple3ey? width>@AA height>BAAC
=<appletC
:<
public class imple3ey extends Applet implements 3ey$istener D
tring msg > ??/
int E > BA, 5 > HA/ << output coordinates
public void init%& D
add3ey$istener%this&/
request'ocus%&/ << request input focus
F
public void key1ressed%3ey!vent ke& D
showtatus%?3ey *own?&/
F
public void key(eleased%3ey!vent ke& D
showtatus%?3ey 9p?&/
F
public void keyTyped%3ey!vent ke& D
msg G> ke.get3ey-har%&/
repaint%&/
F
<< *isplay keystrokes.
public void paint%,raphics g& D
g.drawtring%msg, E, 5&/
F
F
*da!ter classes
0any listener interfaces have more than one callback method. An example is java.awt.'ocus$istener that
has two methods/ focus,ained%java.awt.'ocus!vent event& and focus$ost%java.awt.'ocus!vent event&.
)hen creating a listener class that implements the interface the Iava compiler insists that all of the interface
methods are implemented, which often results in many empty methods being created to satisfy its
requirements when only one or some of its methods actually contain code. The following statement shows a
'ocus$istener being used to perform some logic when a Iava bean gains focus. "owever, an empty
focus$ost method must be provided.
java+ean.add'ocus$istener%new java.awt.event.'ocus$istener%& D
public void focus,ained%java.awt.event.'ocus!vent e& D
do'ocus,ained-ode%&/
F
public void focus$ost%java.awt.event.'ocus!vent e& D
F
F&/
To avoid having many empty listener methods for many listeners, Adapter classes are provided. These
implement the listener interface, and provide empty no.op implementation of its methods. The advantage is
that the listener can extend these, and only speciali2e methods of choice without having to provide default
implementations for the rest %these are inherited from the Adapter&.
java+ean.add'ocus$istener%new java.awt.event.'ocusAdapter%& D
public void focus,ained%java.awt.event.'ocus!vent e& D
do'ocus,ained-ode%&/
F
F&/
*da!ter classes
Anonymous Inner Classes
Anonymous inner class# An inner class with no name.
!xample# action1erformed events utili2e the 4bserver.4bservable pattern .. An instance of the
observer is added to the observable. I+uilder creates an anonymous inner class to give to the
button as its Action$istener.
Anonymous inner classes are very similar to named inner classes#
o Anonymous inner classes can override methods of the superclass.
o Anonymous inner classes are scoped inside the private scoping of the outer class. They
can access the internal %private& properties and methods of the outer class.
o (eferences to an inner class can be passed to other objects. ;ote that it still retains its
scoping.
+ut there are some important differences#
o Anonymous inner classes must use the no parameter constructor of the superclass.
o ince an object made from the inner class has a ?life? independent of its outer class
object, there is a problem with accessing local variables, especially method input
paramenters.
o Two ways to pass initiali2ing parameters to an inner class#
Initiali2e a property that the inner class then uses .. properties have the cross.
method.call persistence that local variables lack.
0ake the local variable ?final? .. compiler will automatically transfer the value
to a more persistent portion of the computer memory. *isadvantage# the value
cannot be changed.
9sages#
o Jery useful for controlled access to the innards of another class.
o Jery useful when you only want one instance of a special class.
import java.applet.:/
import java.awt.:/
import java.awt.event.:/
<:
=applet code>?0ouseAnonymous*emo? width>BAA height>BAAC
=<appletC
:<
public class 0ouseAnonymous*emo extends Applet D
public void init%& D
set+ackground%-olor.green&/
addMouseListener(new Mouse*da!ter() ,

!u-lic void mousePressed(MouseEvent me) ,
set.ack%round("olor.red)/
re!aint()/
0
!u-lic void mouseReleased(MouseEvent me) ,
set.ack%round("olor.%reen)/
re!aint()/
0
0)/
F
F

Anda mungkin juga menyukai