Event Handling in Java
• An event can be defined as changing the state of an object or behaviour by
performing actions.
• Example: Actions can be a button click, cursor movement, keypress through
keyboard or page scrolling, etc.
• The [Link] package can be used to provide various event classes.
Classification of Events
• Foreground Events
• Background Events
Delegation Event model
• Source: Events are generated from the source.
• Example: buttons, checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to
generate events.
• Listeners: Listeners are used for handling the events generated from the source. Each of these listeners
represents interfaces that are responsible for handling events.
• To perform Event Handling, we need to register the source with the listener.
• Registering the Source With Listener
Different Classes provide different registration methods.
Syntax:
addTypeListener()
where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register.
Event Classes in Java
Event Class Listener Interface Description
An event that indicates that a component-
ActionEvent ActionListener defined action occurred like a button click or
selecting an item from the menu-item list.
The adjustment event is emitted by an
AdjustmentEvent AdjustmentListener
Adjustable object like Scrollbar.
An event that indicates that a component
ComponentEvent ComponentListener moved, the size changed or changed its
visibility.
When a component is added to a container (or)
ContainerEvent ContainerListener removed from it, then this event is generated by
a container object.
These are focus-related events, which include
FocusEvent FocusListener
focus, focusin, focusout, and blur.
An event that indicates whether an item was
ItemEvent ItemListener
selected or not.
An event that occurs due to a
KeyEvent KeyListener sequence of keypresses on the
keyboard.
The events that occur due to the
MouseListener &
MouseEvent user interaction with the mouse
MouseMotionListener
(Pointing Device).
An event that specifies that the
MouseWheelEvent MouseWheelListener mouse wheel was rotated in a
component.
An event that occurs when an
TextEvent TextListener
object’s text changes.
An event which indicates whether a
WindowEvent WindowListener window has changed its status or
not.
Different methods in Different interfaces
Listener Interface Methods
ActionListener •actionPerformed()
AdjustmentListener •adjustmentValueChanged()
•componentResized()
•componentShown()
ComponentListener
•componentMoved()
•componentHidden()
•componentAdded()
ContainerListener
•componentRemoved()
•focusGained()
FocusListener
•focusLost()
ItemListener •itemStateChanged()
•keyTyped()
KeyListener •keyPressed()
•keyReleased()
•mousePressed()
•mouseClicked()
MouseListener •mouseEntered()
•mouseExited()
•mouseReleased()
•mouseMoved()
MouseMotionListener
•mouseDragged()
MouseWheelListener •mouseWheelMoved()
TextListener •textChanged()
•windowActivated()
•windowDeactivated()
•windowOpened()
WindowListener •windowClosed()
•windowClosing()
•windowIconified()
•windowDeiconified()
Key Differences: AWT vs Swing
Feature AWT ([Link]) Swing ([Link])
Heavyweight (uses native OS
Component Type Lightweight (Java-based)
UI)
Platform Dependency OS-dependent Platform-independent
Customizable with
Look & Feel OS-defined
UIManager
Event Handling Uses old event model Uses event delegation model
Uses
Thread-Safety Not thread-safe
[Link]()
Customization Limited Supports icons, tooltips, etc.
Slower due to OS
Performance Faster and more flexible
dependency
Best Use Case Simple UI applications Modern applications
import [Link].*; add(b);add(tf);
import [Link].*; setSize(300,300);
class AEvent extends Frame implements ActionList setLayout(null);
ener setVisible(true);
{ }
TextField tf; public void actionPerformed(ActionEvent e)
AEvent() {
{ [Link]("Welcome");
tf=new TextField(); }
[Link](60,50,170,20); public static void main(String args[]){
Button b=new Button("click me"); new AEvent();
[Link](100,120,80,30); }
[Link](this); }
import [Link].*;
public class MyFrame extends JFrame {
public MyFrame()
{
setTitle("Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new JButton("Click Me"));
setVisible(true);
}
public static void main(String[] args)
{
new MyFrame();
}
}
import [Link].*;
import [Link].*;
public class MyFrame extends Jframe
{
public MyFrame()
{
setTitle("Welcome");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
add(new JButton("Click Me"));
add(new JButton("Search"));
setVisible(true);
}
public static void main(String[] args) {
new MyFrame();
}
}
HANDLING MOUSE EVENTS
/*Write a program to create a text area and display the mouse event when the
the mouse is clicked, when the mouse is moved, etc. is done by the user
Mouse events*/
import [Link].*;
import [Link].*;
import [Link].*;
public class MouseEvents extends JFrame implements MouseListener, MouseMotionListener
{
String str= " ";
JTextArea ta;
Container c;
int x,y;
public MouseEvents()
{ c= getContentPane();
[Link](new FlowLayout());
ta = new JTextArea ("Click the mouse ",5,20);
[Link](new Font("Arial", Font. BOLD, 30));
[Link](ta);
[Link](this);
[Link](this);
}
public void mouseClicked (MouseEvent me)
{
int i= [Link]();
if(i==1)
str += "Clicked Button: Left";
else if(i==2)
str += "Clicked Button: Middle";
else if(i==3)
str += "Clicked Button: Right";
[Link]();
}
public void mouseEntered (MouseEvent me)
{
str += "Mouse entered";
[Link]();
}
public void mouseExited (MouseEvent me)
{
str += "MouseExited";
[Link]();
}
public void mousePressed(MouseEvent me)
{
x = [Link]();
y = [Link](); // If you need the y-coordinate
str +="mousePressed t: " +x +"\t"+y;
[Link]();
}
public void mouseReleased (MouseEvent me)
{
x= [Link]();
y= [Link]();
str += "Mouse Released at: "+x+"\t"+y;
[Link]();
}
public void mouseDragged (MouseEvent me)
{
x = [Link]();
y = [Link]();
str += "Mouse Dragged at: "+x+"\t"+y;
[Link]();
}
public void mouseMoved (MouseEvent me)
{
x = [Link]();
y = [Link]();
str += "Mouse Moved at: "+x+"\t"+y;
[Link]();
}
public void display()
{
[Link](str);
str="";
}
public static void main(String args[])
{
MouseEvents mes = new MouseEvents();
[Link](400,400);
[Link](true);
[Link] (JFrame.EXIT_ON_CLOSE);
}
}
OUTPUT
KEYBOARD EVENTS
import [Link].*;
import [Link].*;
import [Link].*;
public class KeyBoardEvents extends JFrame implements KeyListener
{
Container c;
JTextArea ta;
String str="";
KeyBoardEvents()
{
c= getContentPane();
ta= new JTextArea ("Press a key");
ta. setFont(new Font("Arial", Font. BOLD, 30));
[Link](ta);
[Link](this);
}
public void keyPressed(KeyEvent ke)
{
int keycode = [Link]();
if (keycode== KeyEvent.VK_F1) str += "F1 key";
if (keycode == KeyEvent.VK_F2) str += "F2 key";
if (keycode== KeyEvent.VK_F3) str += "F3 key";
if (keycode ==KeyEvent.VK_PAGE_UP) str += "Page Up";
if (keycode ==KeyEvent.VK_PAGE_DOWN) str += "Page Down";
if (keycode ==KeyEvent.VK_ALT) str += "Alter";
if (keycode==KeyEvent.VK_HOME) str += "Home";
if (keycode==KeyEvent.VK_END) str += "End";
[Link](str);
str="";
}
public void keyReleased (KeyEvent ke)
{}
public void keyTyped (KeyEvent ke)
{}
public static void main(String args[])
{
KeyBoardEvents kbe = new KeyBoardEvents();
[Link](400,400);
[Link](true);
[Link] (JFrame.EXIT_ON_CLOSE);
}
}
OUTPUT