Unit 3
Unit 3
What is an Event?
Change in the state of an object is known as event i.e. event describes the change in state of
source. Events are generated as result of user interaction with the graphical user interface
components.
For example, clicking on a button, moving the mouse, entering a character through keyboard,
selecting an item from list, scrolling the page are the activities that causes an event to happen.
The event object is used to carry the required information about the state change.
Types of Event
The events can be broadly classified into two categories:
Foreground Events - Those events which require the direct interaction of user. They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from list, scrolling the page etc.
Background Events - Events that don’t require interactions of users to generate are
known as background events. Operating system interrupts, hardware or software failure, timer
expires, an operation completion are the example of background events.
The Delegation Event Model has the following key participants namely:
Source - 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.
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( ).
Listener - It is also known as event handler. Event listeners are objects that are notified as soon
as a specific event occurs. Event listeners must define the methods to process the notification.
Listener is responsible for generating response to an event. From java implementation point of
view the listener is also an object. Listener waits until it receives an event. Once the event is
received , the listener process the event an then returns.
Class constructors :
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
modifiers - The modifier keys down during event (shift, ctrl, alt, meta). Passing negative
parameter is not recommended. Zero value means that no modifiers were passed.
when - A long that gives the time the event occurred.
Methods
public String getActionCommand()
Returns the string identifying the command for this event.
public long getWhen()
Returns the time at which the event took place. This is called the event’s timestamp.
public int getModifiers()
Returns the modifier keys held down during this action event.
For example, when a button is pressed, an action event is generated. The getModifiers( ) method
returns a value that indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed
when the event was generated.
The ActionEvent class defines four integer constants that can be used to identify any modifiers
associated with an action event: ALT_MASK, CTRL_MASK, META_MASK, and SHIFT_MASK.
In addition, there is an integer constant, ACTION_PERFORMED, which indicates that a meaningful
action occured.
ItemEvent
An ItemEvent is generated when a check box or a list item is clicked or when a checkable menu
item is selected or deselected.
Constructor
ItemEvent(ItemSelectable source, int id, Object item, int stateChange)
Constructs an ItemEvent object.
Parameters:
source - The ItemSelectable object that originated the event
id - The integer that identifies the event type.
item - the item affected by the event
stateChange - An integer that indicates whether the item was selected or deselected.
The stateChange of any ItemEvent instance takes one of the following values:
ItemEvent.SELECTED :- The user selected an item.
ItemEvent.DESELECTED :- The user deselected an item.
getItemSelectable
public ItemSelectable getItemSelectable()
Returns the ItemSelectable object that originated the event.
Lists and choices are examples of user interface elements that implement the ItemSelectable
interface.
getItem
public Object getItem()
Returns: the item (object) that was affected by the event
getStateChange
public int getStateChange()
Returns: an integer that indicates whether the item was selected or deselected
paramString
public String paramString()
Returns a parameter string identifying this item event.
Interface:-
ItemListener
This interface deals with the item event. Following is the event handling method available in the
ItemListener interface:
void itemStateChanged(ItemEvent ie)
Example:
import java.awt.*;
import java.awt.event.*;
public class ItemListenerExample extends Frame implements ItemListener
{
Checkbox checkBox1,checkBox2;
Label label;
ItemListenerExample()
{
label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
checkBox1 = new Checkbox("C++");
checkBox1.setBounds(100,100, 50,50);
checkBox2 = new Checkbox("Java");
checkBox2.setBounds(100,150, 50,50);
add(checkBox1);
add(checkBox2);
add(label);
checkBox1.addItemListener(this);
checkBox2.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
if(e.getSource()==checkBox1)
label.setText("C++ Checkbox: " + (e.getStateChange()==1? "checked" : "unchecked"));
if(e.getSource()==checkBox2)
label.setText("Java Checkbox: "+ (e.getStateChange()==1?"checked":"unchecked"));
}
public static void main(String args[])
{
ItemListenerExample f = new ItemListenerExample();
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
KeyEvent
Constructor
KeyEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar)
Parameters:
source - The Component that originated the event
id - An integer indicating the type of event.
when - A long integer that specifies the time the event occurred.
modifiers - The modifier keys down during event (shift, ctrl, alt, meta).
keyCode - The integer code for an actual key, or VK_UNDEFINED (for a key-typed event)
keyChar - The Unicode character generated by this event, or CHAR_UNDEFINED (for key-
pressed and key-released events which do not map to a valid Unicode character)
Interface:-
KeyListener
This interface deals with the key events. Following are the event handling methods available in
the KeyListener interface:
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
Program:
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener
{
Label l;
TextArea area;
KeyListenerExample()
{
l = new Label();
l.setBounds (20, 50, 100, 20);
area = new TextArea();
area.setBounds (20, 80, 300, 300);
area.addKeyListener(this);
add(l);
add(area);
}
public void keyPressed (KeyEvent e)
{
l.setText ("Key Pressed");
}
public void keyReleased (KeyEvent e)
{
l.setText ("Key Released");
}
public void keyTyped (KeyEvent e)
{
l.setText ("Key Typed");
}
MouseEvent
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.
Constructor
public MouseEvent(Component source, int id, long when, int modifiers, int x, int y, int
clickCount, boolean popupTrigger, int button)
Parameters:
source - the Component that originated the event
id - the integer that identifies the event
when - a long int that gives the time the event occurred
modifiers - the modifier keys down during event (e.g. shift, ctrl, alt, meta)
x - the horizontal x coordinate for the mouse location
y - the vertical y coordinate for the mouse location
clickCount - the number of mouse clicks associated with event
popupTrigger - a boolean, true if this event is a trigger for a popup menu
button - which of the mouse buttons has changed state.
MouseEvent class defines the following integer constants that can be used to identify them:
MouseEvents
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.
MOUSE_CLICKED The user clicked the mouse (pressed and released)
MOUSE_ENTERED The mouse entered a component.
MOUSE_EXITED The mouse exited from a component.
ClassMethods
S.N. Method & Description
1 int getButton()
Returns which of the mouse buttons has changed state.
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.
2 int getClickCount()
Returns the number of mouse clicks associated with this event.
3 Point getPoint()
Returns the x,y position of the event relative to the source component.
4 int getX()
Returns the horizontal x position of the event relative to the source component.
5 int getY()
Returns the vertical y position of the event relative to the source component.
Interface:-
MouseListener
This interface deals with five of the mouse events. Following are the event handling methods
available in the MouseListener interface:
MouseMotionListener
This interface deals with two of the mouse events. Following are the event handling methods
available in the MouseMotionListener interface:
Exanple:
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener
{
Label l1,l2;
MouseListenerExample()
{
addMouseListener(this);
l1=new Label("Label 1");
l2=new Label("Label 2");
l1.setBounds(20,50,100,20);
l2.setBounds(20,100,100,20);
add(l1);
add(l2);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseEntered(MouseEvent e)
{
l1.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
l1.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{
l1.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
l1.setText("Mouse Released");
}
public void mouseClicked(MouseEvent e) {
l2.setText("Mouse Clicked");
}
TextEvent
The object of this class represents the text events. The TextEvent is generated when character is
entered in the text fields or text area. The TextEvent instance does not include the characters
currently in the text component that generated the event rather we are provided with other
methods to retrieve that information.
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
TextEvent defines the integer constant TEXT_VALUE_CHANGED.
// This operation differs from other event objects discussed in this section. For this reason, no
methods are discussed here for the TextEvent class. Think of a text event notification as a signal
to a listener that it should retrieve information from a specific text component.
Interface
TextListener
This interface deals with the text events. Following is the event handling method available in the
TextListener interface:
Example:
import java.awt.*;
import java.awt.event.*;
label1= new Label("Type in the textfield, to see the textevents it generates -");
label1.setBounds(100,100,300,40);
label2= new Label();
label2.setBounds(100,150,300,40);
field1 = new TextField(25);
field1.setBounds(100,200,100,40);
add(label1);
add(field1);
add(label2);
field1.addTextListener(this);
}
WindowEvent
This Event indicates that a window has changed its status. This is generated by a Window object when it is
opened, closed, activated, deactivated, iconified, or deiconified, or when focus is transfered into or out of
the Window.
Constructor
public WindowEvent(Window source, int id, Window opposite, int oldState, int newState)
Parameters:
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.
WindowEvent class defines the following integer constants that can be used to identify them:
Interface
WindowListener
This interface deals with seven of the window events. Following are the event handling methods
available in the WindowListener interface:
Example:
import java.awt.*;
import java.awt.event.*;
public class WindowExample extends Frame implements WindowListener {
WindowExample()
{
addWindowListener(this);
}
public void windowActivated (WindowEvent w) {
System.out.println("activated");
}
To avoid this unnecessary code, the java.awt.event package provides adapter classes for various
event-listener types. 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.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
Example of KeyAdapter
import java.awt.*;
import java.awt.event.*;
// class which inherits the KeyAdapter class
public class KeyAdapterExample extends KeyAdapter
{
Label l;
TextArea area;
Frame f;
KeyAdapterExample()
{
f = new Frame();
l = new Label();
l.setBounds (20, 50, 200, 20);
area = new TextArea();
area.setBounds (20, 80, 300, 300);
area.addKeyListener(this);
f.add(l);
f.add(area);
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);
}
// overriding the keyReleased() method
public void keyReleased (KeyEvent e)
{
String text = area.getText();
String words[] = text.split ("\\s");
l.setText ("Words: " + words.length + " Characters:" + text.length());
}
public static void main(String[] args)
{
new KeyAdapterExample();
}
}
Example of MouseAdapter
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter
{
MouseAdapterExample()
{
Frame f = new Frame();
f.addMouseListener(this);
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);
}
public void mouseReleased (MouseEvent e)
{
System.out.println(e);
}
public static void main(String[] args)
{
new MouseAdapterExample();
}
}