Presentation is loading. Please wait.

Presentation is loading. Please wait.

What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.

Similar presentations


Presentation on theme: "What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event."— Presentation transcript:

1 What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event object, deciphers it, and processes the user’s interaction

2 Delegation model

3 Sources: –The mouse and keyboard and the GUI components (Buttons, lists, checkboxes etc.) Events: –Objects that describe a state change in a source. Listeners: –Objects notified when events occur.

4 Event Source Event Object Listener When the state of the source changes… The Source registers a Listener… The Source generates an event and sends it to the registered listener

5 Any number of event listener objects can listen for all kinds of events from any number of event source objects. E.g. a program might create one listener per event source. Or a program might have a single listener for all events from all sources. Listeners

6 Multiple listeners can register to be notified of events of a particular type from a particular source. Also, the same listener can listen to notifications from different objects. Each type of listeners can be notified only for its corresponding types of events which can be generated by specific types of sources.

7 Multiple sources, single listener Many buttons can register the same listener since all buttons generate the same type of event. This type of event may be generated by other types of sources as well. button1 ListItem3 button2 ActionListener ActionEvent3 ActionEvent2 ActionEvent1 ActionEvent3

8 Single source, multiple listeners A single source may generate different types of events and thus register multiple listeners. MouseMotion Listener MouseWheel Listener MouseEvent MouseWheelEvent Mouse

9 Listeners as interfaces You implement an interface to create a listener. In the case of a single source that generates multiple types of events you can create a single listener that implements all interfaces (remember: a class may extend only one superclass but implement more than one interfaces).

10 Delegation Model import java.awt.*; public class TestButton { public static void main(String args[]) { Frame f = new Frame("Test"); Button b = new Button("Press Me!"); b.addActionListener(new ButtonHandler()); f.add(b,BorderLayout.CENTER); f.pack(); f.setVisible(true);}} import java.awt.event.*; public class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("Action occurred"); System.out.println(7 "Button's label is :" + e.getActionCommand()); }

11 FrameWith a Single Button 1 import java.awt.*; 2 3 public class TestButton { 4 public static void main(String args[]) { 5 Frame f = new Frame("Test"); 6 Button b = new Button("Press Me!"); 7 b.addActionListener(new ButtonHandler()); 8 f.add(b,BorderLayout.CENTER); 9 f.pack(); 10 f.setVisible(true); 11 } 12 }

12 The ButtonHandler Class 1 import java.awt.event.*; 2 3 public class ButtonHandler implements ActionListener { 4 public void actionPerformed(ActionEvent e) { 5 System.out.println("Action occurred"); 6 System.out.println( 7 "Button's label is :" + e.getActionCommand()); 8 } 9 }

13 Event-Handling in Java An object that describes a change of state in a source component is called an event. The source components can be the elements of the Graphical User Interface (GUI). Events are supported by the classes and interfaces defined in the java.awt.event package. Identifying the Source Of Events: An event source is an object that generates an event. An event source registers some listeners, which receive notifications about a specific type of event generated by that particular event source. All the registered listeners are notified about the generation of an event and receive a copy of the event object. This is known as multicasting the event. Some sources allow only single listener to register. This is known as unicasting of event.

14 Various event sources and the types of events they generate: Event Source Description Checkbox Creates an item event when a check box is selected or deselected. Button Creates an action event when a button is pressed. List Creates an action event when an item is double-clicked; creates an item event when an item is selected or deselected.

15 Event SourceDescription Scrollbar Creates an adjustment event when a scroll bar is scrolled. Text components Creates a text event when a text character is entered in the text component. Window Creates a window event when a window is activated, deactivated, opened, closed, or quit.

16 Event Listeners and Event Handlers An event listener listens for a specific event and is notified when that specific event occurs. An event listener registers with one or more event sources to receive notifications about specific types of events and processes the events. An event-handler is called by the event listener whenever a specific event occurs. Event listeners are interfaces and the event-handler is a method declared in the event listener interface that is implemented by the application. The syntax of a method that registers an event listener with an event source is: public void addTYPEListener(TYPEListener obj)

17 The Delegation Event Model The delegation event model is based on the concept that source generates the event and notifies one or more event listeners. The delegation event model allows you to specify the objects that are to be notified when a specific event occurs. In delegation event model, the event listener has to be registered with a source in order to get notified about the occurrence of a particular event.

18 Event Classes The Java event class hierarchy:

19 Event Classes The Action Event class ActionEvent is generated by an AWT component, such as a button, when a component-specific action is performed. The action event is generated when a button is pressed, a list item is double-clicked, or a menu item is selected. The following syntax shows the declaration of the constructor of the ActionEvent class is: public ActionEvent(Object source, int id, String command) The main methods included in the Action Event class are: String getActionCommand() int getModifiers()

20 Event Classes The MouseEvent class The MouseEvent class extends the java.awt.event.InputEvent class. The mouse event indicates that a mouse action has occurred on a component. The mouse events include: Pressing a mouse button Releasing a mouse button Clicking a mouse button Entering of mouse in a component area Exiting of mouse from a component area The mouse event class defines some integer constants that can be used to identify several types of mouse events.

21 Event Classes Various integer constants of the Event class: Constants Description MOUSE_CLICKED Identifies the event of mouse clicking. MOUSE_DRAGGEDIdentifies the event of dragging of mouse. MOUSE_MOVEDIdentifies the event of mouse moving. MOUSE_PRESSEDIdentifies the event of mouse pressing.

22 Event Classes Constants Description MOUSE_RELEASEDIdentifies the event of mouse releasing. MOUSE_ENTEREDIdentifies the event of mouse entering an AWT component. MOUSE_EXITEDIdentifies the event of mouse exiting an AWT component.

23 Event Classes The following syntax shows the declaration of one of the constructors of the MouseEvent class: public MouseEvent(Component source, int eventType, long when, int modifiers, int x, int y, int clickCount,boolean triggersPopup ) Various methods of the MouseEvent class: MethodsDescription public int getX() Returns the horizontal x coordinate of the mouse position relative to a source component. public int getY() Returns the vertical y coordinate of the mouse position relative to a source component.

24 Event Classes Methods Description public point getPoint()Returns the Point object. The Point object contains the x and y coordinates of the mouse position relative to a source component. public void translatePoint(int x, int y) Translates the coordinates of a mouse event to a new position by adding x and y offsets. public int getClickCount()Returns the number of mouse clicks associated with an event.

25 Event Listener Interfaces An event listener registers with an event source to receive notifications about the events of a particular type. Various event listener interfaces defined in the java.awt.event package: InterfaceDescription ActionListenerDefines the actionPerformed() method to receive and process action events. MouseListenerDefines five methods to receive mouse events, such as when a mouse is clicked, pressed, released, enters, or exits a component. MouseMotionListener Defines two methods to receive events, such as when a mouse is dragged or moved.

26 Event Listener Interfaces InterfaceDescription AdjustmentListner Defines the adjustmentValueChanged() method to receive and process the adjustment events. TextListenerDefines the textValueChanged() method to receive and process an event when the text value changes. WindowListener Defines seven window methods to receive events. ItemListener Defines the itemStateChanged() method when an item has been selected or deselected by the user.

27 Example-Using the ActionListener Interface Problem Statement Create an applet that contains a button. When you click the button, the label of the button is changed from "Click here" to "Button clicked". Solution To solve the above problem, perform the following tasks: Code the application Compile and execute the application

28 Using the MouseListener Interface The MouseListener interface is implemented for receiving various mouse events, such as when you press, click, release, enter, and exit a component. Various public methods declared in the MouseListener interface: MethodsDescription void mouseClicked(MouseEvent me)Performs an action when the mouse button clicks a component. void mousePressed(MouseEvent me)Performs an action when mouse button presses a component. void mouseReleased(MouseEvent me) Performs an action when the mouse button releases a component. void mouseEntered(MouseEvent me)Performs an action when a mouse enters a component area. void mouseExited(MouseEvent me)Performs an action when a mouse exits a component area.

29 Adapter Classes The Java programming language provides adapter classes, which implement the event listener interfaces containing more than one event-handling method. An adapter class provides an empty implementation of the event-handling methods in an event listener interface. The adapter classes are useful because they allows you to receive and process only some of the events that are handled by a particular event listener interface. You can define a class that acts as an event listener by extending one of the adapter classes and overriding its methods to handle a particular type of event.

30 Adapter Classes Various adapter classes: Adapter Class Description KeyAdapter Provides empty implementation of the methods of the KeyListener interface. MouseAdapter Provides empty implementation of the methods of the MouseListener interface. MouseMotionAdapter Provides empty implementation of the methods of the MouseMotionListener interface.

31 Various adapter classes: (contd.) Adapter Classes Adapter Class Description WindowAdapter Provides empty implementation of the methods of the WindowListener and WindowFocusListener interfaces. FocusAdapterProvides empty implementation of the methods of the FocusListener interface.

32 Adapter Classes Using the MouseAdapter Class The MouseAdapter class provides empty implementation of mouse event-handling methods, such as mouseClicked(), mouseEntered(), mouseExited(), mousePressed(), and mouseReleased(). A class that acts as a listener for mouse events extends the MouseAdapter class and overrides the required methods. Using the MouseMotionAdapter Class The MouseMotionAdpater class provides empty implementation of methods, such as mouseDragged() and mouseMoved(). A class that acts as a listener for mouse motion events extends the MouseAdapter class and overrides the required method.

33 The components of an event-driven program are: Event Source: Refers to AWT components such as Button, List, Checkbox, and Scrollbar that generate events. Event Listener- Refers to any object that receives messages or events. Event Handler- Refers to the method that receives and processes the event. The event handler method takes an Event object as a parameter. The various event classes in Java, such as the ActionEvent and MouseEvent classes. To handle action events, you need to register the listener object that implements the ActionListener interface. To handle mouse events, you need to register the listener object that implements the MouseListener interface. Events generated by mouse are of two types, mouse events and mouse motion events.

34 Mouse events include, pressing a mouse button, releasing a mouse button, clicking a mouse button, entering of a mouse in a component area, exiting of a mouse from a component area. Mouse motion events include, moving a mouse and dragging a mouse. Adapter classes provides an empty implementation of all the methods in an event listener interface.

35 Event Handling When an event is generated by a source it is handled by the listener registered by this source. As shown, the listener is an implemented interface (or an extended adapter) and thus you have to implement some methods. These methods take the event as an argument and this is where you put the code to be executed when the event happens. In other words, you define what you want to happen eg. when a button is pressed, inside the actionPerformed method implemented inside the listener To be able to do that efficiently, the event classes define specific methods to extract information about the events.

36 EventObject: // superclass of all events, so the following method is inherited by all event objects Object getSource() MouseEvent: int getX(), int getY() int getButton() KeyEvent: char getKeyChar() ActionEvent: String getActionCommand() long getWhen() Event Handling

37 Four design options Implement your handlers: in separate classes, using inner classes using anonymous inner classes, in the same class that creates your window.

38 Using inner classes This is the easiest and more practical approach. Inner classes belong to the app class and have access to all its members. The only thing you have to do is implement the handler and add its object to the element.

39 Using inner classes //Declare your handler class: class MyHandler Implements ActionListener{... //Add the actionPerformed method inside your handler class: public void actionPerformed(ActionEvent ev){... // Inside your app’s constructor, create your element objects: b1=new JButton(“I’m a Swing button!”);... // Inside your app’ s constructor, add them on your content pane: myCont.add(b1);... // Tie them together in two steps: // Create a handler object inside the app’s constructor: MyHandler handler = new MyHandler(); // Add it to the element: b1.addActionListener(handler);

40 Using anonymous inner classes This is a variation of the previous option. An anonymous inner class is an inner class without a name. You define the class “on the fly” when you need an instance of it (an object) to be created.

41 Using anonymous inner classes //Inside the app’s constructor where you have added the component on the content pane, add the listener just as in the previous case. Only this time write its code at the same time you instantiate and add it: b1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ev) {...

42 Using a separate class Since this does not belong to the app class, it cannot access its private members directly. Due to the above you need to implement public access methods for each app’s element in order to be able to interact with them through the handler.

43 Apart from the above you need to pass a reference of your app object to the handler in order to tie the app and the handler together. Using an inner class you didn’t have to do this, since the handler class belong to the app itself. How you do this: Using a separate class

44 // Create a handler object inside the app’s constructor. Pass a reference to the app using this as an argument: MyHandler handler = new MyHandler(this); // Add it to the element (as with the inner classes): b1.addActionListener(handler); // Inside the handler class: // Declare an app object: MyApp appObj; // Create a handler ’ s constructor which takes an app object as an argument. This is the app object that ties the app with the handler. Assign this object to the object declared inside your handler ’ s class. public MyHandler (MyApp app){appObj=app;}

45 Using a separate class // Inside the handler class: // Add the actionPerformed method (as previously) and access all elements through the appObj: public void actionPerformed(ActionEvent ev) { if ev.getSource()==appObJ.b1{......

46 Using the same class You can make the class that extends a JFrame (the app class) to listen to its own events. This way you have all access advantages you had by using inner classes and putting everything together is easy as well.

47 Using the same class //Extend a JFrame and implement a handler at the same time. actionPerformed is now a method of this same class: class MyHandler extends JFrame implements ActionListener{... //Inside the app’s constructor, register the listener by using this, as the handler-adding methods need handler objects to be passed as arguments. In this case the object passed is of the very same class: b1.addActionListener(this);


Download ppt "What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event."

Similar presentations


Ads by Google