SlideShare a Scribd company logo
oops@chapter6 Page 1
Chapter-6
Event Handling
Event handling is fundamental to Java programming because it is integral to
the creation of applets and other types of GUI-based programs.
Events
In the delegation model, an event is an object that describes a state change
in a source. It can be generated as a consequence of a person interacting
with the elements in a graphical user interface. Some of the activities that
cause events to be generated are pressing a button, entering a character via
the keyboard, selecting an item in a list, and clicking the mouse etc.
Events may also occur that are not directly caused by interactions with a
user interface.
Event Sources
A source is an object that generates an event. This occurs when the internal
state of that object changes in some way. Sources may generate more than
one type of event.
Each type of event has its own registration method. Here is the general form:
public void addTypeListener(TypeListener el)
Here, Type is the name of the event, and el is a reference to the event
listener. For example, the method that registers a keyboard event listener is
called addKeyListener( ). The method that registers a mouse motion
listener is called addMouseMotionListener( ). When an event occurs, all
registered listeners are notified and receive a copy of the event object. This is
known as multicasting the event.
Some sources may allow only one listener to register. The general form of
such a method is this:
public void addTypeListener(TypeListener el)
throws java.util.TooManyListenersException
Here, Type is the name of the event, and el is a reference to the event
listener. When such an event occurs, the registered listener is notified. This
is known as unicasting the event.
A source must also provide a method that allows a listener to unregister an
interest in a specific type of event. The general form of such a method is
this:
public void removeTypeListener(TypeListener el)
Here, Type is the name of the event, and el is a reference to the event
listener. For example, to remove a keyboard listener, you would call
removeKeyListener( ).
Event Listeners
Alistener is an object that is notified when an event occurs. It has two major
requirements.
First, it must have been registered with one or more sources to receive
notifications about specific types of events. Second, it must implement
methods to receive and process these notifications.
oops@chapter6 Page 2
The methods that receive and process events are defined in a set of
interfaces found in java.awt.event.
Event Classes
The classes that represent events are at the core of Java’s event handling
mechanism. Thus, a discussion of event handling must begin with the event
classes. It is important to understand, however, that Java defines several
types of events and that not all event classes can be discussed in this
chapter. The most widely used events are those defined by the AWT and
those defined by Swing. This chapter focuses on the AWT events. (Most of
these events also apply to Swing.)
At the root of the Java event class hierarchy is EventObject, which is in
java.util. It is the superclass for all events. Its one constructor is shown
here:
EventObject(Object src)
Here, src is the object that generates this event. EventObject contains two
methods: getSource( ) and toString( ). The getSource( ) method returns the
source of the event. Its general form is shown here:
Object getSource( )
As expected, toString( ) returns the string equivalent of the event.
The class AWTEvent, defined within the java.awt package, is a subclass of
EventObject. It is the superclass (either directly or indirectly) of all AWT-
based events used by the delegation event model. Its getID( ) method can be
used to determine the type of the event. The signature of this method is
shown here:
int getID( )
At this point, it is important to know only that all of the other classes
discussed in this section are subclasses of AWTEvent.
To summarize:
• EventObject is a superclass of all events.
• AWTEvent is a superclass of all AWT events that are handled by the
delegation event model.
The package java.awt.event defines many types of events that are generated
by various user interface elements.
oops@chapter6 Page 3
The ActionEvent Class
An ActionEvent is generated when a button is pressed, a list item is
double-clicked, or a menu item is selected. The ActionEvent class defines
four integer constants that can be used to identify any modifiers associated
with an action event
The KeyEvent Class
AKeyEvent is generated when keyboard input occurs. There are three types
of key events, which are identified by these integer constants:
KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first two events
are generated when any key is pressed or released. The last event occurs
only when a character is generated. Remember, not all keyp presses result
in characters. For example, pressing SHIFT does not generate a character.
There are many other integer constants that are defined by KeyEvent. For
example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII
equivalents of the numbers and letters. Here are some others:
The VK constants specify virtual key codes and are independent of any
modifiers, such as control, shift, or alt.
KeyEvent is a subclass of InputEvent. Here is one of its constructors:
KeyEvent(Component src, int type, long when, int modifiers, int code,
char ch)
Here, src is a reference to the component that generated the event. The type
of the event is specified by type. The system time at which the key was
pressed is passed in when. The modifiers argument indicates which
modifiers were pressed when this key event occurred. The virtual key code,
such as VK_UP, VK_A, and so forth, is passed in code. The character
oops@chapter6 Page 4
equivalent (if one exists) is passed in ch. If no valid character exists, then ch
contains CHAR_UNDEFINED. For KEY_TYPED events, code will contain
VK_UNDEFINED.
The KeyEvent class defines several methods, but the most commonly used
ones are getKeyChar( ), which returns the character that was entered, and
getKeyCode( ), which returns the key code. Their general forms are shown
here:
char getKeyChar( )
int getKeyCode( )
If no valid character is available, then getKeyChar( ) returns
CHAR_UNDEFINED. When a KEY_TYPED event occurs, getKeyCode( )
returns VK_UNDEFINED.
The MouseEvent Class
There are eight types of mouse events. The MouseEvent class defines the
following integer constants that can be used to identify them:
MouseEvent is a subclass of InputEvent. Here is one of its constructors:
MouseEvent(Component src, int type, long when, int modifiers,
int x, int y, int clicks, boolean triggersPopup)
Here, src is a reference to the component that generated the event. The type
of the event is specified by type. The system time at which the mouse event
occurred is passed in when. The modifiers argument indicates which
modifiers were pressed when a mouse event occurred.
The coordinates of the mouse are passed in x and y. The click count is
passed in clicks. The triggersPopup flag indicates if this event causes a pop-
up menu to appear on this platform.
Two commonly used methods in this class are getX( ) and getY( ). These
return the X and Y coordinates of the mouse within the component when
the event occurred. Their forms are shown here:
int getX( )
int getY( )
Alternatively, you can use the getPoint( ) method to obtain the coordinates
of the mouse. It is shown here:
Point getPoint( )
It returns a Point object that contains the X,Y coordinates in its integer
members: x and y. The translatePoint( ) method changes the location of the
event. Its form is shown here:
void translatePoint(int x, int y)
Here, the arguments x and y are added to the coordinates of the event.
oops@chapter6 Page 5
The getClickCount( ) method obtains the number of mouse clicks for this
event. Its signature is shown here:
int getClickCount( )
The isPopupTrigger( ) method tests if this event causes a pop-up menu to
appear on this platform. Its form is shown here:
boolean isPopupTrigger( )
Also available is the getButton( ) method, shown here:
int getButton( )
It returns a value that represents the button that caused the event. The
return value will be one of these constants defined by MouseEvent:
NOBUTTON BUTTON1 BUTTON2 BUTTON3
The NOBUTTON value indicates that no button was pressed or released.
Java SE 6 added three methods to MouseEvent that obtain the coordinates
of the mouse relative to the screen rather than the component. They are
shown here:
Point getLocationOnScreen( )
int getXOnScreen( )
int getYOnScreen( )
The getLocationOnScreen( ) method returns a Point object that contains
both the X and Y coordinate. The other two methods return the indicated
coordinate.
Event Model
Now that you have learned the theory behind the delegation event model and
have had an overview of its various components, it is time to see it in
practice. Using the delegation event model is actually quite easy. Just follow
these two steps:
1. Implement the appropriate interface in the listener so that it will
receive the type of event desired.
2. Implement code to register and unregister (if necessary) the listener as
a recipient for the event notifications.
Remember that a source may generate several types of events. Each event
must be registered separately. Also, an object may register to receive several
types of events, but it must implement all of the interfaces that are required
to receive these events.
To see how the delegation model works in practice, we will look at examples
that handle two commonly used event generators: the mouse and keyboard.
Handling Mouse Events
To handle mouse events, you must implement the MouseListener and the
MouseMotionListener interfaces. (You may also want to implement
MouseWheelListener, but we won’t be doing so, here.) The following applet
demonstrates the process. It displays the current coordinates of the mouse
in the applet’s status window. Each time a button is pressed, the word
“Down” is displayed at the location of the mouse pointer. Each time the
button is released, the word “Up” is shown. If a button is clicked, the
message “Mouse clicked” is displayed in the upperleft corner of the applet
display area.
As the mouse enters or exits the applet window, a message is displayed in
the upper-left corner of the applet display area. When dragging the mouse, a
* is shown, which tracks with the mouse pointer as it is dragged. Notice that
oops@chapter6 Page 6
the two variables, mouseX and mouseY, store the location of the mouse
when a mouse pressed, released, or dragged event occurs. These coordinates
are then used by paint( ) to display output at the point of these occurrences.
// Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="MouseEvents" width=300 height=100>
</applet>*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
oops@chapter6 Page 7
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}
Sample output from this program is shown here:
Let’s look closely at this example. The MouseEvents class extends Applet
and implements both the MouseListener and MouseMotionListener
interfaces. These two interfaces contain methods that receive and process
the various types of mouse events. Notice that the applet
is both the source and the listener for these events. This works because
Component, which supplies the addMouseListener( ) and
addMouseMotionListener( ) methods, is a superclass of Applet. Being both
the source and the listener for events is a common situation for applets.
Inside init( ), the applet registers itself as a listener for mouse events. This is
done by using addMouseListener( ) and addMouseMotionListener( ),
which, as mentioned, are members of Component. They are shown here:
void addMouseListener(MouseListener ml)
oops@chapter6 Page 8
void addMouseMotionListener(MouseMotionListener mml)
Here, ml is a reference to the object receiving mouse events, and mml is a
reference to the object receiving mouse motion events. In this program, the
same object is used for both. The applet then implements all of the methods
defined by the MouseListener and MouseMotionListener interfaces. These
are the event handlers for the various mouse events. Each method handles
its event and then returns.
Handling Keyboard Events
To handle keyboard events, you use the same general architecture as that
shown in the mouse event example in the preceding section. The difference,
of course, is that you will be implementing the KeyListener interface.
Before looking at an example, it is useful to review how key events are
generated. When a key is pressed, a KEY_PRESSED event is generated. This
results in a call to the keyPressed( ) event handler. When the key is
released, a KEY_RELEASED event is generated and the keyReleased( )
handler is executed. If a character is generated by the keystroke, then a
KEY_TYPED event is sent and the keyTyped( ) handler is invoked. Thus,
each time the user presses a key, at least two and often three events are
generated. If all you care about are actual characters, then you can ignore
the information passed by the keypress and release events.
However, if your program needs to handle special keys, such as the arrow or
function keys, then it must watch for them through the keyPressed( )
handler.
The following program demonstrates keyboard input. It echoes keystrokes to
the applet window and shows the pressed/released status of each key in the
status window.
// Demonstrate the key event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="SimpleKey" width=300 height=100>
</applet>*/
public class SimpleKey extends Applet
implements KeyListener {
String msg = "";
int X = 10, Y = 20; // output coordinates
public void init() {
addKeyListener(this);
}
public void keyPressed(KeyEvent ke) {
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke) {
msg += ke.getKeyChar();
repaint();
}
oops@chapter6 Page 9
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}
Sample output is shown here:
Ad

More Related Content

What's hot (20)

Unit-3 event handling
Unit-3 event handlingUnit-3 event handling
Unit-3 event handling
Amol Gaikwad
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
Ayesha Kanwal
 
tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handling
teach4uin
 
Java gui event
Java gui eventJava gui event
Java gui event
SoftNutx
 
Event handling
Event handlingEvent handling
Event handling
swapnac12
 
Event handling in Java(part 2)
Event handling in Java(part 2)Event handling in Java(part 2)
Event handling in Java(part 2)
RAJITHARAMACHANDRAN1
 
Java Event Handling
Java Event HandlingJava Event Handling
Java Event Handling
Shraddha
 
Events1
Events1Events1
Events1
Nuha Noor
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
OXUS 20
 
Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5
sotlsoc
 
What is Event
What is EventWhat is Event
What is Event
Asmita Prasad
 
GUI (graphical user interface)
GUI (graphical user interface)GUI (graphical user interface)
GUI (graphical user interface)
rishi ram khanal
 
Advance Java Programming (CM5I) 2.Swing
Advance Java Programming (CM5I) 2.SwingAdvance Java Programming (CM5I) 2.Swing
Advance Java Programming (CM5I) 2.Swing
Payal Dungarwal
 
Event handling
Event handlingEvent handling
Event handling
Ravi_Kant_Sahu
 
Chapter11 graphical components
Chapter11 graphical componentsChapter11 graphical components
Chapter11 graphical components
Arifa Fatima
 
Synapseindia dotnet development chapter 14 event-driven programming
Synapseindia dotnet development  chapter 14 event-driven programmingSynapseindia dotnet development  chapter 14 event-driven programming
Synapseindia dotnet development chapter 14 event-driven programming
Synapseindiappsdevelopment
 
Ms Ajax Dom Event Class
Ms Ajax Dom Event ClassMs Ajax Dom Event Class
Ms Ajax Dom Event Class
jason hu 金良胡
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
PRN USM
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Java
yht4ever
 
Android intents
Android intentsAndroid intents
Android intents
Siva Ramakrishna kv
 
Unit-3 event handling
Unit-3 event handlingUnit-3 event handling
Unit-3 event handling
Amol Gaikwad
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
Ayesha Kanwal
 
tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handling
teach4uin
 
Java gui event
Java gui eventJava gui event
Java gui event
SoftNutx
 
Event handling
Event handlingEvent handling
Event handling
swapnac12
 
Java Event Handling
Java Event HandlingJava Event Handling
Java Event Handling
Shraddha
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
OXUS 20
 
Chapter 11.5
Chapter 11.5Chapter 11.5
Chapter 11.5
sotlsoc
 
GUI (graphical user interface)
GUI (graphical user interface)GUI (graphical user interface)
GUI (graphical user interface)
rishi ram khanal
 
Advance Java Programming (CM5I) 2.Swing
Advance Java Programming (CM5I) 2.SwingAdvance Java Programming (CM5I) 2.Swing
Advance Java Programming (CM5I) 2.Swing
Payal Dungarwal
 
Chapter11 graphical components
Chapter11 graphical componentsChapter11 graphical components
Chapter11 graphical components
Arifa Fatima
 
Synapseindia dotnet development chapter 14 event-driven programming
Synapseindia dotnet development  chapter 14 event-driven programmingSynapseindia dotnet development  chapter 14 event-driven programming
Synapseindia dotnet development chapter 14 event-driven programming
Synapseindiappsdevelopment
 
Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
PRN USM
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Java
yht4ever
 

Similar to Dr Jammi Ashok - Introduction to Java Material (OOPs) (20)

Unit 6 Java
Unit 6 JavaUnit 6 Java
Unit 6 Java
arnold 7490
 
Advance java programming- Event handling
Advance java programming- Event handlingAdvance java programming- Event handling
Advance java programming- Event handling
vidyamali4
 
UNIT III Event Handling of the car j.pptx
UNIT III Event Handling of the car j.pptxUNIT III Event Handling of the car j.pptx
UNIT III Event Handling of the car j.pptx
CISCONETWORKING
 
EVENT DRIVEN PROGRAMMING SWING APPLET AWT
EVENT DRIVEN PROGRAMMING SWING APPLET AWTEVENT DRIVEN PROGRAMMING SWING APPLET AWT
EVENT DRIVEN PROGRAMMING SWING APPLET AWT
mohanrajm63
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
sharanyak0721
 
Module 5.pptx
Module 5.pptxModule 5.pptx
Module 5.pptx
VeenaNaik23
 
EventHandling in object oriented programming
EventHandling in object oriented programmingEventHandling in object oriented programming
EventHandling in object oriented programming
Parameshwar Maddela
 
JAVA UNIT 5.pptx jejsjdkkdkdkjjndjfjfkfjfnfn
JAVA UNIT 5.pptx jejsjdkkdkdkjjndjfjfkfjfnfnJAVA UNIT 5.pptx jejsjdkkdkdkjjndjfjfkfjfnfn
JAVA UNIT 5.pptx jejsjdkkdkdkjjndjfjfkfjfnfn
KGowtham16
 
Module3.11.pptx
Module3.11.pptxModule3.11.pptx
Module3.11.pptx
VeenaNaik23
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
usvirat1805
 
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing ButtonsJAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
Jyothishmathi Institute of Technology and Science Karimnagar
 
AJP key event class.pptx
AJP key event class.pptxAJP key event class.pptx
AJP key event class.pptx
komalpatil707727
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
raksharao
 
Advance java for bscit
Advance java for bscitAdvance java for bscit
Advance java for bscit
YogeshDhamke2
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
udithaisur
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
Good657694
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
nehakumari0xf
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
kashyapneha2809
 
CSharp_04_Events-in-C#-introduction-with-examples
CSharp_04_Events-in-C#-introduction-with-examplesCSharp_04_Events-in-C#-introduction-with-examples
CSharp_04_Events-in-C#-introduction-with-examples
Ranjithsingh20
 
event handling new.ppt
event handling new.pptevent handling new.ppt
event handling new.ppt
usama537223
 
Advance java programming- Event handling
Advance java programming- Event handlingAdvance java programming- Event handling
Advance java programming- Event handling
vidyamali4
 
UNIT III Event Handling of the car j.pptx
UNIT III Event Handling of the car j.pptxUNIT III Event Handling of the car j.pptx
UNIT III Event Handling of the car j.pptx
CISCONETWORKING
 
EVENT DRIVEN PROGRAMMING SWING APPLET AWT
EVENT DRIVEN PROGRAMMING SWING APPLET AWTEVENT DRIVEN PROGRAMMING SWING APPLET AWT
EVENT DRIVEN PROGRAMMING SWING APPLET AWT
mohanrajm63
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
sharanyak0721
 
EventHandling in object oriented programming
EventHandling in object oriented programmingEventHandling in object oriented programming
EventHandling in object oriented programming
Parameshwar Maddela
 
JAVA UNIT 5.pptx jejsjdkkdkdkjjndjfjfkfjfnfn
JAVA UNIT 5.pptx jejsjdkkdkdkjjndjfjfkfjfnfnJAVA UNIT 5.pptx jejsjdkkdkdkjjndjfjfkfjfnfn
JAVA UNIT 5.pptx jejsjdkkdkdkjjndjfjfkfjfnfn
KGowtham16
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
usvirat1805
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
raksharao
 
Advance java for bscit
Advance java for bscitAdvance java for bscit
Advance java for bscit
YogeshDhamke2
 
ITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptxITE 1122_ Event Handling.pptx
ITE 1122_ Event Handling.pptx
udithaisur
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
Good657694
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
nehakumari0xf
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
kashyapneha2809
 
CSharp_04_Events-in-C#-introduction-with-examples
CSharp_04_Events-in-C#-introduction-with-examplesCSharp_04_Events-in-C#-introduction-with-examples
CSharp_04_Events-in-C#-introduction-with-examples
Ranjithsingh20
 
event handling new.ppt
event handling new.pptevent handling new.ppt
event handling new.ppt
usama537223
 
Ad

Recently uploaded (20)

railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Ad

Dr Jammi Ashok - Introduction to Java Material (OOPs)

  • 1. oops@chapter6 Page 1 Chapter-6 Event Handling Event handling is fundamental to Java programming because it is integral to the creation of applets and other types of GUI-based programs. Events In the delegation model, an event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse etc. Events may also occur that are not directly caused by interactions with a user interface. Event Sources A source is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event. Each type of event has its own registration method. Here is the general form: public void addTypeListener(TypeListener el) Here, Type is the name of the event, and el is a reference to the event listener. For example, the method that registers a keyboard event listener is called addKeyListener( ). The method that registers a mouse motion listener is called addMouseMotionListener( ). When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known as multicasting the event. Some sources may allow only one listener to register. The general form of such a method is this: public void addTypeListener(TypeListener el) throws java.util.TooManyListenersException Here, Type is the name of the event, and el is a reference to the event listener. When such an event occurs, the registered listener is notified. This is known as unicasting the event. A source must also provide a method that allows a listener to unregister an interest in a specific type of event. The general form of such a method is this: public void removeTypeListener(TypeListener el) Here, Type is the name of the event, and el is a reference to the event listener. For example, to remove a keyboard listener, you would call removeKeyListener( ). Event Listeners Alistener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.
  • 2. oops@chapter6 Page 2 The methods that receive and process events are defined in a set of interfaces found in java.awt.event. Event Classes The classes that represent events are at the core of Java’s event handling mechanism. Thus, a discussion of event handling must begin with the event classes. It is important to understand, however, that Java defines several types of events and that not all event classes can be discussed in this chapter. The most widely used events are those defined by the AWT and those defined by Swing. This chapter focuses on the AWT events. (Most of these events also apply to Swing.) At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all events. Its one constructor is shown here: EventObject(Object src) Here, src is the object that generates this event. EventObject contains two methods: getSource( ) and toString( ). The getSource( ) method returns the source of the event. Its general form is shown here: Object getSource( ) As expected, toString( ) returns the string equivalent of the event. The class AWTEvent, defined within the java.awt package, is a subclass of EventObject. It is the superclass (either directly or indirectly) of all AWT- based events used by the delegation event model. Its getID( ) method can be used to determine the type of the event. The signature of this method is shown here: int getID( ) At this point, it is important to know only that all of the other classes discussed in this section are subclasses of AWTEvent. To summarize: • EventObject is a superclass of all events. • AWTEvent is a superclass of all AWT events that are handled by the delegation event model. The package java.awt.event defines many types of events that are generated by various user interface elements.
  • 3. oops@chapter6 Page 3 The ActionEvent Class An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item is selected. The ActionEvent class defines four integer constants that can be used to identify any modifiers associated with an action event The KeyEvent Class AKeyEvent is generated when keyboard input occurs. There are three types of key events, which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first two events are generated when any key is pressed or released. The last event occurs only when a character is generated. Remember, not all keyp presses result in characters. For example, pressing SHIFT does not generate a character. There are many other integer constants that are defined by KeyEvent. For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers and letters. Here are some others: The VK constants specify virtual key codes and are independent of any modifiers, such as control, shift, or alt. KeyEvent is a subclass of InputEvent. Here is one of its constructors: KeyEvent(Component src, int type, long when, int modifiers, int code, char ch) Here, src is a reference to the component that generated the event. The type of the event is specified by type. The system time at which the key was pressed is passed in when. The modifiers argument indicates which modifiers were pressed when this key event occurred. The virtual key code, such as VK_UP, VK_A, and so forth, is passed in code. The character
  • 4. oops@chapter6 Page 4 equivalent (if one exists) is passed in ch. If no valid character exists, then ch contains CHAR_UNDEFINED. For KEY_TYPED events, code will contain VK_UNDEFINED. The KeyEvent class defines several methods, but the most commonly used ones are getKeyChar( ), which returns the character that was entered, and getKeyCode( ), which returns the key code. Their general forms are shown here: char getKeyChar( ) int getKeyCode( ) If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED. When a KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED. The MouseEvent Class There are eight types of mouse events. The MouseEvent class defines the following integer constants that can be used to identify them: MouseEvent is a subclass of InputEvent. Here is one of its constructors: MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup) Here, src is a reference to the component that generated the event. The type of the event is specified by type. The system time at which the mouse event occurred is passed in when. The modifiers argument indicates which modifiers were pressed when a mouse event occurred. The coordinates of the mouse are passed in x and y. The click count is passed in clicks. The triggersPopup flag indicates if this event causes a pop- up menu to appear on this platform. Two commonly used methods in this class are getX( ) and getY( ). These return the X and Y coordinates of the mouse within the component when the event occurred. Their forms are shown here: int getX( ) int getY( ) Alternatively, you can use the getPoint( ) method to obtain the coordinates of the mouse. It is shown here: Point getPoint( ) It returns a Point object that contains the X,Y coordinates in its integer members: x and y. The translatePoint( ) method changes the location of the event. Its form is shown here: void translatePoint(int x, int y) Here, the arguments x and y are added to the coordinates of the event.
  • 5. oops@chapter6 Page 5 The getClickCount( ) method obtains the number of mouse clicks for this event. Its signature is shown here: int getClickCount( ) The isPopupTrigger( ) method tests if this event causes a pop-up menu to appear on this platform. Its form is shown here: boolean isPopupTrigger( ) Also available is the getButton( ) method, shown here: int getButton( ) It returns a value that represents the button that caused the event. The return value will be one of these constants defined by MouseEvent: NOBUTTON BUTTON1 BUTTON2 BUTTON3 The NOBUTTON value indicates that no button was pressed or released. Java SE 6 added three methods to MouseEvent that obtain the coordinates of the mouse relative to the screen rather than the component. They are shown here: Point getLocationOnScreen( ) int getXOnScreen( ) int getYOnScreen( ) The getLocationOnScreen( ) method returns a Point object that contains both the X and Y coordinate. The other two methods return the indicated coordinate. Event Model Now that you have learned the theory behind the delegation event model and have had an overview of its various components, it is time to see it in practice. Using the delegation event model is actually quite easy. Just follow these two steps: 1. Implement the appropriate interface in the listener so that it will receive the type of event desired. 2. Implement code to register and unregister (if necessary) the listener as a recipient for the event notifications. Remember that a source may generate several types of events. Each event must be registered separately. Also, an object may register to receive several types of events, but it must implement all of the interfaces that are required to receive these events. To see how the delegation model works in practice, we will look at examples that handle two commonly used event generators: the mouse and keyboard. Handling Mouse Events To handle mouse events, you must implement the MouseListener and the MouseMotionListener interfaces. (You may also want to implement MouseWheelListener, but we won’t be doing so, here.) The following applet demonstrates the process. It displays the current coordinates of the mouse in the applet’s status window. Each time a button is pressed, the word “Down” is displayed at the location of the mouse pointer. Each time the button is released, the word “Up” is shown. If a button is clicked, the message “Mouse clicked” is displayed in the upperleft corner of the applet display area. As the mouse enters or exits the applet window, a message is displayed in the upper-left corner of the applet display area. When dragging the mouse, a * is shown, which tracks with the mouse pointer as it is dragged. Notice that
  • 6. oops@chapter6 Page 6 the two variables, mouseX and mouseY, store the location of the mouse when a mouse pressed, released, or dragged event occurs. These coordinates are then used by paint( ) to display output at the point of these occurrences. // Demonstrate the mouse event handlers. import java.awt.*; import java.awt.event.*; import java.applet.*; /*<applet code="MouseEvents" width=300 height=100> </applet>*/ public class MouseEvents extends Applet implements MouseListener, MouseMotionListener { String msg = ""; int mouseX = 0, mouseY = 0; // coordinates of mouse public void init() { addMouseListener(this); addMouseMotionListener(this); } // Handle mouse clicked. public void mouseClicked(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse clicked."; repaint(); } // Handle mouse entered. public void mouseEntered(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse entered."; repaint(); } // Handle mouse exited. public void mouseExited(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse exited."; repaint(); } // Handle button pressed. public void mousePressed(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "Down"; repaint(); }
  • 7. oops@chapter6 Page 7 // Handle button released. public void mouseReleased(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "Up"; repaint(); } // Handle mouse dragged. public void mouseDragged(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "*"; showStatus("Dragging mouse at " + mouseX + ", " + mouseY); repaint(); } // Handle mouse moved. public void mouseMoved(MouseEvent me) { // show status showStatus("Moving mouse at " + me.getX() + ", " + me.getY()); } // Display msg in applet window at current X,Y location. public void paint(Graphics g) { g.drawString(msg, mouseX, mouseY); } } Sample output from this program is shown here: Let’s look closely at this example. The MouseEvents class extends Applet and implements both the MouseListener and MouseMotionListener interfaces. These two interfaces contain methods that receive and process the various types of mouse events. Notice that the applet is both the source and the listener for these events. This works because Component, which supplies the addMouseListener( ) and addMouseMotionListener( ) methods, is a superclass of Applet. Being both the source and the listener for events is a common situation for applets. Inside init( ), the applet registers itself as a listener for mouse events. This is done by using addMouseListener( ) and addMouseMotionListener( ), which, as mentioned, are members of Component. They are shown here: void addMouseListener(MouseListener ml)
  • 8. oops@chapter6 Page 8 void addMouseMotionListener(MouseMotionListener mml) Here, ml is a reference to the object receiving mouse events, and mml is a reference to the object receiving mouse motion events. In this program, the same object is used for both. The applet then implements all of the methods defined by the MouseListener and MouseMotionListener interfaces. These are the event handlers for the various mouse events. Each method handles its event and then returns. Handling Keyboard Events To handle keyboard events, you use the same general architecture as that shown in the mouse event example in the preceding section. The difference, of course, is that you will be implementing the KeyListener interface. Before looking at an example, it is useful to review how key events are generated. When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed( ) event handler. When the key is released, a KEY_RELEASED event is generated and the keyReleased( ) handler is executed. If a character is generated by the keystroke, then a KEY_TYPED event is sent and the keyTyped( ) handler is invoked. Thus, each time the user presses a key, at least two and often three events are generated. If all you care about are actual characters, then you can ignore the information passed by the keypress and release events. However, if your program needs to handle special keys, such as the arrow or function keys, then it must watch for them through the keyPressed( ) handler. The following program demonstrates keyboard input. It echoes keystrokes to the applet window and shows the pressed/released status of each key in the status window. // Demonstrate the key event handlers. import java.awt.*; import java.awt.event.*; import java.applet.*; /*<applet code="SimpleKey" width=300 height=100> </applet>*/ public class SimpleKey extends Applet implements KeyListener { String msg = ""; int X = 10, Y = 20; // output coordinates public void init() { addKeyListener(this); } public void keyPressed(KeyEvent ke) { showStatus("Key Down"); } public void keyReleased(KeyEvent ke) { showStatus("Key Up"); } public void keyTyped(KeyEvent ke) { msg += ke.getKeyChar(); repaint(); }
  • 9. oops@chapter6 Page 9 // Display keystrokes. public void paint(Graphics g) { g.drawString(msg, X, Y); } } Sample output is shown here: