Delegation Event Handling
Delegation Event Handling
Different Controls
Delegation Event model
Input Event
ComponentEvent
Window Event
Item Event
Container Event
Focus Event
Text Event
Action Event
ActionEventclass
1. Event Class:ActionEvent
Listener Interface:ActionListener
Methods:actionPerformed()
• ActionEvent indicates that a component-defined action occurred
• ActionEvent is created when - button is pressed, list item is double clicked
or menu item is selected
• ActionEvent has four integer constants :
• ALT_MASK = whether ALT key was pressed
CTRL_MASK = whether CTRL key was pressed
META_MASK = whether META key was pressed
SHIFT_MASK = whether SHIFT key was pressed.
• ActionEvent class has three constructors :
ActionEvent(Object src,int type,String cmd) ,
ActionEvent( Object src,int type,String cmd,int modifiers)
ActionEvent( Object src,int type,String cmd, long when, int modifiers)
Where :
src = reference to object that generated the event
type = what type of event is
cmd = command string of event modifier
keys = ALT,CTRL,META or SHIFT keys were pressed or not
when = when the event has occured
• String getActionCommand( ) - returns command name of event object
• int getModifiers( ) - returns which modifier key was pressed when
event occurred
• int getWhen( ) - returns the time when event occurs (timestamp)
public abstract void actionPerformed(ActionEvent e);
1) Implement the ActionListener interface in the class:
public class ActionListenerExample Implements ActionListener
import java.awt.*;
import java.awt.event.*;
//1st step
public class ActionListenerExample implements ActionListener{
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
//2nd step
b.addActionListener(this);
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
//3rd step
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
}
OutPut
2. Event Class:AdjustmentEvent
Listener Interface :AdjustmentListener
Methods:adjustmentValueChanged()
`
Method & Description
• Adjustable getAdjustable()
Returns the Adjustable object where this event
originated.
• int getAdjustmentType
Returns the type of adjustment which caused the
value changed event.
• int getValue()
Returns the current value in the adjustment event.
• boolean getValueIsAdjusting()
Returns true if this is one of multiple adjustment
events.
• String paramString()
Returns a string representing the state of this Event.
Methods inherited
// Create a scrollbar
Scrollbar scrollbar = new Scrollbar(Scrollbar.HORIZONTAL, 50, 10, 0,
100);
// Create a label to display the scrollbar value
Label label = new Label("Scrollbar Value: " + scrollbar.getValue());
import java.awt.*;
import java.awt.event.*;
@Override
public void componentMoved(ComponentEvent e) {
textArea.setText("Window Moved: X = " + frame.getX() + ", Y = " + frame.getY());
}
});
// Set frame properties
frame.setSize(300, 200);
frame.setVisible(true);
public ContainerEventExample() {
// Set up the frame
setTitle("ContainerEvent Example");
setSize(400, 300);
setLayout(new FlowLayout());
// Create a panel
JPanel panel = new JPanel();
panel.setBackground(Color.LIGHT_GRAY);
panel.setPreferredSize(new Dimension(300, 200));
// Add a ContainerListener to the panel
panel.addContainerListener(this);
// Set the default close operation and make the frame visible
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void componentAdded(ContainerEvent e) {
System.out.println("Component added: " + e.getChild().getClass().getName());
}
@Override
public void componentRemoved(ContainerEvent e) {
System.out.println("Component removed: " + e.getChild().getClass().getName());
}
Methods: keyPressed(),
keyReleased(),
keyTyped().
• A key event occurs when the user presses a key on the keyboard.
8. Event Class:MouseEvent
Listener Interface : MouseListener and MouseMotionListener
Methods:
mouseClicked(), mousePressed(), mouseEntered(),
mouseExited() and mouseReleased() are the mouseListener methods.
mouseDregged() and mouseMoved() are the
MouseMotionListener() methods.
• A mouse event occurs when the user interacts with the mouse.
9.Event Class:MouseWheelEvent
Listener Interface : MouseWheelListener
Methods:mouseWheelMoved().
Methods: textChanged()
import java.awt.*;
import java.awt.event.*;
// default constructor
public EventHandlingExample1(){
makeGUI();
}
// main() method start
public static void main(String[] args){
// initialize Frame
frame = new Frame("Event Handling Example");
// initialize panel
panel = new Panel();
// set flow layout to panel
panel.setLayout(new FlowLayout());
:
:
public void m1000();
}
As, in this interface, there are 1000 methods present and
if we want to implement this interface in any particular
class then we will have to override all of these 1000
methods of Intref in the implementation class.
We can do this as follows:
class Test implements Intref{
public void m1(){
// some statements
}
public void m2(){
// some statements
}
public void m3(){
// some statements
}
:
:
import java.io.*;
interface Intref{
public void m1();
public void m2();
public void m3();
public void m4();
public void m5();
public void m6();
public void m7();
public void m8();
public void m9();
public void m10();
}
abstract class Adapter implements Intref{
// providing the empty implementation
public void m1(){};
public void m2(){};
public void m3(){};
public void m4(){};
public void m5(){};
public void m6(){};
public void m7(){};
public void m8(){};
public void m9(){};
public void m10(){};
}
class GFG extends Adapter{
@Override
public void m1(){
System.out.println("This is m1() method.");
}
@Override
public void m7(){
System.out.println("This is m7() method.");
}
public static void main (String[] args) {
GFG g = new GFG();
g.m1();
g.m7();
}
}
OutPut
This is m1() method.
This is m7() method.
Program2
/*package whatever //do not write package name here */
import java.io.*;
interface Intref {
public void addNumWith5(int num);
public void multiplyNumWith5(int num);
}
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
• In Java's AWT (Abstract Window Toolkit),
the java.awt.dnd package provides support for drag-and-drop
operations.
• To handle drag-and-drop events, you typically need to implement
several interfaces provided by this package.
• However, instead of implementing these interfaces directly, you can
use adapter classes to simplify event handling.
• Adapter classes in java.awt.dnd serve as convenient base classes that
provide default implementations for the methods in the drag-and-
drop event listener interfaces.
• This allows you to override only the methods you are interested in,
rather than having to implement every method in the interface.
Adapter class Listener interface
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
javax.swing.event Adapter classes
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
AdapterExample.java
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// main method
public static void main(String[] args) {
new AdapterExample();
}
}
Output
Java MouseAdapter Example
public AdapterExample() {
setTitle("Adapter Class Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
outPut
Mouse clicked at: 150, 100
Inner Class
• Inner class refers to the class that is
declared inside class or interface which
were mainly introduced, to sum up, same
logically relatable classes.
Advantages associated with inner classes are
as follows:
• It can access any private instance variable of the outer class. Like any
other instance variable, we can have access modifier
private
protected
public
and default modifier.
Like class, an interface can also be nested and can have access
specifiers.
// Java Program to Demonstrate Nested class
// Class 1
// Helper classes
class Outer {
// Class 2
// Simple nested inner class
class Inner {
// Print statement
System.out.println("In a nested class method");
}
}
}
// Class 2
// Main class
class Nested {
// Class 1
// Outer class
class Outer {
// Print statement
System.out.println("inside outerMethod");
}
// Class 2
// Inner class
class Inner {
// Class 1
// Outer class
class Outer {
// Print statement
System.out.println("inside outerMethod");
// Class 2
// Inner class
// It is local to outerMethod()
class Inner {
// Class 3
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
class MethodLocalVariableDemo {
public static void main(String[] args) {
// Creating an instance of Outer class and calling outerMethod()
Outer x = new Outer();
x.outerMethod();
}
}
OutPut
inside outerMethod
x= 98
• Note: Local inner class cannot access non-final local variable till JDK
1.7. Since JDK 1.8, it is possible to access the non-final local variable in
method local inner class.
The following code compiles and
runs fine (Note that x is final this
time)
class Outer {
void outerMethod() {
final int x=98;
System.out.println("inside outerMethod");
class Inner {
void innerMethod() {
System.out.println("x = "+x);
}
}
Inner y = new Inner();
y.innerMethod();
}
}
class MethodLocalVariableDemo {
public static void main(String[] args){
Outer x = new Outer();
x.outerMethod();
}
}
Output
inside outerMethod
X=98
• The main reason we need to declare a local variable as a final is that
the local variable lives on the stack till the method is on the stack but
there might be a case the object of the inner class still lives on the
heap.
// Class 1
// Outer class
class Outer {
// Method
private static void outerMethod()
{
// Print statement
System.out.println("inside outerMethod");
}
// Class 2
// Static inner class
static class Inner {
public static void display()
{
// Print statement
System.out.println("inside inner class Method");
// Calling method static display method rather than an instance of that class.
Outer.Inner.display();
}
}
OutPut
inside inner class Method
inside outerMethod
Program
• Syntax of an ActionListener
1. At first, implement the ActionListener interface in the class.
public class Example Implements ActionListener
2. Configure the component with the Listener.
component.addActionListener(instance of the Listener class);
• \ 3. Override the actionPerformed method as a response to the
method call.
public void actionPerformed(ActionEvent e){
//Write the code here
}
Exampkle
// Java Program to implement
// AWT ActionListener
import java.awt.*;
import java.awt.event.*;
// Driver Class
public class Main {
// main function
public static void main(String[] args){
// Create a frame
Frame f = new Frame("AWT ActionListener Example");
// Create a button
Button b = new Button("Click Me");
// Create a label
Label lb = new Label();
// Set the positions
lb.setBounds(100, 150, 300, 30);
});
}
}
output
Example
// Java Program to
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Main(){
// Create a frame
Frame f = new Frame("AWT ActionListener Example");
// Create a label
Label l = new Label("Food Menu");
// Set the positions
l.setBounds(150, 50, 300, 20);
// Main method
public static void main(String[] args) {
new Main();
}
}
ItemListener
}
ItemListener Method
itemStateChanged(ItemEvent e)
This method is invoked when an item has been selected or
deselected by the user. It takes an ItemEvent object as a parameter, p
ItemListener Example
// Driver Class
class CheckboxExample {
// Main function
public static void main(String[] args) {
// Create a new frame with a title.
Frame frame = new Frame("Checkbox Example");
void mouseReleased(MouseEvent e)
This method is called when a mouse button is released on a
component.
void mouseReleased(MouseEvent e)
This method is called when a mouse button is released on a
component.
void mouseEntered(MouseEvent e)
Invoked after mouse entry into a component.
void mouseExited(MouseEvent e)
Invoked when the mouse exits a component.
Example
// Java AWT Program to demonstrate
// MouseListener
import java.awt.*;
import java.awt.event.*;
// Create a label
Label l = new Label("Welcome to GeeksforGeeks!");
});
// default constructor
Mouse()
{
}
// main class
public static void main(String[] args)
{
// create a frame
JFrame f = new JFrame("MouseListener");
f.show();
}
// show the point where the user released the mouse click
label1.setText("mouse released at point:"
+ e.getX() + " " + e.getY());
}
// show the point through which the mouse exited the frame
label2.setText("mouse exited through point:"
+ e.getX() + " " + e.getY());
}
// show the point through which the mouse entered the frame
label2.setText("mouse entered at point:"
+ e.getX() + " " + e.getY());
}
// Create a JTextField
JTextField textField = new JTextField(20);
Called when the user initiates a "window closing" action (e.g., clicking
the close button).
void windowClosed(WindowEvent e);