Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en...
-
Upload
lynne-willis -
Category
Documents
-
view
214 -
download
0
Transcript of Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en...
Universidad Nacional de Universidad Nacional de ColombiaColombia
Facultad de IngenieríaFacultad de Ingeniería
Departamento de SistemasDepartamento de Sistemas
ertificación enertificación en
AVAAVA
10. 10. EVENTSEVENTS
ObjectivesObjectives
Interface EventInterface Event
Event Delegation ModelEvent Delegation Model
The Event Class HierarchyThe Event Class Hierarchy
Event ListenersEvent Listeners
Explicit Event EnabliExplicit Event Enablingng
AdaptersAdapters
ObjectivesObjectives
• Write code to implement listener classes and methods, and in listener methods, extract informationfrom the event to determine the affected component,mouse position, nature, and time of the event. Statethe event classname for any specified event listenerinterface in the java.awt.event package.
Interface Event
When the user clicks a button, types text, uses the mouse, or performs any other interface-related action in your applet, an interface event occurs.
When an event occurs, the applet is notified and takes the appropriate action.
Interface Event
In GUI, the program responds to user events when they happen because the user directs the program flow by manipulating the controls in the applet.
Java declares ActionListener as an interface to let you use the ActionListener methods.
You can extend the Applet class to create your applet, and implement the ActionListener interface to use the Action-Listener methods as well.
Interface Event
Most of the event classes reside in the java.awt.event package.
The class that implements the ActionListener interface does not have to be the applet's main class. In fact, you can create an entirely new class, which helps break up the code.
Event Delegation ModelDelegation Model
Delegation-Based Event Model
Listener ---------------- Component
event delegation model
a component may be told which object or objects should be notified when the component generates a particular kind of event
If a component is not interested in an event type, then events of that type will not be propagated
The delegation model is based on four concepts:
• Event classes• Event listeners• Explicit event enabling• Adapters
Event Delegation ModelDelegation Model
The delegation-based event model passes events from source controls to Listener objects.
That means you will connect a Listener to your component.
When an event occurs, the Listener object will hear it.
Event Delegation ModelDelegation Model
In this case, you will make the Listener object the applet object itself by connecting your applet to your component as a listener, using the button's addActionListener() method.
To indicate that you want the applet itself to be the component's listener, you would need to be able to pass the applet as an argument to addActionListener().
public class clicker extends Applet implements ActionListener
Event Delegation ModelDelegation Model
That is accomplished with the this keyword, which refers to the current object. Then, when there are component events, they will be sent to your applet.
The Event Class Hierarchy
Most of the event classes reside in the java.awt.event package
java.awt.AWTEvent
java.util.eventobject
The Event Class Hierarchy
ActionEvent
AdjustmentEvent ComponentEvent
TextEvent
ItemEvent
ContainerEvent
FocusEvent InputEvent
WindowEvent
PaintEvent
KeyEvent MouseEvent
java.util.EventObject: topmost superclass of all the new event classes is. It is a very general class, with only one method of interest:
• Object getSource(): returns the object that
originated the event One subclass of EventObject is
java.awt.AWTEvent, which is the superclass of all the delegation model event classes.
Again, there is only one method of interest: • int getlD(): returns the ID of the event
An event's ID is an int that specifies the exact nature of the event. For example, an instance of the MouseEvent class can represent one of seven occurrences: a click, a drag, an entrance, an exit, a move, a press, or a release
Each of these possibilities is represented by an int:
MouseEvent.MOUSE_CLICKED, MouseEvent.MOUSE_DRAGGED, and so on.
Subclasses of java.awt.AWTEvent
event types that can be generated by the various AWT components
• ActionEvent: generated by activation of components • AdjustmentEvent: generated by adjustment of adjustable
component such as scroll bars • ContainerEvent: generated when components are added to or
removed from a container
• FocusEvent: generated when a component receives or
loses input focus
• ItemEvent: generated when an item is selected from a
list, choice, or check box • KeyEvent: generated by keyboard activity • MouseEvent: generated by mouse activity
• PaintEvent:generated when a component is painted • TextEvent: generated when a text component is modified • WindowEvent: generated by window activity (such as
iconifying or de-iconifying)
The InputEvent superclass has a getWhen() method that returns the time when the event took place; the return type is long
The MouseEvent class has getX() and getY() methods that return the position of the mouse within the originating component at the time the event took place; the return types are both int
Event Listeners An event listener is an object to which a
component has delegated the task of handling a particular kind of event
• When the component experiences input, an event of the appropriate type is constructed;
• the event is then passed as the parameter to a method call on the listener
• A listener must implement the interface that contains the event-handling method
Example: a button in an applet
When the button is clicked, an action event is to be sent to an instance of class MyActionListener
1. class MyActionListener implements ActionListener {2. public void actionPerformed( ActionEvent ae ) {3. System.out.println( "Action performed." );4. }5. }
1. public class ListenerTest extends Applet {4. public void init() {5. Button btn = new Button( "OK" );6. MyActionListener listener = new7. MyActionListener();5. btn.addActionListener( listener );6. add( btn );7. } 8. }
import java.applet.Applet;import java.awt.*;import java.awt.event.*;public class click extends Applet implements
ActionListener{ TextField texto; Button boton; public void init() { texto = new TextField(20); add(texto); texto.setText("Bienvenido a Java"); boton = new Button("Haga Click!"); add(boton); boton.addActionListener(this); }
public void actionPerformed(ActionEvent event)
{ String msg = new String("Welcome to
Java"); if(event.getSource() == boton) { texto.setText(msg); } } }
A standard formula for giving an action listener to a component
1. Create a listener class that implements the
ActionListener interface
2. Construct the component
3. Construct an instance of the listener class
4. Call addActionListener() on the component, passing in the listener object
A component may have multiple listeners for A component may have multiple listeners for any event typeany event type
There is no guarantee that listeners will be There is no guarantee that listeners will be notified in the order in which they were notified in the order in which they were addedadded
There is also no guarantee that all listener There is also no guarantee that all listener notification will occur in the same thread; notification will occur in the same thread; thus listeners must take precautions thus listeners must take precautions against corrupting shared dataagainst corrupting shared data
Listener InterfacesListener Interfaces
Interface Interface methods Add Method
ActionListener actionPerformed( ActionEvent ) addActionListener()
AdjustmentListener adjustmentValueChanged( AdjustmentEvent )
addAdjustmentListener()
ComponentListener componentHidden( ComponentEvent )componentMoved( ComponentEvent )componentResized( ComponentEvent )componentShown( ComponentEvent )
addComponentlistener()
ContainerListener componentAdded( ContainerEvent )componentRemoved( ContainerEvent )
addContainerListener()
FocusListener focusGained( FocusEvent )focusLost( FocusEvent )
addFocusListener()
Listener Interfaces ...Listener Interfaces ...
Interface Interface methods Add Method
ItemListener itemStateChanged( ItemEvent ) addItemListener()
KeyListener keyPressed( KeyEvent )keyReleased( KeyEvent )keyTyped( KeyEvent )
addKeyListener()
MouseListener mousedClicked( MouseEvent ) mouseEntered( MouseEvent ) mouseExited( MouseEvent ) mousePressed( MouseEvent ) mouseReleased( MouseEvent )
addMouseListener()
MouseMotionListener mouseDragged( MouseEvent )mouseMoved( MouseEvent )
addMouseMotionListener()
Listener Interfaces ...Listener Interfaces ...
Interface Interface methods Add Method
TextListener textValueChanged( TextEvent ) addTextListener()
WindowListener windowActivated( WindowEvent ) windowClosed( WindowEvent ) windowClosing( WindowEvent ) windowDeactivated( WindowEvent ) windowDeiconified( WindowEvent ) windowlconified( WindowEvent ) windowOpened( WindowEvent )
addWindowListener()
An event listener may be removed from a component's list of listeners by calling a
removeXXXListener() method, passing in the listener to be removed
btn.removeActionListener( al );
Explicit Event Enabling
There is an alternative to delegating a component's events
It is possible to subclass the component and override the method that receives events and dispatches them to listeners
Example:components that originate action events have
a method called processActionEvent( ActionEvent ), which dispatches its action event to each action listener
1. class MyBtn extends Button {2. public MyBtn( String label ) {3. super( label );4. enableEvents( AWTEvent.ACTION_EVENT_MASK );5. }6.7. public void processActionEvent( ActionEvent ae ) {8. System.out.println( "Processing an action event."
);9. super.processActionEvent( ae );10. }11. }
1. class MyBtn extends Button implements ActionListener {2. public MyBtn( String label ) {3. super( label );4. addActionListener( this );5. }6. 7. public void actionPerformed( ActionEvent ae
) {8. // Handle the event here9. }10.}
you can always make a component subclass handle its own events by making the subclass an event listener of itself
The only difference between this strategy and the enableEvents() strategy is the order in which event handlers are invoked
When you explicitly call enableEvents(), the component's processActionEvent() method will be called before any action listeners are notified
When the component subclass is its own event listener, there is no guarantee as to order of notification
Event MasksEvent Masks
Each of the 11 listener types has a corresponding
XXX_EVENT_MASK
constant defined in the AWTEvent class, and corresponding
processXXXEvent()
methods
Event MasksEvent Masks
Mask Method
AWTEvent.ACTION EVENT MASK processActionEvent()
AWTEvent.ADJUSTMENT EVENT MASK processAdjustmentEvent()
AWTEvent.COMPONENT EVENT MASK processComponentEvent()
AWTEvent.CONTAINER EVENT MASK processContainerEvent()
AWTEvent.FOCUS EVENT MASK process FocusEvent()
AWTEvent.ITEM EVENT MASK processItemEvent()
AWTEvent.KEY_EVENT_MASK processKeyEvent()
AWTEvent.MOUSE_EVENT_MASK processMouseEvent()
AWTEvent.MOUSE_MOTION_EVENT_MASK processMouseMotionEvent()
AWTEvent.TEXT_EVENT_MASK AWT processTextEvent()
Event.WINDOW EVENT MASK processWindowEvent()
The strategy of explicitly enabling events for a component:
1. Create a subclass of the component 2. In the subclass constructor, call
enableEvents( AWTEvent.XXXEVENT_MASK ) 3. Provide the subclass with a
processXXXEvent() method; this method should call the superclass' version before returning
Example:Catching iconified events on a frame
AdaptersAdapters
1. class MyIkeListener implements WindowListener {2. public void windowIconified( WindowEvent we ) {3. // process the event4. }5. }
1. class MylkeListener extends WindowAdapter {2. public void windowIconified( WindowEvent we ) {3. // process the event4. }5. }
The java.awt.event provides seven adapter classes, one for each listener interface that defines more than just a single method
An adapter is simply a class that implements an interface by providing do-nothing methods
Adapter ClassAdapter Class Listener InterfaceListener Interface______________________________________________________________________________________________________________________
ComponentAdapter ComponentAdapter ComponentListenerComponentListenerContainerAdapter ContainerAdapter ContainerListenerContainerListenerFocusAdapterFocusAdapter FocusListenerFocusListenerKeyAdapter KeyAdapter KeyListenerKeyListenerMouseAdapter MouseAdapter MouseListenerMouseListenerMouseMotionAdapter MouseMotionAdapter MouseMotionListenerMouseMotionListenerWindowAdapterWindowAdapter WindowlistenerWindowlistener
AdaptersAdapters