0% found this document useful (0 votes)
58 views31 pages

Event Handling

This document discusses event handling in Java. It explains that Java uses the event delegation model which gives more flexibility than languages like Visual Basic and C. It describes how events are generated by event sources and handled by registered event listeners. It provides examples of common event classes like ActionEvent and listeners like ActionListener. It also discusses how to identify the specific event source that triggered an event and how to handle different types of events like window events using adapters.

Uploaded by

vedant kulkarni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views31 pages

Event Handling

This document discusses event handling in Java. It explains that Java uses the event delegation model which gives more flexibility than languages like Visual Basic and C. It describes how events are generated by event sources and handled by registered event listeners. It provides examples of common event classes like ActionEvent and listeners like ActionListener. It also discusses how to identify the specific event source that triggered an event and how to handle different types of events like window events using adapters.

Uploaded by

vedant kulkarni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Event Handling

1
To implement Graphical User Interface programming, the event
handling is very important.

Working:

OS constantly monitors the events from event queue such as


Key Events, Window Events, Mouse Events, etc.

The OS reports these events to currently running programs.

Each program then decides what to do in response to these events.

Before Java we have two way to handle events…

2
Visual Basic Approach:
Each GUI component response to a fixed set of events.
We can not change in it.

The EVENT QUEUE is hidden form programmer

We need to write code for specific event in event procedure.

C Language Approach:
The EVENT QUEUE is not hidden from programmer.

We write code that constantly check the events from


the EVENT QUEUE of OS.

It is some what difficult to write code.

Advantage: - The events that we responds are not limited as in VB.


3
The Java uses the approach between the above two approaches.

Java used the Event Delegation Model.


It gives us more flexibility than other languages like VB and C.

Event Source:

Event Class:

Event Listener Interface:

4
Event Delegation Model:

Event Source

Cr
ea
ter

tes
gis
Re
Event Listener Sends Event Class
Interface Object
In
vo
kes

Event Listener
Methods
5
Event Delegation Model:

6
Different Events by different Event Sources:

Button produce ActionEvent and send object of ActionEvent Class


Window produce WindowEvent and send object of WindowEvent
Mouse produce MouseEvent and send object of MouseEvent class.

Working of Event Delegation Model: -

 Implement a class from Listener Interface.

 Register a Event Source to the appropriate Listener.

 When an event occurs an Event Source sends the event object to all the
registered Listeners.

 The Listener uses this information of event object to react to event.

 The Listener contains methods that executes as reaction to the event.

7
Register an Event Source to Listener: -
eventSourceObject.addEventListener (eventListenerObject);

e.g.

Button b1 = new Button (“OK”);


add(b1);
b1.addActionListener(ListenerClassObject);

The ActionListener interface have a method


actionPerformed(ActionEvent a)

This method get execute every time we clicked on “OK” button.

8
Respond to Event: -
First we need to write definition of class that implements Listener
Interface.

Listener Interface contains several methods,


Which we need to override in our class.

class MyListener implements ActionListener


{
----
public void actionPerformed(ActionEvent ae)
{
// Code that react to Action Event.
}
----
}
Then,

we register the Event Source as follows…

MyListener ml = new MyListener();


b1.addActionListener(ml); 9
AWT Event Class Hierarchy: -

EventObject
|
AWTEvent
_________________________|________________________________
| | | |
ActionEvent Adjustment Event Component Event
ItemEvent _________________________________|
______________________
| | | |
FocusEvent InputEvent PaintEvent WindowEvent
___________|__________________
| |
KeyEvent MouseEvent
|
MouseWheelEvent
10
Some Commonly used AWT Event Classes: -
ActionEvent KeyEvent
AdjustmentEvent MouseEvent
FocusEvent MouseWheelEvent
ItemEvent WindowEvent

Some Commonly used Listeners Interfaces: -


ActionListener MouseListener
AdjustmentListener MouseMotionListener
FocusListener WindowListener
ItemListener KeyListener

11
Assignment:
Create Frame with three Button Red, Blue, and Green in it.
Write a program to handle the Action Event such that
When we click on Red Button, Background Color of frame changes to
Red, if click on Blue Button, then Background Color of frame changes to
Blue, and so on.

12
When single panel sets as listener to more than one event source,
then we need to identify the event source which generates the event.

e.g.
In above assignment all three buttons have single listener panel.
So
In actionPerformed() method we need to identify the button for which
it get called, to performed appropriate action.

We can do this in two way…

1)
String getActionCommand(): - This method returns the command string
associated with the event source.

2)
Object getSource(): - This method returns the event source for which
actionPerformed() method get called.
13
e.g. 1)

public void actionPerformed(ActionEvent ae)


{
String str = ae.getActionCommand();

if( str.equals (“Red”) )


----
else if( str.equals (“Blue”) )
----
else if( str.equals (“Green”) )
----
}

Note: - We may make an easy mistake to caption the button and then spell
the string differently while checking with command string.

14
e.g. 2.

public void actionPerformed(ActionEvent ae)


{
Object src = ae.getSource();

if( src = = b1 )
----
else if( src = = b2 )
----
else if( src = = b3 )
----
}

15
Window Events: -
To handle the Window events we need to used WindowEvent class and
WindowListener interface. Window event is performed on Window
and not on Panel.

Steps To Handle Window Event: -


 Register the event source (frame) to appropriate Listener (WindowListener)
by using addWindowListener() method.

 WindowListener Interface contains 7 methods to handle 7 window events .

 We need to define all the 7 methods in class which implements from


WindowListener.

 All the 7 methods required one argument of type WindowEvent.

16
The 7 methods of WindowListener are…
public void windowOpened(WindowEvent we)
// get called after window has been opened.

public void windowClosing(WindowEvent we)


// get called when user issued window closed command.

public void windowClosed(WindowEvent we)


// get called after window has closed.

public void windowIconified(WindowEvent we)


// get called when window has minimized.

public void windowDeiconified(WindowEvent we)


// get called when window has maximized.

public void windowActivated(WindowEvent we)


// get called when window has become activate.

public void windowDeactivated(WindowEvent we)


// get called when window has become deactivate. 17
class FrameEvent extends Frame implements WindowListener
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
public void windowClosed(WindowEvent we) { }
public void windowOpened(WindowEvent we) { }
public void windowIconified(WindowEvent we) { }
public void windowDeiconified(WindowEvent we) { }
public void windowActivated(WindowEvent we) { }
public void windowDeactivated(WindowEvent we) { }
}
And then…

FrameEvent fevt = new FrameEvent();


frm.addWindowListener(fevt);

Otherwise…

18
Adapter Classes: -
It is tedious task to write the definition of six do nothing methods.

To simplify this task, AWT provides us Adapter Classes for all the
Interfaces which having more than one method in it.

These Adapter classes are already implementing from the Interfaces to


satisfy the technical requirement of Java

Adapter Classes of AWT are…


WindowAdapter MouseAdapter
FocusAdapter KeyAdapter
MouseMotionAdapter

Note: - But we can not extends our frame class from two classes i.e. Frame
and WindowAdapter i.e. Multiple Inheritance is not allowed.

19
So we need to extends new class from Adapter class as…

class FrameEvent extends WindowAdapter


{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}

And then…
FrameEvent fevt = new FrameEvent();
frm.addWindowListener(fevt);

Still it is no need to create an object of FrameEvent class.

20
So, we can write directly as…

frm.addWindowListener ( new FrameEvent() );

We can go even further by creating anonymous class as follows…

Anonymous class: -
It is class, which has no name.

It combines the class declaration and the creation of an instance


of the class in one step.

21
Rules:
 An anonymous class must always extend a super class or implement an
interface but it cannot have an explicit extends or implements clause.

 An anonymous class must implement all the abstract methods in the


super class or the interface.

 An anonymous class always uses the default constructor from the super
class to create an instance.

e.g.
frm.addWindowListener( new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
22
This will do…

 It defines a class without a name that extends WindowAdapter class.

 Adds a windowClosing() method to this anonymous class.

 WindowAdapter class inherits remaining six do nothing methods in to


anonymous class.

 Creates an object of anonymous class, that also does not have a name.

 Passes the object to the addWindowListener() method.

23
Mouse Events: -

When we wants to do drawing with mouse, or to do selection


we need to trap mouse events like 1. Mouse Click
2. Mouse Move, and
3. Mouse drag.

For that we need to used two listener 1. MouseListener


2. MouseMotionListener
3. MouseWheelListener

When the user clicks a mouse button, three methods get called for
MouseListener…

mousePressed() - when mouse is first pressed.

mouseReleased() - when mouse is released.

mouseClicked() - at the last after mouse released.

24
When the user moves a mouse,
two methods get called for MouseMotionListener…

mouseDragged() : When user drag mouse by pressing mouse.


mouseMoved() : When user move the mouse.

When the user moves a scrolling wheel of mouse ,


two methods get called for MouseWheelListener…

mouseWheelMoved() : When user drag mouse by pressing


mouse.

25
Some methods used to handle mouse event…

getX() - returns the x-coordinate of mouse pointer.

getY() - returns the Y-coordinate of mouse pointer.

getPoint() - returns the (x, y) coordinates by Point object.

getClickedCount() - returns the no of consecutive mouse click count.

getWheelRoatation() - returns the rotation direction of wheel.

getScrollAmout() - returns the amount of scroll of wheel.

26
Key Events: -

When user presses any key on keyboard this event occur. We need
to handle the key events.

The three methods of KeyListener interface gets called…


keyPressed() - When user presses a key, returns key actual pressed
keyReleased() - When user released a key, returns actual key pressed
keyTyped() - Used to get characters generated by key strokes.

Java makes an distinction between characters on the Keyboard and virtual key
(functional keys) codes.

Virtual key codes are indicated with a prefix of VK_ such as…
VK_A - denotes the key marked with A,
VK_B - denotes the key marked with B,
VK_SHIFT - denotes the key marked with Shift,
and so on…

27
Note: - There is no separate lowercase virtual key code.

e.g.
If user types an uppercase “A”, i.e. Shift + a, then 5 events generated are…
 Pressed the SHIFT key - keyPressed() get called for VK-SHIFT.

 Pressed the “A” key - keyPressed() get called for VK_A.


 Typed “A” key - keyTyped () get called for an “A”.
 Released the “A” key - keyReleased() get called for VK_A.
 Released the SHIFT key - keyReleased() get called for VK_SHIFT.

If user types an lowercase “a”, i.e. just A, then 3 events generated are…
 Pressed the A key - keyPressed() get called for VK_A.
 Typed “a” key - keyTyped() get called for an “a”.
 Released the “a” key - keyReleased() get called for VK_A.

28
While working with keyPressed and keyReleased methods…

public static void keyPressed (KeyEvent ke)


{
int keycode = ke.getKeyCode();
----
}

The keycode is one of the constants defined in KeyEvent class.


VK_A … VK_Z, VK_0 … VK_9, VK_F1 … VK_F12
VK_SPACE, VK_ENTER, VK_SHIFT, VK_CONTROL, VK_ALT,
VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN
VK_PAGE_UP, VK_PAGE_DOWN, VK_HOME, VK_END, etc.

29
While working with keyTyped method…

public static void keyTyped (KeyEvent ke)


{
char keychar = ke.getKeyChar();
----
}

The current state of SHIFT, CONTROL, ALT keys can be checked as…

isShiftDown() - returns true/false if SHIFT key was held down or not.


isControlDown() - returns true/false if CONTROL key was down or not.
isAltDown() - returns true/false if ALT key was down or not.

30
Following code will tests whether user presses
SHIFT + RIGHT ARROW

public static void keyPressed (KeyEvent ke)


{
int keyCode = ke.getKeyCode();

if( keyCode == KeyEvent.VK_s && ke.isControlDown())


{
----
----
}
}

31

You might also like