Presentation is loading. Please wait.

Presentation is loading. Please wait.

Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.

Similar presentations


Presentation on theme: "Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA."— Presentation transcript:

1 Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA

2 10. EVENTS  Objectives  Interface Event  Event Delegation Model  The Event Class Hierarchy  Event Listeners  Explicit Event Enabling  Adapters

3 Objectives Write code to implement listener classes and methods, and in listener methods, extract information from the event to determine the affected component, mouse position, nature, and time of the event. State the event classname for any specified event listener interface in the java.awt.event package.

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

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

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

7 Delegation Model Event Delegation Model Delegation-Based Event Model Listener ---------------- Component

8 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

9 The delegation model is based on four concepts: Event classes Event listeners Explicit event enabling Adapters

10 Delegation Model Event Delegation 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.

11 Delegation Model Event Delegation 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

12 Delegation Model Event Delegation 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.

13 The Event Class Hierarchy Most of the event classes reside in the java.awt.event package

14 java.awt.AWTEvent java.util.eventobject The Event Class Hierarchy ActionEvent AdjustmentEventComponentEvent TextEvent ItemEvent ContainerEvent FocusEventInputEvent WindowEvent PaintEvent KeyEventMouseEvent

15 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

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

17 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

18 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

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

20 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

21 Event Listeners An event listener is an object to which a component has delegated the task of handling a particular kind of event

22 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

23 1. class MyActionListener implements ActionListener { 2. public void actionPerformed( ActionEvent ae ) { 3. System.out.println( "Action performed." ); 4. } 5. }

24 1. public class ListenerTest extends Applet { 2. 2. public void init() { 3. 3. Button btn = new Button( "OK" ); 3. 3. MyActionListener listener = new 4. 4. MyActionListener(); 5. btn.addActionListener( listener ); 6. add( btn ); 7. } 8. }

25 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); }

26 public void actionPerformed(ActionEvent event) { String msg = new String("Welcome to Java"); if(event.getSource() == boton) { texto.setText(msg); }

27 A standard formula for giving an action listener to a component 1. 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

28 A component may have multiple listeners for any event type There is no guarantee that listeners will be notified in the order in which they were added There is also no guarantee that all listener notification will occur in the same thread; thus listeners must take precautions against corrupting shared data

29 Listener Interfaces InterfaceInterface methodsAdd Method ActionListeneractionPerformed( ActionEvent )addActionListener() AdjustmentListeneradjustmentValueChanged( AdjustmentEvent ) addAdjustmentListener() ComponentListenercomponentHidden( ComponentEvent ) componentMoved( ComponentEvent ) componentResized( ComponentEvent ) componentShown( ComponentEvent ) addComponentlistener() ContainerListenercomponentAdded( ContainerEvent ) componentRemoved( ContainerEvent ) addContainerListener() FocusListenerfocusGained( FocusEvent ) focusLost( FocusEvent ) addFocusListener()

30 Listener Interfaces... InterfaceInterface methodsAdd Method ItemListeneritemStateChanged( ItemEvent )addItemListener() KeyListenerkeyPressed( KeyEvent ) keyReleased( KeyEvent ) keyTyped( KeyEvent ) addKeyListener() MouseListenermousedClicked( MouseEvent ) mouseEntered( MouseEvent ) mouseExited( MouseEvent ) mousePressed( MouseEvent ) mouseReleased( MouseEvent ) addMouseListener() MouseMotionListenermouseDragged( MouseEvent ) mouseMoved( MouseEvent ) addMouseMotionListener()

31 Listener Interfaces... InterfaceInterface methodsAdd Method TextListenertextValueChanged( TextEvent )addTextListener() WindowListenerwindowActivated( WindowEvent ) windowClosed( WindowEvent ) windowClosing( WindowEvent ) windowDeactivated( WindowEvent ) windowDeiconified( WindowEvent ) windowlconified( WindowEvent ) windowOpened( WindowEvent ) addWindowListener()

32 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 );

33 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

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

35 1. 1.class MyBtn extends Button implements ActionListener { 2. public MyBtn( String label ) { 3. super( label ); 4. 4. addActionListener( this ); 5. 5. } 6. 6. 7. 7. public void actionPerformed( ActionEvent ae ) { 8. 8. // Handle the event here 9. 9. } 10. 10.} you can always make a component subclass handle its own events by making the subclass an event listener of itself

36 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

37 Event Masks Each of the 11 listener types has a corresponding XXX_EVENT_MASK constant defined in the AWTEvent class, and corresponding processXXXEvent() methods

38 Event Masks MaskMethod AWTEvent.ACTION EVENT MASKprocessActionEvent() AWTEvent.ADJUSTMENT EVENT MASKprocessAdjustmentEvent() AWTEvent.COMPONENT EVENT MASKprocessComponentEvent() AWTEvent.CONTAINER EVENT MASKprocessContainerEvent() AWTEvent.FOCUS EVENT MASKprocess FocusEvent() AWTEvent.ITEM EVENT MASKprocessItemEvent() AWTEvent.KEY_EVENT_MASKprocessKeyEvent() AWTEvent.MOUSE_EVENT_MASKprocessMouseEvent() AWTEvent.MOUSE_MOTION_EVENT_MASKprocessMouseMotionEvent() AWTEvent.TEXT_EVENT_MASK AWTprocessTextEvent() Event.WINDOW EVENT MASKprocessWindowEvent()

39 The strategy of explicitly enabling events for a component: 1. 1. Create a subclass of the component 2. 2.In the subclass constructor, call enableEvents( AWTEvent.XXXEVENT_MASK ) 3. 3.Provide the subclass with a processXXXEvent() method; this method should call the superclass' version before returning

40 Example: Catching iconified events on a frame Adapters 1. 1.class MyIkeListener implements WindowListener { 2. public void windowIconified( WindowEvent we ) { 3. // process the event 4. } 5. }

41 1. class MylkeListener extends WindowAdapter { 2. public void windowIconified( WindowEvent we ) { 3. // process the event 4. } 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

42 Adapter Class Listener Interface Adapter Class Listener Interface___________________________________________________________ ComponentAdapter ComponentListener ContainerAdapter ContainerListener FocusAdapterFocusListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener WindowAdapterWindowlistener Adapters


Download ppt "Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA."

Similar presentations


Ads by Google