1 / 31

Event Handling

Event Handling. Objectives. Concept of events Event handling in Java Action, Window and Mouse Events Event Adapters. Event: Introduction. An event occurs when a user clicks a mouse button, presses or releases a key, or in general, interacts with the program

elsa
Download Presentation

Event Handling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Event Handling

  2. Objectives • Concept of events • Event handling in Java • Action, Window and Mouse Events • Event Adapters

  3. Event: Introduction • An event occurs when a user clicks a mouse button, presses or releases a key, or in general, interacts with the program • An event can be thought of as an external user action with the program; the sequence of this interaction is user dependent • User’s interaction is analogous to generating a signal to the program and the program would be expected to respond • It is then up to the program whether it responds or ignores the event

  4. Responding to an Event • A program, in order to respond to an event, must know three important pieces of information about the event • What type of event occurred? • Which component originated the event? • Who gets notified when the event occurs? • A GUI component may be able to generate more than one event type - for example, releasing a key generates a key released and a key typed event • Many components on a GUI screen may generate the same type of event - all buttons generate action events, program’s response may differ from one button to another • We may designate an object to listen for the arrival of an event i.e be notified

  5. Event Models • An event model describes the mechanism of handling events in a programming environment • In the old days (jdk1.0), Java’s event handling was hierarchical - events were handled in the top layer of an application • In the current model, the event handling is delegation based - we delegate the responsibility of event handling for a component to an object and we tell all (or who so ever cares to listen) about it • Notice that in the delegation model, we can have any number of objects responsible for event handling

  6. What about the three pieces of information? • How do Java programs deal with the three pieces of information • What type of event occurred? • This is easy. Java programs do not worry about it, but JVM does. JVM recognizes the type of event and takes the responsibility of notifying the designated greeter • Which component originated the event? • This is a programming responsibility and we will see how to do that • Who gets notified when an event occurs? • In some sense, JVM is the starting point of the notification cycle. However, we designate Java objects as responsible parties to be notified by JVM

  7. Responding to an event • The notification process depends on registering an object with a component for an event • The objects responsible for event handling are sometimes called Listeners • Listeners are interface classes • Listeners declare abstract methods, each method is associated with a predefined type of event • When JVM recognizes an event, it notifies the registered listener which in turn executes the designated method • The program defines the response to an event by providing content to the interface methods

  8. Event Handling: Delegation Model Frame Panel or Frame Event handlers Panel Mouse Click i.e. an action event, can occur with either buttons void actionPerformed(ActionEvent e) { // }

  9. Basics of the Event Model • Listener: an object responsible for ‘listening’ for events and responding • Registering Listener - add listener method of the GUI component is used to register the listener object • Event source: The GUI component • Steps: • An user initiated event occurs: for example a mouse click • JVM recognizes an event • The event object is sent to the registered listener object for that component • Listener object activates the handler method to respond

  10. Listeners • Java defines a number of event listener Interfaces Listener Type Listens for ActionListener Action Events ItemListener Change in an item’s state WindowListener Window events MouseListener Mouse events MouseMotionListener Mouse motion events TextListener Change in text value and others....

  11. Registering a Listener • Event sources may register one or more listeners • The current object is registered as a listener for a button named exit exit.addActionListener(this); • A separate class MyWindowListener is registered as the listener for a frame named jf jf.addWindowListener(new MyWindowListener()); • The registration process always takes the form component.addListenerName(listenerObject); • A component can register multiple listener jf.addWindowListener(new MyWindowListener()); jf.addMouseListener(this);

  12. Listener Object • A listener object is an instance of a class that implements the appropriate listener interface exit.addActionListener(this); • ‘this’ object is responsible for implementing the ActionListener interface • Since the current class is responsible for action events from the component exit, the class must be declared using the following format <modifier> class <class name> implements ActionListener { .... }

  13. Listener Object • The listener interface may be implemented in a completely separated class jf.addWindowListener(new MyWindowListener()); • Listener is implemented in a separate class: MyWindowListener • The listener class should be implemented using the following format <modifier> class <class name> implements WindowListener { ......... }

  14. Implementing a Listener • As you know, Listeners are interfaces • They declare abstract methods that an implementing class must implement, or be itself treated as abstract • For event handling, an implementing class must implement all abstract methods declared in the interface • Different interfaces define different abstract methods • For example, the only method defined in ActionListener public void actionPerformed (ActionEvent e) { //code to handle action events }

  15. Example: Event handler in the same class as the event source import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SimpleAction implements ActionListener { SwingFrameWithExit jf; Container cp; JButton one, two, three; JButton exit; JPanel jp; public SimpleAction() { ImageIcon bullet = new ImageIcon("bullet2.gif"); ImageIcon middle = new ImageIcon("middle.gif"); jf = new SwingFrameWithExit(); cp = jf.getContentPane(); cp.setLayout(new BorderLayout(2,2)); SimpleAction declares the intention of handling action events in this class

  16. Example: Event handler in the same class as the event source cp.setBackground(Color.red); // create the Panel jp = new JPanel(); jp.setBackground(Color.blue); // create the buttons and add them to the panel one = new JButton("ONE",bullet); jp.add(one); two = new JButton(middle); jp.add(two); three = new JButton("THREE",bullet); jp.add(three); cp.add(jp,BorderLayout.CENTER); // add panel to the frame exit = new JButton("EXIT"); exit.addActionListener(this); cp.add(exit,BorderLayout.SOUTH); Registering event handler for the GUI component exit; ‘this’ object is the listener

  17. Example: Event handler in the same class as the event source jf.setSize(300,300); jf.setVisible(true); } // Event handler for the Exit button public void actionPerformed(ActionEvent e) { System.exit(0); } public static void main(String[] args) { SimpleAction eac = new SimpleAction(); } } Implementation of the event handling method; JVM notifies this object (SimpleAction) about an action event, which in turn fires actionPerformed method and passes an ActionEvent object to this method Code to respond to the event, may be as needed

  18. Example: Event handler in a separate class • Code is exactly same as the previous example: SimpleAction.java, only changes are shown. The full source is in Example subdirectory for the module ...... public class SimpleActionSeparateClass { ..... public SimpleActionSeparateClass() { ...... exit.addActionListener(new MyButtonHandler()); ....... } public static void main(String[] args) { SimpleActionSeparateClass eac = new SimpleActionSeparateClass(); } } class MyButtonHandler implements ActionListener { // Event handler for the Exit button public void actionPerformed(ActionEvent e) { System.exit(0); } } No ‘implement’ here, since a separate class does event handling Registering by embedding the constructor of the listener object Separate class altogether, does contain the actionPerformed method though

  19. Identifying source of Events • Source of an event can be identified in more than one way • By finding a reference to the source object itself Object evtSource = e.getSource(); if (evtSource == exit) { // response code } • Necessary condition for this code to work exitis a valid reference in the actionPerformed method • Not always possible in a large application

  20. Identifying source of Action Events • An event source can be identified by comparing with the command string String s = e.getActionCommand(); if (“EXIT”equals(s)) { // response code } • The button or other action generating objects must have a ‘face’ string equal to “EXIT” • Not very convenient in a large program or for internationalization

  21. Identifying source of Action Events • A command string can be attached to an event source exit.setActionCommand(“Close”); • The handler method can then compare with this String String s = e.getActionCommand(); if (“Close”equals(s)) { // response code } • This technique is flexible, but program must ensure unique command string names.

  22. Example: Action event from multiple sources BorderLayoutEvents.java

  23. WindowListener Interface • Window Listeners are used to trap Window events • We can use window events to monitor events with frames and dialog boxes • The implementing class can be same as the class that originates the events, or a separate class • Since the WindowListener interface defines 7 abstract methods, the implementing class must implement all 7 of them • The next slide shows an example of a window listener class that can be registered to listen for window events • jf.addWindowListener(new MyWindowListener());

  24. WindowListener Interface import java.awt.event.*; public class MyWindowListener implements WindowListener { public void windowClosed(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) { System.exit(0); } } • Shows all methods of the Window Listener interface Only closing event is implemented

  25. Event handling through Adapters • MyWindowListener implements only one method • windowClosing(WindowEvent e) • Six other methods of the WindowListener interface must still be implemented even if all of these have empty actions • This approach is ‘bothersome’ • Java provides adapter classes matching each listener class where the listener has more than one abstract methods • For example, WindowListener has a corresponding WindowAdapter class

  26. Event handling through Adapters • Adapter classes are not abstract • These can be extended and only required method(s) can be overridden class MyWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } } • MyWindowAdapter class overrides the windowClosing method and provides for exiting from an application.

  27. Event handling through Adapters • All other methods of WindowAdapter class are then inherited by the MyWindowAdapter; these inherited methods have empty implementation • Such an adapter object can be registered as the event handler for a frame using similar syntax as in the case of the listener class object • jf.addWindowListener(new MyWindowAdapter()); • Java provides adapter classesfor all listeners with more than one abstract method

  28. Mouse Listener • Receives mouse events excluding motion • Name of the interface is MouseListener When called void mouseClicked(MouseEvent e) mouse is clicked void mouseEntered(MouseEvent e) enters a component void mouseExited(MouseEvent e) exits a component void mousePressed(MouseEvent e) mouse is pressed void mouseReleased(MouseEvent e) mouse is released • Yes, there is a MouseAdapter class

  29. Interesting methods of Mouse Event • int getClickCount() - gets you the number of mouse clicks • Point getPoint() - Returns the x,y coordinates of the mouse event, These coordinates are screen coordinates in pixels • int getX() - Returns the x coordinate of the event • int getY() - Returns the y coordinate of the event

  30. Mouse Motion Listener • Interface to track Mouse Motion • There is an equivalent MouseMotionAdapter class • Since mouse motion events get constantly fired as a mouse moves, efficiency dictates a separation between motion and mouse down. • Two event types void mouseDragged(MouseEvent e) - fires when a mouse button is pressed on a component and then dragged void mouseMoved(MouseEvent e) - fires when the mouse button is moved on a component without any button down

  31. Example: Mouse Events MouseEventDemo.java

More Related