Presentation is loading. Please wait.

Presentation is loading. Please wait.

For IST410 Students only Events-1 Event Handling.

Similar presentations


Presentation on theme: "For IST410 Students only Events-1 Event Handling."— Presentation transcript:

1 For IST410 Students only Events-1 Event Handling

2 For IST410 Students only Events-2 Objectives l Concept of events l Event handling in Java l Action, Window and Mouse Events l Event Adapters

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

4 For IST410 Students only Events-4 l A program, in order to respond to an event, must know three important pieces of information about the event m What type of event occurred? m Which component originated the event? m Who gets notified when the event occurs? l 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 l 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 l We may designate an object to listen for the arrival of an event i.e be notified Responding to an Event

5 For IST410 Students only Events-5 l An event model describes the mechanism of handling events in a programming environment l In the old days (jdk1.0), Java’s event handling was hierarchical - events were handled in the top layer of an application l 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 l Notice that in the delegation model, we can have any number of objects responsible for event handling Event Models

6 For IST410 Students only Events-6 l How do Java programs deal with the three pieces of information l What type of event occurred? m 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 l Which component originated the event? m This is a programming responsibility and we will see how to do that l Who gets notified when an event occurs? m 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 What about the three pieces of information?

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

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

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

10 For IST410 Students only Events-10 l Java defines a number of event listener Interfaces Listener TypeListens for ActionListenerAction Events ItemListenerChange in an item’s state WindowListenerWindow events MouseListenerMouse events MouseMotionListener Mouse motion events TextListenerChange in text value and others.... Listeners

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

12 For IST410 Students only Events-12 l A listener object is an instance of a class that implements the appropriate listener interface exit.addActionListener(this); m ‘this’ object is responsible for implementing the ActionListener interface l Since the current class is responsible for action events from the component exit, the class must be declared using the following format class implements ActionListener {.... } Listener Object

13 For IST410 Students only Events-13 l The listener interface may be implemented in a completely separated class jf.addWindowListener(new MyWindowListener()); m Listener is implemented in a separate class: MyWindowListener l The listener class should be implemented using the following format class implements WindowListener {......... } Listener Object

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

15 For IST410 Students only Events-15 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)); Example: Event handler in the same class as the event source SimpleAction declares the intention of handling action events in this class

16 For IST410 Students only Events-16 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); Example: Event handler in the same class as the event source Registering event handler for the GUI component exit; ‘this’ object is the listener

17 For IST410 Students only Events-17 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(); } Example: Event handler in the same class as the event source 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 For IST410 Students only Events-18 l 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); } Example: Event handler in a separate class 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 For IST410 Students only Events-19 l Source of an event can be identified in more than one way l By finding a reference to the source object itself Object evtSource = e.getSource(); if (evtSource == exit) { // response code } l Necessary condition for this code to work exit is a valid reference in the actionPerformed method l Not always possible in a large application Identifying source of Events

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

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

22 For IST410 Students only Events-22 BorderLayoutEvents.java Example: Action event from multiple sources

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

24 For IST410 Students only Events-24 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); } l Shows all methods of the Window Listener interface WindowListener Interface Only closing event is implemented

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

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

27 For IST410 Students only Events-27 l All other methods of WindowAdapter class are then inherited by the MyWindowAdapter; these inherited methods have empty implementation l 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 m jf.addWindowListener(new MyWindowAdapter()); l Java provides adapter classes for all listeners with more than one abstract method Event handling through Adapters

28 For IST410 Students only Events-28 l Receives mouse events excluding motion l 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 l Yes, there is a MouseAdapter class Mouse Listener

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

30 For IST410 Students only Events-30 l Interface to track Mouse Motion l There is an equivalent MouseMotionAdapter class l Since mouse motion events get constantly fired as a mouse moves, efficiency dictates a separation between motion and mouse down. l 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 Mouse Motion Listener

31 For IST410 Students only Events-31 MouseEventDemo.java Example: Mouse Events


Download ppt "For IST410 Students only Events-1 Event Handling."

Similar presentations


Ads by Google