0% found this document useful (0 votes)
1 views

Event Handling

The document provides an overview of event handling in Java, detailing the types of events, event sources, and listeners used to manage these events. It explains the delegation event model and lists various event classes along with their corresponding listener interfaces and methods. Additionally, it compares AWT and Swing in terms of component types, platform dependency, and performance, while also including sample code for handling mouse and keyboard events.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Event Handling

The document provides an overview of event handling in Java, detailing the types of events, event sources, and listeners used to manage these events. It explains the delegation event model and lists various event classes along with their corresponding listener interfaces and methods. Additionally, it compares AWT and Swing in terms of component types, platform dependency, and performance, while also including sample code for handling mouse and keyboard events.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

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 java.awt.event 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 (java.awt) Swing (javax.swing)
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
SwingUtilities.invokeLater()
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 java.awt.*; add(b);add(tf);
import java.awt.event.*; setSize(300,300);
class AEvent extends Frame implements ActionList setLayout(null);
ener setVisible(true);
{ }
TextField tf; public void actionPerformed(ActionEvent e)
AEvent() {
{ tf.setText("Welcome");
tf=new TextField(); }
tf.setBounds(60,50,170,20); public static void main(String args[]){
Button b=new Button("click me"); new AEvent();
b.setBounds(100,120,80,30); }
b.addActionListener(this); }
import javax.swing.*;
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 javax.swing.*;
import java.awt.*;

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 java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseEvents extends JFrame implements MouseListener, MouseMotionListener
{
String str= " ";
JTextArea ta;
Container c;
int x,y;
public MouseEvents()
{ c= getContentPane();
c.setLayout(new FlowLayout());
ta = new JTextArea ("Click the mouse ",5,20);
ta.setFont(new Font("Arial", Font. BOLD, 30));
c.add(ta);
ta.addMouseListener(this);
ta.addMouseMotionListener(this);
}
public void mouseClicked (MouseEvent me)
{
int i= me.getButton();
if(i==1)
str += "Clicked Button: Left";
else if(i==2)
str += "Clicked Button: Middle";
else if(i==3)
str += "Clicked Button: Right";
this.display();
}
public void mouseEntered (MouseEvent me)
{

str += "Mouse entered";


this.display();
}
public void mouseExited (MouseEvent me)
{
str += "MouseExited";
this.display();
}
public void mousePressed(MouseEvent me)
{
x = me.getX();
y = me.getY(); // If you need the y-coordinate
str +="mousePressed t: " +x +"\t"+y;
this.display();
}
public void mouseReleased (MouseEvent me)
{
x= me.getX();
y= me.getY();
str += "Mouse Released at: "+x+"\t"+y;
this.display();
}

public void mouseDragged (MouseEvent me)


{
x = me.getX();
y = me.getY();
str += "Mouse Dragged at: "+x+"\t"+y;
this.display();
}
public void mouseMoved (MouseEvent me)
{
x = me.getX();
y = me.getY();
str += "Mouse Moved at: "+x+"\t"+y;
this.display();
}
public void display()
{
ta.setText(str);
str="";
}
public static void main(String args[])
{
MouseEvents mes = new MouseEvents();
mes.setSize(400,400);
mes.setVisible(true);
mes.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
}
OUTPUT
KEYBOARD EVENTS
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
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));
c.add(ta);
ta.addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{

int keycode = ke.getKeyCode();


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";
ta.setText(str);
str="";
}
public void keyReleased (KeyEvent ke)
{}
public void keyTyped (KeyEvent ke)
{}
public static void main(String args[])
{
KeyBoardEvents kbe = new KeyBoardEvents();
kbe.setSize(400,400);
kbe.setVisible(true);
kbe.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
}
OUTPUT

You might also like