0% found this document useful (0 votes)
11 views88 pages

Event Handling

Java programming

Uploaded by

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

Event Handling

Java programming

Uploaded by

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

Advance Java Programming(22517)

Unit III
Event Handling

1
Topics and Sub-Topics

2
Outcomes

3
Event Handling
 Any program that uses GUI (graphical user interface) such as Java application

written for windows, is event driven.

 Event describes the change of state of any object.

 Events are generated as result of user interaction with the graphical user

interface components.

 Changing the state of an object is known as an event.

 For example: clicking on a button, Entering a character in Textbox, moving

the mouse, selecting an item from list, scrolling the page, etc.

 The java.awt.event package provides many event classes and Listener

4 interfaces for event handling.


Delegation Event Model

 The modern approach to handling events is based on the

delegation event model.

 The delegation event model defines a standard and

consistent mechanism to generate and process events.

 Source -> generates event ->send to listener

 listener waits to receive ->after received event->process it

and returns
5
Delegation Event Model
 Advantage: Application logic for processing events are separated from GUI that

generates events

 A user interface element is able to “delegate” the processing of an event to a

separate piece of code.

 In this model, listener must register with source in order to receive an event

notification.

 Notification are send only to listener that want to receive them

 There are mainly three parts in delegation event model.

 Events.

 Event sources.

 Event Listeners.

6
7
Events
 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.

8
Events
 Events may also occur that are not directly caused by

interactions with a user interface.

 For example, an event may be generated when a timer

expires, a counter exceeds a value, software or hardware


failure occurs, or an operation is completed.

 We are free to define events that are appropriate for an

application.

9
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.

 A source must register listeners in order for the listeners

to receive notifications about a specific type of event.

 Each type of event has its own registration method.

10
Event Sources
 Here is the general form to register listeners:

public void addTypeListener(TypeListener el)


 For example: b.addActionListener(this);

 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.
11
Event Sources
 The general form of unregister listener method is this:

public void removeTypeListener(TypeListener el)

 Here, type is an object that is notified when an event listener.

 For example, to remove a keyboard listener, you would call

removeKeyListener()

 The methods that add or remove listeners are provided by the

source that generates events.

 For Example, the Component class provides methods to add

and remove keyboard and mouse event listeners.


12
Event Listeners
 A listener 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.
 The method that receive and process events are defined in a set of
interfaces found in java.awt.event
 For example, the MouseMotionListener interface defines two methods to
receive notifications when the mouse is dragged or moved.
 Any object may receive and process one or both of these events if it
13 provides an implementation of this interface.
Event Classes

 At the root of the Java event class hierarchy is EventObject,

which is in java.util

 It is the superclass for all events.

 Constructor: EventObject(Object source)

 Methods:

1. Object getSource( ) : returns the source of the event.

2. String toString( ): returns the string equivalent of the event.


14
Event Classes

 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 used to determine the type of the event.

 Syntax: int getID()

15
16
Important Event Classes
and Interface

17
Event Classes Description Listener Interface
ActionEvent generated when button is pressed, menu-item is selected, ActionListener
list-item is double clicked

MouseEvent generated when mouse is dragged, moved, clicked, pressed MouseListener


or released and also when it enters or exit a component

KeyEvent generated when input is received from keyboard KeyListener

ItemEvent generated when check-box or list item is clicked ItemListener

TextEvent generated when value of textarea or textfield is changed TextListener

MouseWheelEvent generated when mouse wheel is moved MouseWheelListener

WindowEvent generated when window is activated, deactivated, WindowListener


deiconified, iconified, opened or closed
ComponentEven generated when component is hidden, moved, resized or set ComponentEventListe
visible ner
t
ContainerEvent generated when component is added or removed from ContainerListener
container
AdjustmentEven generated when scroll bar is manipulated AdjustmentListener
t
18
FocusEvent generated when component gains or loses keyboard focus FocusListener
 Steps to handle events:

 Implement appropriate interface in the class.

 Register the component with the listener.

19
Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For example:
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}

20
ActionEvent
 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 are used to identify any
modifiers associated with an action event:

 public static final int ALT_MASK The alt modifier.

 An indicator that the alt key was held down during the event.

 public static final int SHIFT_MASK The shift modifier.

 An indicator that the shift key was held down during the event.

 public static final int CTRL_MASK The control modifier.

 An indicator that control key was held down during the event.

 public static final int META_MASK The meta modifier.

 An indicator that the meta key was held down during the event. (The Meta key is

a modifier key on certain keyboards)


Constructor-1
public ActionEvent(Object source,int id,String command)

 Constructs an ActionEvent object with modifier keys.


 Parameters: source - the object that originated the event

 id - an integer that identifies the event

 command - a string that may specify a command (possibly


one of several) associated with the event

22
Constructor-2
public
ActionEvent(Object source,int id,String command,int modifiers)

 Constructs an ActionEvent object with modifier keys.


 Parameters: source - the object that originated the event

 id - an integer that identifies the event

 command - a string that may specify a command (possibly


one of several) associated with the event

 modifiers - the modifier keys held down during this action

23
Constructor-3
public
ActionEvent(Object source,int id,String command,long when,
int modifiers)

Constructs an ActionEvent object with the specified modifier keys and


timestamp.
Parameters: source - the object that originated the event

id - an integer that identifies the event

command - a string that may specify a command (possibly one of


several) associated with the event

when - the time the event occurred

24
modifiers - the modifier keys held down during this action
Methods
 public String getActionCommand()
 Returns the command string associated with this action.

 public long getWhen()


 Returns the timestamp of when this event occurred.

 int getModifiers()
 Returns the modifier keys held down during this action event.

 String paramString()
 Returns a parameter string identifying this action event.

25
ActionListener Interface

 This interface defines the actionPerformed() method that is

invoked when an action event occurs.

 Its general form is shown here:

 void actionPerformed(ActionEvent ae)

26
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/* <applet code="ActionEventExample" width=200 height=200>


</applet> */

public class ActionEventExample extends Applet implements ActionListener


{
String actionMessage="";
public void init()
{
Button Button1 = new Button("Ok");
Button Button2 = new Button("Cancel");
add(Button1);
add(Button2);
Button1.addActionListener(this); //Listener Registered
Button2.addActionListener(this); //Listener Registered
}
27
public void paint(Graphics g)
{
g.drawString(actionMessage,10,50);
}

public void actionPerformed(ActionEvent ae)


{

String action = ae.getActionCommand();

if(action.equals("Ok"))
actionMessage = "Ok Button Pressed";
else if(action.equals("Cancel"))
actionMessage = "Cancel Button Pressed";

repaint();
}
}

28
29
AdjustmentEvent
 An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events.

 The AdjustmentEvent class defines integer constants that can be used to identify them.

 BLOCK_DECREMENT

 The user clicked inside the scroll bar to decrease its value.

 BLOCK_INCREMENT

 The user clicked inside the scroll bar to increase its value.

 TRACK

 The slider was dragged.

 UNIT_DECREMENT

 The button at the end of the scroll bar was clicked to decrease its value.

 UNIT_INCREMENT

 The button at the end of the scroll bar was clicked to increase its value.

30
 ADJUSTMENT_VALUE_CHANGED : indicates that a change has occured
AdjustmentEvent
 Constructor: AdjustmentEvent(Adjustable src, int id, int
type, int data)

 src: object that generates event

 id: equals ADJUSTMENT_VALUE_CHANGED

 type: type of the event

 data: its associated data

 getAdjustable() methods returns the object that generates

the event
Adjustable getAdjustable()
31
AdjustmentEvent
 The type of the adjustment event may be obtained by the

getAdjustmentType( ) method. It returns one of the constants


defined by AdjustmentEvent.

 The general form is shown here:

int getAdjustmentType( )

 The amount of the adjustment can be obtained from the

getValue( ) method, shown here:


int getValue( )

 For example, when a scroll bar is manipulated, this method

returns the value represented by that change.


32
AdjustmentListener Interface

 This interface defines the adjustmentValueChanged( ) method

that is invoked when an adjustment event occurs.

 Its general form is shown here:

void adjustmentValueChanged(AdjustmentEvent ae)

33
ComponentEvent class
 A low-level event which indicates that a component moved,
changed size, or changed visibility.
 This class has following constants to identify the four types of component events.

 public static final int COMPONENT_MOVED

 This event indicates that the component's position changed.

 public static final int COMPONENT_RESIZED

 This event indicates that the component's size changed.

 public static final int COMPONENT_SHOWN

 This event indicates that the component was made visible.

 public static final int COMPONENT_HIDDEN

 This event indicates that the component was become invisible.


34
 Constructor:

public ComponentEvent(Component source, int id)


 Parameters:
 source - the Component that originated the event

 id - an integer indicating the type of event

 ComponentEvent is superclass either directly or indirectly of


ContainerEvent, FocusEvent, KeyEvent, MouseEvent and
WindowEvent.
 Method: Component getComponent()
 Returns the creator of the event.

 the Component object that originated the event, or null if the object is not a
Component.

35
ComponentLIstener interface

 The listener interface for receiving component events.

 void componentResized(ComponentEvent e)

 Invoked when the component's size changes.

 void componentMoved(ComponentEvent e)

 Invoked when the component's position changes

 void componentShown(ComponentEvent e)

 Invoked when the component has been made visible.

 void componentHidden(ComponentEvent e)

 Invoked when the component has been made invisible.


36
ContainerEvent class
 A low-level event which indicates that a container's
contents changed because a component was added or
removed
 There are two types of container events and following constants
are used to identify them.
 public static final int COMPONENT_ADDED

 This event indicates that a component was added to the container.

 public static final int COMPONENT_REMOVED

 This event indicates that a component was removed from the container.

37
 Constructor:

public ContainerEvent(Component source, int id, Component child)

 Parameters:

 source - the Component object (container) that originated the event

 id - an integer indicating the type of event

 child - the component that was added or removed

38
 Methods:

 public Container getContainer()

 Returns the originator of the event.

 Returns the Container object that originated the event, or null if the

object is not a Container.

 public Component getChild()

 Returns the component that was affected by the event.

 Returns the Component object that was added or removed.

39
ContainerListener interface

 The listener interface for receiving container events.

 void componentAdded(ContainerEvent e)

 Invoked when a component has been added to the container.

 void componentRemoved (ContainerEvent e)

 Invoked when a component has been removed from the container.

40
FocusEvent class

 A low-level event which indicates that a Component has


gained or lost the input focus.
 This class has following constants.

 public static final int FOCUS_GAINED

 This event indicates that the Component is now the focus owner.

 public static final int FOCUS_LOST

 This event indicates that the Component is no longer the focus


owner.
41
Constructors
public FocusEvent(Component source,int id,boolean temporary, Component opposite)

 source - the Component that originated the event

 id - FOCUS_GAINED or FOCUS_LOST

 temporary - true if the focus change is temporary; false otherwise

 opposite - the other Component involved in the focus change, or null

public FocusEvent(Component source,int id,boolean temporary)

 id - an integer indicating the type of event

 temporary - true if the focus change is temporary; false otherwise.

public FocusEvent(Component source,int id)

 source - the Component that originated the event

 id - an integer indicating the type of event


42
 Methods

 public boolean isTemporary()

 Identifies the focus change event as temporary or permanent.

 Returns: true if the focus change is temporary; false otherwise

 public Component getOppositeComponent()

 Returns the other Component involved in this focus change.

43
FocusListener interface

 void focusGained(FocusEvent e)

 Invoked when a component gains the keyboard focus.

 void focusLost(FocusEvent e)

 Invoked when a component loses the keyboard focus.

44
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class FocusListenerExample extends JFrame implements FocusListener


{
Button b1,b2;

public FocusListenerExample()
{
b1=new Button ("First");
b2=new Button ("Second");
add(b1,BorderLayout.SOUTH);
add(b2,BorderLayout.NORTH);
b1.addFocusListener(this);
b2.addFocusListener(this);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
45
public void focusGained(FocusEvent fe) //method of focuslistener
{
if(fe.getSource()==b1)
System.out.println(b1.getLabel()+"gained");
if(fe.getSource()==b2)
System.out.println(b2.getLabel()+"gained");
if(fe.isTemporary())
System.out.println("Temporary Focus");
}
public void focusLost(FocusEvent fe) //in focusevent "getID()"is a method
{
if(fe.getSource()==b1)
System.out.println(b1.getLabel()+"lost");
if(fe.getSource()==b2)
System.out.println(b2.getLabel()+"lost");
}
public static void main(String a[])
{
new FocusListenerExample();
}
46 }
47
InputEvent class
 It is abstract class and is a subclass of ComponentEvent class
 Its subclasses are KeyEvent and and MouseEvent
 This class has following constants.
 ALT_MASK
 CTRL_MASK
 META_MASK
 ALT_GRAPH_MASK
 SHIFT_MASK
 BUTTON1_MASK
 BUTTON2_MASK
 BUTTON3_MASK
48
InputEvent class
 Methods:

 boolean isAltDown()

 boolean isAltGraphDown()

 boolean isControlDown()

 boolean isMetaDown()

 boolean isShiftDown()

 int getModifiers()

49
ItemEvent class

 A semantic event which indicates that an item was selected or


deselected.
 This high-level event is generated by an ItemSelectable object (such
as a List) when an item is selected or deselected by the user.
 This class has following constants.
 public static final int SELECTED
 This state-change value indicates that an item was selected.
 public static final int DESELECTED
 This state-change-value indicates that a selected item was deselected

50
 public ItemEvent (ItemSelectable source, int id,
Object item, int stateChange)
 Constructs an ItemEvent object.
 Parameters:
 source - the ItemSelectable object that originated the event
 id - an integer that identifies the event type
 item - an object -- the item affected by the event
 stateChange - an integer that indicates whether the item was selected
or deselected

51
Methods of ItemEvent Class
 public ItemSelectable getItemSelectable()
 Returns the creator of the event.
 Returns: the ItemSelectable object that originated the event.
 public Object getItem()
 Returns the item affected by the event.
 Returns: the item (object) that was affected by the event.
 public int getStateChange()
 Returns the type of state change (selected or deselected).
 Returns: an integer that indicates whether the item was selected or
deselected

52
ItemListener interface

 The listener interface for receiving item events.

 void itemStateChanged(ItemEvent e)

 Invoked when an item has been selected or deselected by the user.

 The code written for this method performs the operations that need

to occur when an item is selected (or deselected).

53
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/* <applet code="ItemListenerExample" width=200 height=200>


</applet> */

public class ItemListenerExample extends Applet implements ItemListener


{

Checkbox java = null;


Checkbox vb = null;
Checkbox c = null;

54
public void init()
{
java = new Checkbox("Java");
vb = new Checkbox("Visual Basic");
c = new Checkbox("C");

add(java);
add(vb);
add(c);

java.addItemListener(this);
vb.addItemListener(this);
c.addItemListener(this);
}
public void paint(Graphics g)
{
g.drawString("Java: " + java.getState(),10,80);
g.drawString("VB: " + vb.getState(), 10, 100);
g.drawString("C: " + c.getState(), 10, 120);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
55 }
}
56
KeyEvent class
 An event which indicates that a keystroke occurred in a component.

 This class has following constant.

 public static final int KEY_PRESSED

 This event is generated when a key is pushed down.

 public static final int KEY_RELEASED

 This event is generated when a key is let up.

 public static final int KEY_TYPED

 This event is generated when a character is entered. In the simplest case, it is

produced by a single key press. Often, however, characters are produced by series
of key presses, and the mapping from key pressed events to key typed events may

be many-to-one or many-to-many.
57
 There are many other integer constants that are defined
by KeyEvent. For example
 VK_0 to VK_9

 VK_A to VK_Z define the ASCII equivalents of the numbers


and letters.

 Here are some others:

 VK_ENTER, VK_ESCAPE, VK_CANCEL, VK_UP, VK_DOWN,


VK_LEFT, VK_RIGHT, VK_PAGE_DOWN,VK_PAGE_UP,
VK_SHIFT, VK_ALT, VK_CONTROL

 The VK constants specify virtual key codes and are

58
independent of any modifiers, such as control, shift, or alt.
Methods of KeyEvent class

 public int getKeyCode()

 Returns the integer keyCode associated with the key in this event.

 Returns: the integer code for an actual key on the keyboard.

 public char getKeyChar()

 Returns the character associated with the key in this event.

 For example, the KEY_TYPED event for shift + "a" returns the value for "A".

• boolean isActionKey()

 Returns true if the key firing the event is an action key. Examples of action keys

include Page Up, Caps Lock, the arrow and function keys.
59
KeyListener Interface
 Key events indicate when the user is typing at the keyboard.

 Key events are fired by the component with the keyboard focus

when the user presses or releases keyboard keys.

 Notifications are sent about two basic kinds of key events:

 The typing of a Unicode character

 The pressing or releasing of a key on the keyboard

60
 The first kind of event is called a key-typed event.

 To know when the user types a Unicode character ? whether

by pressing one key such as 'a' or by pressing several keys in

sequence ?

 The second kind is either a key-pressed or key-released event.

 To know when the user presses the F1 key, or whether the user

pressed the '3' key on the number pad, you handle key-pressed

events.
61
Methods of KeyListener Interface
Method Purpose

Called just after the user types a Unicode


keyTyped(KeyEvent)
character into the listened-to component.

Called just after the user presses a key while


keyPressed(KeyEvent)
the listened-to component has the focus.

Called just after the user releases a key


keyReleased(KeyEvent) while the listened-to component has the
focus.
62
import java.awt.*;
import java.awt.event.*;
import javax.swing.JApplet;
public class EventDemo6 extends JApplet implements KeyListener
{
String event; // description of keyboard event
public void init() // set up UI
{
setLayout(new FlowLayout());
event = ""; addKeyListener(this); // listen for keyboard events
setFocusable(true); // force applet to receive KeyEvent
}
public void paint(Graphics g) // draw message to applet
{
super.paint(g);
g.drawRect(0, 0, getWidth(), getHeight()); // show bounds of applet
g.drawString(event, 10, 50);
}

63
public void keyPressed(KeyEvent e) // handle key presses
{
event = e.getKeyChar() + " pressed"; repaint();
}
public void keyReleased(KeyEvent e) // handle key releases
{
event = e.getKeyChar() + " released"; repaint();
}
public void keyTyped(KeyEvent e) // handle typing on applet
{
event = e.getKeyChar() + " typed"; repaint();
}
}

64
TextEvent class

 A semantic event which indicates that an object's text changed.

 This high-level event is generated by an object (such as a TextComponent) when its

text changes.

 Constructor: public TextEvent(Object source,int id)

 Constructs a TextEvent object.

 Parameters:

 source - the (TextComponent) object that originated the event

 id - an integer that identifies the event type

65
TextListener interface

 The listener interface for receiving text events.

void textValueChanged(TextEvent te)

 Invoked when the value of the text has changed.

 The code written for this method performs the operations that

need to occur when text changes.

66
WindowEvent class
 A low-level event indicates that a window has changed its status.

 This event is generated by a Window object when it is opened, closed, activated,

deactivated, iconified, or deiconified, or when focus is transferred into or


out of the Window.

 Constant defined in WindowEvent Class

WINDOW_ACTIVATED WINDOW_CLOSED
WINDOW_CLOSING WINDOW_DEACTIVATED
WINDOW_DEICONIFIED WINDOW_GAINED_FOCUS
WINDOW_ICONIFIED WINDOW_LOST_FOCUS

67
WINDOW_OPENED WINDOW_STATE_CHANGED
Constructors
 public WindowEvent(Window source,int id)

 Constructs a WindowEvent object.

 source - the Window object that originated the event

 id - an integer indicating the type of event

 public WindowEvent(Window source,int id,Window opposite,int oldState, int newState)

 Note that passing in an invalid id results in unspecified behavior. This method throws an

IllegalArgumentException if source is null.

 source - the Window object that originated the event

 id - an integer indicating the type of event.

 opposite - the other window involved in the focus or activation change, or null

 oldState - previous state of the window for window state change event

 newState - new state of the window for window state change event
68
Method

 The most commonly used method in this class is getWindow()

 public Window getWindow()


 Returns the originator of the event.

 Returns: the Window object that originated the event

 public Window getOppositeWindow()


 Returns the opposite window.

 public int getOldState()


 Returns the previous window state.

 public int getNewState()


 Returns the current state of the window.
69
WindowListener interface
 void windowOpened(WindowEvent e)
 Invoked the first time a window is made visible.

 void windowClosing(WindowEvent e)
 Invoked when the user attempts to close the window from the window's system menu.

 void windowClosed(WindowEvent e)
 Invoked when a window has been closed as the result of calling dispose on the window

 void windowIconified(WindowEvent e)
 Invoked when a window is changed from a normal to a minimized state. For many platforms, a minimized
window is displayed as the icon specified in the window's iconImage property.
 void windowDeiconified(WindowEvent e)
 Invoked when a window is changed from a minimized to a normal state.

 void windowActivated(WindowEvent e)
 Invoked when the Window is set to be the active Window.

 void windowDeactivated(WindowEvent e)
 Invoked when a Window is no longer the active Window.
70
WindowFocusListener interface
 The listener interface for receiving WindowEvents, including
WINDOW_GAINED_FOCUS and WINDOW_LOST_FOCUS events.

 void windowGainedFocus(WindowEvent e)

 Invoked when the Window is set to be the focused Window, which

means that the Window, or one of its subcomponents, will receive


keyboard events.

 void windowLostFocus(WindowEvent e)

 Invoked when the Window is no longer the focused Window, which

means that keyboard events will no longer be delivered to the Window


71 or any of its subcomponents.
MouseEvent class
• This event indicates a mouse action occurred in a component.
• This low-level event is generated by a component object for
Mouse Events and Mouse motion events.
• This class defines following constants:
static int BUTTON1 static int BUTTON2
static int BUTTON3 static int MOUSE_CLICKED
static int MOUSE_DRAGGED static int MOUSE_ENTERED
static int MOUSE_EXITED static int MOUSE_MOVED
static int MOUSE_PRESSED static int MOUSE_RELEASED
static int MOUSE_WHEEL
Constructor
MouseEvent(Component source, int id, long when, int
modifiers, int x, int y, int clickCount, boolean popupTrigger)
source- source component,
id- type of event,
when- system time at mouse event occurred
modifiers-to know what modifiers were pressed after event was occurred,
x & y- coordinates of the mouse ,
clickCount- click count
popupTrigger- whether popup menu appeared
73
Method Purpose

Returns the number of quick, consecutive


int getClickCount() clicks the user has made (including this event).
For example, returns 2 for a double click.
Returns which mouse button, if any, has a
changed state. One of the following constants
int getButton() is returned: NOBUTTON, BUTTON1,
BUTTON2, or BUTTON3.
Return the (x,y) position at which the event
int getX()
occurred, relative to the component that fired
int getY() the event.

Returns the x,y position of the event rlative to


Point getPoint() the source component.
74
MouseListener Interface
 Mouse events notify when the user uses the mouse (or similar

input device) to interact with a component.

 Mouse events occur when the cursor enters or exits a

component's onscreen area and when the user presses or

releases one of the mouse buttons.

75
Methods of MouseListener Interface
Method Purpose
Called just after the user clicks the listened-to
mouseClicked(MouseEvent)
component.
Called just after the cursor enters the bounds
mouseEntered(MouseEvent)
of the listened-to component.
Called just after the cursor exits the bounds of
mouseExited(MouseEvent)
the listened-to component.
Called just after the user presses a mouse
mousePressed(MouseEvent)
button while the cursor is over the listened-to
component.
Called just after the user releases a mouse
mouseReleased(MouseEvent) button after a mouse press over the listened-to
76 component.
MouseMotionListener Interface
 Mouse-motion events notify when the user uses the mouse (or a similar

input device) to move the onscreen cursor.

 If an application requires the detection of both mouse events and mouse-

motion events, use the MouseInputAdapter class.

 It implements the MouseInputListener a convenient interface that implements

both the MouseListener and MouseMotionListener interfaces.

77
Methods of MouseMotionListener Interface

Method Purpose

Called in response to the user moving the mouse while


holding a mouse button down. This event is fired by
the component that fired the most recent mouse-
mouseDragged(MouseEvent)
pressed event, even if the cursor is no longer over that
component.

Called in response to the user moving the mouse with


no mouse buttons pressed. This event is fired by the
mouseMoved(MouseEvent)
component that's currently under the cursor.

78
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseEventDemo extends JApplet implements MouseListener


{
private int x; // x coordinate of mouse event
private int y; // y coordinate of mouse event
private String event; // description of mouse event

public void init() // set up GUI


{
setLayout(new FlowLayout());

addMouseListener(this); // listen for mouse events

x = -1; // set x negative for no initial message


}

79
public void paint(Graphics g) // draw message to screen
{
super.paint(g);

g.drawRect(0, 0, getWidth(), getHeight()); // show bounds of applet

if(x != - 1) // display event during repainting only


{
g.drawString("Mouse event " + event +
" at (" + x + ", " + y + ")",
10, 50);
}
}

public void mousePressed(MouseEvent e) // save coordinates of presses


{
x = e.getX();
y = e.getY();
event = "press";

repaint();
80
}
public void mouseClicked(MouseEvent e) // save coordinates of clicks
{
x = e.getX();
y = e.getY();
event = "click";

repaint();
}

public void mouseReleased(MouseEvent e) // save coordinates of releases


{
x = e.getX();
y = e.getY();
event = "release";

repaint();
}

81
public void mouseEntered(MouseEvent e) // save coordinates when mouse enters applet
{
x = e.getX();
y = e.getY();
event = "enter";

repaint();
}

public void mouseExited(MouseEvent e) // save coordinates when mouse leaves applet


{
x = e.getX();
y = e.getY();
event = "exit";

repaint();
}
}
/*<applet code=MouseEventDemo height=300 width=300></applet>*/

82
Summary of Event Classes
& Listeners

83
84
85
86
87
Adapter Classes
 Java provides a special feature, called an adapter class that can simplify the
creation of event handlers in certain situations.
 An adapter class provides an empty implementation of all methods in an
event listener interface.
 Adapter classes are useful when we want to receive and process only
some of the events that are handled by a particular event listener interface.
 We can define a new class to act as an event listener by extending one of the
adapter classes and implementing only those events in which we are
interested.
 For example, the MouseMotionAdapter class has two methods,
mouseDragged( ) and mouseMoved( ).

88

You might also like