Presentation is loading. Please wait.

Presentation is loading. Please wait.

Event Handling Chapter 2 Objectives

Similar presentations


Presentation on theme: "Event Handling Chapter 2 Objectives"— Presentation transcript:

1 Event Handling Chapter 2 Objectives
To write event driven programs using the delegation event model To write programs using adapter classes & the inner classes

2 2.1 Delegation Event Model
-> What is an Event? Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of user interaction with the graphical user interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page are the activities that causes an event to happen.

3 Types of Event -> The events can be broadly classified into two categories: Foreground Events - Those events which require the direct interaction of user. They are generated as consequences of a person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page etc. 2) Background Events - Those events that require the interaction of end user are known as background events. Operating system interrupts, hardware or software failure, timer expires, an operation completion are the example of background events.

4 What is Event Handling? Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard mechanism to generate and handle the events.

5 Components of Delegation Event Model
1) Source - The source is an object on which event occurs. Source is responsible for providing information of the occurred event to it's handler. Java provide as with classes for source object. 2) Listener - It is also known as event handler. Listener is responsible for generating response to an event. From java implementation point of view the listener is also an object. Listener waits until it receives an event. Once the event is received , the listener process the event an then returns.

6 In this model, an event is sent to component from which it originated
In this model, an event is sent to component from which it originated. The component registers a listener object with the program. The listener processes the event and then returns. For e.g.: When you click a button, the action to be performed is handled by an object registered to handle the button click event. The following diagram illustrates the delegation event model Every event has a corresponding listener interface that specifies the methods that are required to handle the event. Event object are sent to registered listeners. To enable a component to handle events, you must register an appropriate listener for it.

7 The Event Handling process
When an event is triggered, the JAVA runtime first determines its source and type. If a listener for this type of event is registered with the source, an event object is created. For each listener to this type of an event, the JAVA runtime invokes the appropriate event handling method to the listener and passes the event object as the parameter.

8 The Event Handling Process

9 Event Class hierarchy The Event classes are used to represent the event. Following diagram shows hierarchy of event classes.

10 Constructors: Methods:
At the root of Java event class hierarchy is EventObject which is in java.util. It is a super class for all events. Constructors: -> EventObject(Object src) ‘src’ is event that generates event. Methods: -> getSource()-returns the source of the event. -> toString()-returns string equivalent of event. AWT Event is the subclass of EventObject. It is in java.awt package.It is the super class of all AWT-based events. The ComponentEvent class is super class of FocusEvent,InputEvent,WindowEvent.

11 Event Classes 1) Action Event class 3) Component Event class
-> An action event is generated when a button is pressed, a list item is double clicked. 2) Adjustment Event class -> Adjustment event is generated by a scrollbar. 3) Component Event class -> It is generated when a component is hidden, moved, resized or becomes visible. 4) Item Event class -> Generated when checkbox or a list item is clicked or when a checkbox menu item is selected or deselected. 5) Text Event class -> Generated when the value of textarea or textfield is changed. 6) Focus Event class -> Event is generated when a component gains or losses input focus. 7) Key Event class -> KeyEvent occurs, when keyboard input occurs.

12 -> Window is iconified, deiconified, opened or closed.
8) Mouse Event class -> Generated when the mouse is dragged, moved, clicked, pressed or released, also generated when mouse enters or exits a component. 9) Window Event class -> Window is iconified, deiconified, opened or closed. 10) Container Event class –> components are added or removed from Container

13 The listener interface
An event listener interface defines the methods used by a component to dispatch events. Each event type will have at least one corresponding dispatch method in a listener interface. To listen for an event, a listener must implement the Listener interface and register itself with the component. When an event occurs, the component will call the proper dispatch method. The methods are defined in an interface so that any object can receive the event. 

14 When you use interfaces for creating listeners, the listener class has to override all the methods that are declared in the interface. Some of the interfaces have only one method, whereas others have many. Even if you want to handle only one event, you have to override all the methods. To overcome this, the event package provides 7 adapter classes.

15 Event Classes and their corresponding Listener Interfaces
1) ActionEvent ActionListener 2) MouseEvent MouseListener andMouseMotionListener 3) KeyEvent KeyListener 4)ItemEvent ItemListener 5)TextEvent TextListener 6)AdjustmentEvent AdjustmentListener 7)WindowEvent WindowListener 8)ComponentEvent ComponentListener 9)ContainerEvent ContainerListener 10)FocusEvent FocusListener

16 import java.awt.*; import java.applet.*; import java.awt.event.*; /* <applet code="ActionDemo.class" width=200 height=200> </applet> */ public class ActionDemo extends Applet implements ActionListener { String actionMessage=""; public void init() Button Button1 = new Button("Ok"); Button Button2 = new Button("Cancel"); add(Button1); add(Button2); //set action listeners for buttons Button1.addActionListener(this); Button2.addActionListener(this); } public void paint(Graphics g) g.drawString(actionMessage,10,50); public void actionPerformed(ActionEvent ae){ /* Get the action command using String getActionCommand() method. */ String action = ae.getActionCommand(); if(action.equals("Ok")) actionMessage = "Ok Button Pressed"; else if(action.equals("Cancel")) actionMessage = "Cancel Button Pressed"; repaint();

17

18 import java. awt. event. ; import java. awt. ; import java. applet
import java.awt.event.*; import java.awt.*; import java.applet.*; public class checkboxlistener extends Applet implements ItemListener { Checkbox m1,m2,m3; public void init() m1=new Checkbox("A"); m2=new Checkbox("B"); m3=new Checkbox("C"); add(m1); add(m2); add(m3); m1.addItemListener(this); m2.addItemListener(this); } public void itemStateChanged(ItemEvent ie) if(ie.getSource()==m1) setBackground(Color.red); if(ie.getSource()==m2) setBackground(Color.green); /* <applet code="checkboxlistener.class" height=150 width=150 > </applet>*/

19

20 import java. awt. ; import java. awt. event. ; import java. applet
import java.awt.*; import java.awt.event.*; import java.applet.*; public class KeyDemo extends Applet implements KeyListener { String msg=""; public void init() addKeyListener(this); } public void keyPressed(KeyEvent k) showStatus("KeyPressed"); public void keyReleased(KeyEvent k) showStatus("KeyRealesed"); public void keyTyped(KeyEvent k) msg = msg+k.getKeyChar(); repaint(); public void paint(Graphics g) g.drawString(msg, 20, 40); /*<applet code="KeyDemo.class" width=500 height=500></applet>*/

21 import java.awt.*; import javax.swing.*; import java.awt.event.*; public class AdjustmentListenerExample { public static void main(String[] args) Frame frame = new Frame("AdjustmentListenerExample"); Label label = new Label("Welcome To JavaTips.net"); Scrollbar hbar = new Scrollbar(Scrollbar.HORIZONTAL, 30, 20, 0, 300); Scrollbar vbar = new Scrollbar(Scrollbar.VERTICAL, 30, 40, 0, 300); frame.setLayout(new BorderLayout()); frame.add(hbar, BorderLayout.SOUTH); frame.add(vbar, BorderLayout.EAST); frame.add(label, BorderLayout.CENTER); AdjustmentListener adj = new MyAdjustmentListener(); hbar.addAdjustmentListener(adj); vbar.addAdjustmentListener(adj); frame.setSize(400, 400); frame.setVisible(true); } } class MyAdjustmentListener implements AdjustmentListener public void adjustmentValueChanged(AdjustmentEvent ae) System.out.println(ae.getValue()); }

22

23 Adapter classes in Java
An adapter class provides the default implementation of all methods in an event listener interface. They are very useful when you want to process only few of the events that are handled by a particular event listener interface. You can define a new class by extending one of the adapter classes and implement only those events relevant to you. The adapter classes are found in java.awt.event package. The Adapter classes with their corresponding listener interfaces are given below.

24 Adapter class Listener interface 1) WindowAdapter WindowListener 2) KeyAdapter KeyListener 3)MouseAdapter MouseListener 4)MouseMotionAdapter MouseMotionListener 5)FocusAdapter FocusListener 6)ComponentAdapter ComponentListener 7)ContainerAdapter ContainerListener

25 -> We only need to implement those methods that are modified.
-> For example, the WindowListener interface contains seven methods. Whenever we need to use this interface we must implement all 7 methods. So when we use the Adapter class (WindowAdapter) we don't need to implement all the methods. -> We only need to implement those methods that are modified. -> Various methods of the WindowListener class 1) public void windowActivated(WindowEvent we) This method is used when the current Window is set to be activated. 2) public void windowClosed(WindowEvent we) Invoked when a window has been closed. 3) public void windowClosing(WindowEvent we) When a user wants to close a window this method is used. 4) public void windowDeactivated(WindowEvent we) Used when the current window is not activated for a long time. 5) public void windowDeiconfied(WindowEvent we) Used when a window changes its position from minimized to normal (restored) state. 6) public void windowIconified(WindowEvent we) Used when a window is changed from normal to minimized state. 7) public void windowOpened(WindowEvent e) Invoked when a window has been opened.

26 How to create an adapter :
public class WindowAdapter implements WindowListner { public void windowClosed(WindowEvent e){} public void windowOpened(WindowEvent e){} public void windowIconified(WindowEvent e){} public void windowDeiconified(WindowEvent e){} public void windowActivated(WindowEvent e){} public void windowDeactivated(WindowEvent e){} public void windowClosing(WindowEvent e){} }

27 import java.awt.*; import java.awt.event.*; public class WindowAdapterEx extends Frame { public WindowAdapterEx() WindowAdapterClose clsme = new WindowAdapterClose(); addWindowListener(clsme); setTitle("WindowAdapter frame closing"); setSize(400, 400); setVisible(true); } public static void main(String args[]) new WindowAdapterEx(); class WindowAdapterClose extends WindowAdapter public void windowClosing(WindowEvent e) System.exit(0);

28 Java MouseAdapter Example import java. awt. ; import java. awt. event
Java MouseAdapter Example 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();

29 import java.applet.*; import java.awt.*; import java.awt.event.*; /*<applet code="mouseevent.class" width=400 height=500></applet>*/ public class mouseevent extends Applet { int x=0; int y=0; public void init() addMouseListener(new mymouselistener()); } public void paint(Graphics g) g.drawString("This is MouseAdapter class",x,y); public class mymouselistener extends MouseAdapter public void mouseClicked(MouseEvent e) x=e.getX(); y=e.getY(); repaint();

30 Inner Classes Java inner class or nested class is a class i.e. declared inside the class or interface. We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable. It can access all the members of outer class including private data members and methods.

31 Inner Classes (Non-static Nested Classes)
Inner classes are a security mechanism in Java. A class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class. Inner classes are of three types depending on how and where they are defined. Types are 1) Inner Class 2) Method-local Inner Class 3) Anonymous Inner Class

32 Inner class To create an inner class we need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class. class Outer_Demo { int num; private class Inner_Demo // inner class { public void print() { System.out.println("This is an inner class"); } void display_Inner() Inner_Demo inner = new Inner_Demo(); inner.print(); public class My_class public static void main(String args[]) Outer_Demo outer = new Outer_Demo(); // Instantiating the outer class outer.display_Inner(); // Accessing the display_Inner() method.

33 Method-local Inner Class
In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method. A method-local inner class can be instantiated only within the method where the inner class is defined.

34 public class Outerclass { void my_Method() { int num = 23; class MethodInner_Demo { public void print() { System.out.println("This is method inner class "+num); } } // end of inner class MethodInner_Demo inner = new MethodInner_Demo(); inner.print(); } public static void main(String args[]) Outerclass outer = new Outerclass(); outer.my_Method();


Download ppt "Event Handling Chapter 2 Objectives"

Similar presentations


Ads by Google