ajpunit3eventhandling.docx

Full Transcript

**[The Delegation Event Model]** i\) The modern approach to handling events is based on the ***delegation event model,*** which defines standard and consistent mechanisms to generate and process events. ii\) Its concept is quite simple: **-a *source*** generates an event and sends it to one or m...

**[The Delegation Event Model]** i\) The modern approach to handling events is based on the ***delegation event model,*** which defines standard and consistent mechanisms to generate and process events. ii\) Its concept is quite simple: **-a *source*** generates an event and sends it to one or more ***listeners.*** In this scheme, the listener simply waits until it receives an event. \- Once an event is received, the listener processes the event and then returns. iii\) The advantage of this design is that the application logic that processes events is cleanly separated from the user interface logic that generates those events. A user interface element is able to "delegate" the processing of an event to a separate piece of code. iv\) In the delegation event model, listeners must register with a source in order to receive an event notification. This provides an important benefit: notifications are sent only to listeners that want to receive them. This is a more efficient way to handle events.. **[Events]** In the delegation model, 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. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. Many other user operations could also be cited as examples. Events may also occur that are not directly caused by interactions with a user interface. For example, an event may be generated when a timer expires, a counter exceeds a value, a software or hardware failure occurs, or an operation is completed. **[Event Sources]** A ***source*** is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources 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. Each type of event has its own registration method. Here is the general form: **public void add*Type*Listener(*Type*Listener *el*)** Here, *Type* is the name of the event, and *el* is a reference to the event listener. For example, the method that registers a keyboard event listener is called **addKeyListener( )**. The method that registers a mouse motion listener is called **addMouseMotionListener( )**. When 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. Some sources may allow only one listener to register. The general form of such a method is this: **public void add*Type*Listener(*Type*Listener *el*)throws java.util.TooManyListenersException** Here, *Type* is the name of the event, and *el* is a reference to the event listener. When such an event occurs, the registered listener is notified. This is known as *unicasting* the event. 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 remove*Type*Listener(*Type*Listener *el*)** Here, *Type* is the name of the event, and *el* is a reference to the event listener. For example, to remove a keyboard listener, you would call **removeKeyListener( )**. The methods that add or remove listeners are provided by the source that generates events. For example, the **Component** class provides methods to add and remove keyboard and mouse event listeners. **[Event Listeners]** A ***listener*** is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, 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**. For example, the **MouseMotionListener** interface defines two methods to receive notifications when the mouse is dragged or moved. Any object may receive and process one or both of these events if it provides an implementation of this interface. **[Event Classes]** Java defines several types of events.The most widely used events are those defined by the AWT and those defined by Swing. At the root of the Java event class hierarchy is **EventObject**, which is in **java.util**. It is the superclass for all events. Its one constructor is shown here: \- **EventObject(Object *src*)** Here, *src* is the object that generates this event. **EventObject** contains two methods: **getSource( )** and **toString( )**. The **getSource( )** methodreturns the source of the event. Its general form is shown here: **Object getSource( )** **The toString( )** returns the string equivalent of the event. The class **AWTEvent**, defined within the **java.awt** package, is a subclass of **EventObject**. It is the superclass (either directly or indirectly) of all AWT-based events used by the delegation event model. Its **getID( )** method can be used to determine the type of the event. The signature of this method is shown here: **int getID( )** At this point, it is important to know only that all of the other classes discussed in this section are subclasses of **AWTEvent**. To summarize: **EventObject** is a superclass of all events. **AWTEvent** is a superclass of all AWT events that are handled by the delegation event model. The package **java.awt.event** defines many types of events that are generated by various user interface elements. Table shows several commonly used event classes and provides a brief description of when they are generated. Commonly used constructors and methods in each class are described in the following sections. **[The ActionEvent Class:]** An **ActionEvent** is generated when a button is pressed, a list item is double-clicked, or a menu item is selected. The **ActionEvent** class defines four integer constants that can be used to identify any modifiers associated with an action event: **ALT\_MASK**, **CTRL\_MASK**, **META\_MASK**, and **SHIFT\_MASK**. In addition, there is an integer constant, **ACTION\_** **PERFORMED**, which can be used to identify action events. **ActionEvent** has these three constructors: **-ActionEvent(Object *src*, int *type*, String *cmd*)** **-ActionEvent(Object *src*, int *type*, String *cmd*, int *modifiers*)** **-ActionEvent(Object *src*, int *type*, String *cmd*, long *when*, int *modifiers*)** Here, *src* is a reference to the object that generated this event. The type of the event is specified by *type,* and its command string is *cmd.* The argument *modifiers* indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated. The *when* parameter specifies when the event occurred. You can obtain the command name for the invoking **ActionEvent** object by using the **getActionCommand( )** method, shown here: **-String getActionCommand( )** For example, when a button is pressed, an action event is generated that has a command name equal to the label on that button. The **getModifiers( )** method returns a value that indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated. Its form is shown here: **-int getModifiers( )** The method **getWhen( )** returns the time at which the event took place. This is called the event's *timestamp.* The **getWhen( )** method is shown here: **-long getWhen( )** **[The ItemEvent Class:]** An **ItemEvent** is generated when a check box or a list item is clicked or when a checkable menu item is selected or deselected. (Check boxes and list boxes are described later in this book.) There are two types of item events, which are identified by the following integer constants: ![](media/image2.png) In addition, **ItemEvent** defines one integer constant, **ITEM\_STATE\_CHANGED**, that signifies a change of state. **ItemEvent** has this constructor: ItemEvent(ItemSelectable *src*, int *type*, Object *entry*, int *state*) Here, *src* is a reference to the component that generated this event. For example, this might be a list or choice element. The type of the event is specified by *type.* The specific item that generated the item event is passed in *entry.* The current state of that item is in *state.* The **getItem( )** method can be used to obtain a reference to the item that generated an event. Its signature is shown here: **-Object getItem( )** The **getItemSelectable( )** method can be used to obtain a reference to the **ItemSelectable** object that generated an event. Its general form is shown here: **-ItemSelectable getItemSelectable( )** Lists and choices are examples of user interface elements that implement the **ItemSelectable** interface. The **getStateChange( )** method returns the state change (that is, **SELECTED** or **DESELECTED**) for the event. It is shown here: **int getStateChange( )** **[The KeyEvent Class:]** A **KeyEvent** is generated when keyboard input occurs. There are three types of key events, which are identified by these integer constants: **KEY\_PRESSED**, **KEY\_RELEASED**, and **KEY\_TYPED**. The first two events are generated when any key is pressed or released. The last event occurs only when a character is generated. Remember, not all keypresses result in characters. For example, pressing SHIFT does not generate a character. There are many other integer constants that are defined by **KeyEvent**. For example, **VK\_0** through **VK\_9** and **VK\_A** through **VK\_Z** define the ASCII equivalents of the numbers and letters. Here are some others: The **VK** constants specify *virtual key codes* and are independent of any modifiers, such as control, shift, or alt. **KeyEvent** is a subclass of **InputEvent**. Here is one of its constructors: KeyEvent(Component *src*, int *type*, long *when*, int *modifiers*, int *code*, char *ch*) Here, *src* is a reference to the component that generated the event. The type of the event is specified by *type.* The system time at which the key was pressed is passed in *when.* The *modifiers* argument indicates which modifiers were pressed when this key event occurred. The virtual key code, such as **VK\_UP**, **VK\_A**, and so forth, is passed in *code.* The character equivalent (if one exists) is passed in *ch.* If no valid character exists, then *ch* contains **CHAR\_UNDEFINED**. For **KEY\_TYPED** events, *code* will contain **VK\_UNDEFINED**. The **KeyEvent** class defines several methods, but the most commonly used ones are **getKeyChar( )**, which returns the character that was entered, and **getKeyCode( )**, which returns the key code. Their general forms are shown here: char getKeyChar( ) int getKeyCode( ) If no valid character is available, then **getKeyChar( )** returns **CHAR\_UNDEFINED**. When a **KEY\_TYPED** event occurs, **getKeyCode( )** returns **VK\_UNDEFINED**. **The MouseEvent Class:** There are eight types of mouse events. The **MouseEvent** class defines the following integer constants that can be used to identify them: **MouseEvent** is a subclass of **InputEvent**. Here is one of its constructors: -**MouseEvent(Component *src*, int *type*, long *when*, int *modifiers*,int *x*, int *y*, int *clicks*, boolean *triggersPopup*)** Here, *src* is a reference to the component that generated the event. The type of the event is specified by *type.* The system time at which the mouse event occurred is passed in *when.* The *modifiers* argument indicates which modifiers were pressed when a mouse event occurred. The coordinates of the mouse are passed in *x* and *y.* The click count is passed in *clicks.* The *triggersPopup* flag indicates if this event causes a pop-up menu to appear on this platform. Two commonly used methods in this class are **getX( )** and **getY( )**. These return the X and Y coordinates of the mouse within the component when the event occurred. Their forms are shown here: **int getX( )** **int getY( )** Alternatively, you can use the **getPoint( )** method to obtain the coordinates of the mouse. It is shown here: **-Point getPoint( )** It returns a **Point** object that contains the X,Y coordinates in its integer members: **x** and **y**. The **translatePoint( )** method changes the location of the event. Its form is shown here: void translatePoint(int *x*, int *y*) Here, the arguments *x* and *y* are added to the coordinates of the event. The **getClickCount( )** method obtains the number of mouse clicks for this event. Its signature is shown here: int getClickCount( ) The **isPopupTrigger( )** method tests if this event causes a pop-up menu to appear on this platform. Its form is shown here: boolean isPopupTrigger( ) Also available is the **getButton( )** method, shown here: **int getButton( )** It returns a value that represents the button that caused the event. The return value will be one of these constants defined by **MouseEvent**: ![](media/image4.png) The **NOBUTTON** value indicates that no button was pressed or released. Java SE 6 added three methods to **MouseEvent** that obtain the coordinates of the mouse relative to the screen rather than the component. They are shown here: Point getLocationOnScreen( ) int getXOnScreen( ) int getYOnScreen( ) The **getLocationOnScreen( )** method returns a **Point** object that contains both the X and Y coordinate. The other two methods return the indicated coordinate. **[The TextEvent Class:]** Instances of this class describe text events. These are generated by text fields and text areas when characters are entered by a user or program. **TextEvent** defines the integer constant **TEXT\_VALUE\_CHANGED**. The one constructor for this class is shown here: **TextEvent(Object *src*, int *type*)** Here, *src* is a reference to the object that generated this event. The type of the event is specified by *type.* The **TextEvent** object does not include the characters currently in the text component that generated the event. Instead, your program must use other methods associated with the text component to retrieve that information. This operation differs from other event objects discussed in this section. For this reason, no methods are discussed here for the **TextEvent** class. Think of a text event notification as a signal to a listener that it should retrieve information from a specific text component. **[The WindowEvent Class:]** There are ten types of window events. The**WindowEvent** class defines integer constants that can be used to identify them. The constants and their meanings are shown here: **WindowEvent** is a subclass of **ComponentEvent**. It defines several constructors. The first is **WindowEvent(Window *src*, int *type*)** Here, *src* is a reference to the object that generated this event. The type of the event is *type*. The next three constructors offer more detailed control: **WindowEvent(Window *src*, int *type*, Window *other*)** **WindowEvent(Window *src*, int *type*, int *fromState*, int *toState*)** **WindowEvent(Window *src*, int *type*, Window *other*, int *fromState*, int *toState*)** Here, *other* specifies the opposite window when a focus or activation event occurs. The *fromState* specifies the prior state of the window, and *toState* specifies the new state that the window will have when a window state change occurs. Acommonly used method in this class is **getWindow( )**. It returns the **Window** object that generated the event. Its general form is shown here: **-Window getWindow( )** **WindowEvent** also defines methods that return the opposite window (when a focus or activation event has occurred), the previous window state, and the current window state. These methods are shown here: **Window getOppositeWindow( )** **int getOldState( )** **int getNewState( )** **[Event Listener Interfaces:]** As explained, the delegation event model has two parts: sources and listeners. Listeners are created by implementing one or more of the interfaces defined by the **java.awt.event** package. When an event occurs, the event source invokes the appropriate method defined by the listener and provides an event object as its argument. Table 22-3 lists commonly used listener interfaces and provides a brief description of the methods that they define. The following sections examine the specific methods that are contained in each interface. ![](media/image6.png) **The ActionListener Interface** This interface defines the **actionPerformed( )** method that is invoked when an action event occurs. Its general form is shown here: **void actionPerformed(ActionEvent *ae*)** **The ItemListener Interface** This interface defines the **itemStateChanged( )** method that is invoked when the state of an item changes. Its general form is shown here: **void itemStateChanged(ItemEvent *ie*)** **The KeyListener Interface** This interface defines three methods. The **keyPressed( )** and **keyReleased( )** methods are invoked when a key is pressed and released, respectively. The **keyTyped( )** method is invoked when a character has been entered. For 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 HOME key, two key events are generated in sequence: key pressed and released. The general forms of these methods are shown here: **void keyPressed(KeyEvent *ke*)** **void keyReleased(KeyEvent *ke*)** **void keyTyped(KeyEvent *ke*)** **The MouseListener Interface** This interface defines five methods. If the mouse is pressed and released at the same point, **mouseClicked( )** is invoked. When the mouse enters a component, the **mouseEntered( )** method is called. When it leaves, **mouseExited( )** 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 mouseClicked(MouseEvent *me*)** **-void mouseEntered(MouseEvent *me*)** **-void mouseExited(MouseEvent *me*)** **-void mousePressed(MouseEvent *me*)** **-void mouseReleased(MouseEvent *me*)** **The MouseMotionListener Interface** This interface defines two methods. The **mouseDragged( )** 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 mouseDragged(MouseEvent *me*)** **-void mouseMoved(MouseEvent *me*)** - **The MouseWheelListener Interface** This interface defines the **mouseWheelMoved( )** method that is invoked when the mouse wheel is moved. Its general form is shown here: **-void mouseWheelMoved(MouseWheelEvent *mwe*)** - **The TextListener Interface** This interface defines the **textChanged( )** method that is invoked when a change occurs in a text area or text field. Its general form is shown here: **void textChanged(TextEvent *te*)** - **The WindowFocusListener Interface** This interface defines two methods: **windowGainedFocus( )** and **windowLostFocus( )**. These are called when a window gains or loses input focus. Their general forms are shown here: **void windowGainedFocus(WindowEvent *we*)** **void windowLostFocus(WindowEvent *we)*** - **The WindowListener Interface** This interface defines seven methods. The **windowActivated( )** and **windowDeactivated( )** methods are invoked when a window is activated or deactivated, respectively. If a window is iconified, the **windowIconified( )** method is called. When a window is deiconified, the **windowDeiconified( )** method is called. When a window is opened or closed, the **windowOpened( )** or **windowClosed( )** methods are called, respectively. The **windowClosing( )** method is called when a window is being closed. The general forms of these methods are: **void windowActivated(WindowEvent *we*)** **void windowClosed(WindowEvent *we*)** **void windowClosing(WindowEvent *we*)** **void windowDeactivated(WindowEvent *we*)** **void windowDeiconified(WindowEvent *we*)** **void windowIconified(WindowEvent *we*)** **void windowOpened(WindowEvent *we*)** **[Adapter Classes]** Adapter Classes in Java are nothing new. They are used to provide the implementation of Listener interfaces. The advantage of the adapter class is that it saves code. If we inherit the adapter class using the Adapter interface, we will not be forced to provide the implementation of all the methods of the listener interface. There are namely three packages in which the Java adapter classes are found. The three packages are: - java.awt. event - java.awt. dnd - java.swing. event Also, another advantage of the Adapter Class is that they are useful when we want to process a few of the events that are handled by a particular event listener interface. import java.awt.\*; import java.awt.event.\*; public class MouseAdapterExample extends MouseAdapter { Frame f; MouseAdapterExample() { f=new Frame(\"Mouse Adapter\"); f.addMouseListener(this); f.setSize(300,300); f.setLayout(null); f.setVisible(true); } public void mouseClicked(MouseEvent e) { Graphics g=f.getGraphics(); g.setColor(Color.BLUE); g.fillOval(e.getX(),e.getY(),30,30); } public static void main(String\[\] args) { new MouseAdapterExample(); } } **[Inner Classes:]**

Use Quizgecko on...
Browser
Browser