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

Delegation Event Handling

Uploaded by

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

Delegation Event Handling

Uploaded by

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

Event Handling in Java

• An event can be defined as changing the


state of an object or behavior by performing
actions.
• 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
Types Of Event
Cont….
• 1. Foreground Events
• Foreground events are the events that require user
interaction to generate, i.e., foreground events are
generated due to interaction by the user on
components in Graphic User Interface (GUI).
• Interactions are nothing but clicking on a button,
scrolling the scroll bar, cursor moments, etc.
• 2. Background Events
• Events that don’t require interactions of users to
generate are known as background events.

• Examples of these events are operating system


failures/interrupts, operation completion, etc.
Event Handling

• It is a mechanism to control the events and


to decide what should happen after an
event occur.
• To handle the events, Java follows
the Delegation Event model.
Introduction to Events
Events are generated by variety of sources such as :
• buttons
• checkbox
• choice
• list
• textfield
• textarea
• etc.

Different Controls
Delegation Event model

• It has Sources and Listeners.


Cont…..
• Source: Events are generated from the source.
There are various sources like 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.
• Example 2:that For ActionEvent we
Event Classes:

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

2) Register the component with the Listener:


component.addActionListener(instanceOfListenerclass);
3) Override the actionPerformed() method:
public void actionPerformed(ActionEvent e){
//Write the code here
}
Java ActionListener Example: On Button click

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()

• Adjustment events occur by an adjustable object like a


scrollbar.
• Five types of AdjustmentEvent are as follows :
BLOCK_DECREMENT = when user clicks inside scroll bar to
decrease its value
BLOCK_INCREMENT = when user clicks inside scroll bar to
increase its value
TRACK = when the slider is dragged
UNIT_DECREMENT = when button at the end of scroll bar is
clicked to decrease it's value
UNIT_INCREMENT = when button at the end of scroll bar is
clicked to increase it's value
• ADJUSTMENT_VALUE_CHANGED - tells whether change has occured or not
AdjustmentEvent class has one constructor :
• AdjustmentEvent(Adjustable src, int id, int type, int data)
Where src = reference to the object that generated the event
id = ADJUSTMENT_VALUE_CHANGED
type = type of event
data = data related to the event

• Adjustable getAdjustable( ) - returns the object that generates the event


• int getAdjustmentType( ) - returns the type of adjusment events from five types of events
• int getValue( ) - returns how much scroll bar is changed
Class constructors

• Constructor & Description


• 1. AdjustmentEvent(Adjustable source, int id, int type, int
value)
Constructs an AdjustmentEvent object with the specified Adjustable
source, event type, adjustment type, and value.

• 2. AdjustmentEvent(Adjustable source, int id, int type, int


value, boolean isAdjusting)
Constructs an AdjustmentEvent object with the specified Adjustable
source, event type, adjustment type, and value.

`
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

• This interface inherits methods from the following


classes:
• java.awt.AWTEvent
• java.util.EventObject
• java.lang.Object
• Print Page
program for AdjustmentEvent
import java.awt.*;
import java.awt.event.*;

public class AdjustmentEventExample {


public static void main(String[] args) {
// Create a frame
Frame frame = new Frame("AdjustmentEvent Example");

// 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());

// Create an adjustment listener to handle adjustment events


scrollbar.addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
// Update the label with the current value of the scrollbar
label.setText("Scrollbar Value: " + e.getValue());
}
});

// Set the layout manager


frame.setLayout(new FlowLayout());
// Add the scrollbar and label to the frame
frame.add(scrollbar);
frame.add(label);

// Set the size of the frame


frame.setSize(300, 100);

// Make the frame visible


frame.setVisible(true);

// Add window listener to close the application


frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
3. Event Class:ComponentEvent
Listener Interface :ComponentListener
Methods: componentResized(),
componentMoved()
componentShown()
componentHidden()
• An event occurs when a component moved, changed its visibility or
the size changed.
• ComponentEvent is created when the size, position,or visibility of
component is changed
• Four types of ComponentEvent indentified by integer constants are as
follows :
COMPONENT_HIDDEN = the component was hidden
COMPONENT_MOVED = the component was moved
COMPONENT_RESIZED = the component was resized
COMPONENT_SHOWN= the component becomes visibl
• ComponentEvent class constructor :
ComponentEvent(Component src, int type)
• ComponentEvent class is superclass (parent class) of ContainerEvent
class, FocusEvent class, KeyEvent class, MouseEvent class ans
WindowEvent class
• Component getComponent( ) - returns the component that
generated the event
• ContainerEvent is created when a component is added to or removed from a
container
• Two types of ContainerEvent identified by integer constant are as follow :
• COMPONENT_ADDED = when component is added to the container
COMPONENT_REMOVED = when component is removed from the container
• ContainerEvent class is subclass(child class) of ComponentEvent class
• ContainerEvent(Component src, int type, Component comp)
src = reference to container that generated the event
comp = component that is added or removed from the container
type = type of event
• Container getContainer( ) - returns reference to the container that
generated this event
• Component getChild( ) - returns reference to the component that
was added to or removed from the container
program for ComponentEvent

import java.awt.*;
import java.awt.event.*;

public class ComponentEventExample {

public static void main(String[] args) {


// Create a frame
Frame frame = new Frame("ComponentEvent Example");

// Create a button and text area


Button button = new Button("Click Me");
TextArea textArea = new TextArea("Resize or Move the window");

// Set layout manager


frame.setLayout(new BorderLayout());
frame.add(button, BorderLayout.NORTH);
frame.add(textArea, BorderLayout.CENTER);
// Add a component listener to handle component events
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
textArea.setText("Window Resized: Width = " + frame.getWidth() + ", Height = " +
frame.getHeight());
}

@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);

// Add window listener to handle the window closing event


frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
4.Event Class:ContainerEvent
Listener Interface : ContainerListener
Methods: componentRemoved()
componentAdded()
• The event is fired when a component is added or
removed from a container.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ContainerEventExample extends JFrame implements ContainerListener {

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);

// Add the panel to the frame


add(panel);

// Button to add a component to the panel


JButton addButton = new JButton("Add Button");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButton newButton = new JButton("New Button");
panel.add(newButton);
panel.revalidate(); // To re-layout the components in the panel
panel.repaint(); // To repaint the panel
}
});

// Button to remove a component from the panel


JButton removeButton = new JButton("Remove Button");
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (panel.getComponentCount() > 0) {
panel.remove(panel.getComponent(0));
panel.revalidate();
panel.repaint();
}
}
});

// Add the buttons to the frame


add(addButton);
add(removeButton);

// 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());
}

public static void main(String[] args) {


new ContainerEventExample();
}
}
OutPut:
5.Event Class:FocusEvent
Listener Interface : FocusListener
Methods:
focusLost()
focusGained()

• Focus events include focus, focusout, focusin, and blur.


• FocusEvent is created when a component gets or loses input focus
• Three constructors of FocusEvent class are as follow :
FocusEvent class is subclass(child class) of ComponentEvent class
• Three constructors of FocusEvent class are as follow :
FocusEvent class is subclass(child class) of ComponentEvent class
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, boolean temporaryFlag)
FocusEvent(Component src, int type, boolean temporaryFlag, Component
other)
Where src = reference to component that generated the event
type = type of event
• temoraryFlag has value true or false
• temoraryFlag has value true if the focus event is temporary otherwise
false
• Suppose our focus is in a text field and move the mouse to adjust scroll
bar then we called the focus is temporary lost
• the other component is a opposite component when focus changes
• When the event type is FOCUS_GAINED, the other component is that
component which lost focus
• Similarly, when the event type is FOCUS_LOST, the other component is
that component which gains focus
• Two types of Focus Event identified by integer constant are as follow :
FOCUS_GAINED = when the component gains the input focus
FOCUS_LOST = when the component loses the input focus
• Component getOppositeComponent( ) - this method returns the
opposite component that got or lost the input focus

• boolean isTemporary( ) - this method returns whether the focus


change is temporary or not, true means focus change is temporary
6. Event Class:ItemEvent
Listener Interface : ItemListener
Methods: itemStateChanged()

• Item event occurs when an item is selected.


• An ItemEvent is created when - checkbox or list item is clicked, when
checkable menu item is selected or deselected DESELECTED - when an item is
deselected by the user
• Two types of ItemEvent identified by integer constant are as follow :
DESELECTED - when an item is deselected by the user
• SELECTED - when an item is selected by the user ITEM_STATE_CHANGED
- this constant tells whether the state is changed or not
• ItemEvent( ItemSelectable src, int type, Object entry, int state)
Where
src = the component that generated this event
type = type of event
• Where entry = item of checkbox or list or checkable menu item that
generated the event
state = the current state of the item
• Object getItem( ) - this method returns reference to the item that
generated the event
• ItemSelectable getItemSelectable( ) - this method returns reference to
the itemSelectable object that generated the event
• List and Choice implements (inherits) ItemSelectable interface
• int getStateChange( ) - this method returns the changed state for an
event
7. Event Class:KeyEvent
Listener Interface : KeyListener

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().

• MouseWheelEvent occurs when the mouse wheel rotates in a


component.
10.Event Class:TextEvent
Listener Interface : TextListener

Methods: textChanged()

• TextEvent occurs when an object's text change.


11.Event Class:WindowEvent
Listener Interface : WindowListener

Methods: windowActivated(), windowDeactivated(),


windowOpened(), windowClosed(),
windowClosing(), windowIconfied() and
windowDeiconified().

• Window events occur when a window's status is changed.


EventHandlingExample
/ import required classes and package, if any
package JavaTpoint.Examples;

import java.awt.*;
import java.awt.event.*;

//create class EventHandlingExample1 to perform event handling within the class


public class EventHandlingExample1 {

// create variables for Frame, Label and Panel


private Frame frame;
private Label header;
private Label status;
private Panel panel;

// default constructor
public EventHandlingExample1(){
makeGUI();
}
// main() method start
public static void main(String[] args){

// create an instance of EventHandlingExample1


EventHandlingExample1 obj = new EventHandlingExample1();
obj.addButtonsAndLabel();
}

// create makeGUI() method to create a UI to perform user interaction


private void makeGUI(){

// initialize Frame
frame = new Frame("Event Handling Example");

// set frame size by using setSize() method


frame.setSize(400,400);

//set frame layout by using setLayout() method


frame.setLayout(new GridLayout(3, 1));
// add window listener to frame
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});

// initialize header and set alignment to center


header = new Label();
header.setAlignment(Label.CENTER);

//initialize status and set its alignment and size


status = new Label();
status.setAlignment(Label.CENTER);
status.setSize(350,100);

// initialize panel
panel = new Panel();
// set flow layout to panel
panel.setLayout(new FlowLayout());

// add header, status and panel to frame


frame.add(header);
frame.add(panel);
frame.add(status);
frame.setVisible(true);
}

// create addButtonsAndLabel() method


private void addButtonsAndLabel(){

// set label test


header.setText("Click a button: ");

// create ok, submit and cancel buttons


Button okBtn = new Button("OK");
Button submitBtn = new Button("Submit");
Button cancelBtn = new Button("Cancel");
// use setActionCommand() method to set action for ok, submit and cancel buttons
okBtn.setActionCommand("OK");
submitBtn.setActionCommand("Submit");
cancelBtn.setActionCommand("Cancel");

// add event listener to buttons using addActionListener() and ButtonClickListener()


okBtn.addActionListener(new ButtonClickListener());
submitBtn.addActionListener(new ButtonClickListener());
cancelBtn.addActionListener(new ButtonClickListener());

// add buttons to panel


panel.add(okBtn);
panel.add(submitBtn);
panel.add(cancelBtn);

// make frame visible by using setVisible()mmethod


frame.setVisible(true);
}
// implements ActionListener interface
private class ButtonClickListener implements ActionListener{

// define actionPerformed() method of ActionListener


public void actionPerformed(ActionEvent event) {

// get action command using getActionCommand() method of Event


String command = event.getActionCommand();

// code to check which button is pressed


if( command.equals( "OK" )) {
status.setText("Ok Button clicked.");
} else if( command.equals( "Submit" ) ) {
status.setText("Submit Button clicked.");
} else {
status.setText("Cancel Button clicked.");
}
}
}
}
Adapter Class

• Adapter Class is a simple java class that


implements an interface with only an empty
implementation.

• Let’s suppose, there is an interface Intref which


has various methods as follows:
********************
interface Intref
{
public void m1();
public void m2();
public void m3();

:
:
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
}
:
:

public void m1000(){


// some statements
}
}
*********************************
• The problem with this approach is that it increases the
length of the code and reduces readability.
• We can solve this problem by using the Adapter class.
• Instead of implementing the interface if we extends the
Adapter class to our Test class then we will have to
provide the implementation only for the required
methods that we will needed at the time of
implementation
• and we are not responsible to provide the
implementation for each and every method of the
interface, so that the length of the code will be reduced.
• So, firstly we have to create a class Adapter and we have to
implement the Intref interface and only provide the empty
implementation for each and every method of the Intref
interface.
• And we will have to use an abstract modifier while creating
an Adapter class because we are providing an empty
implementation to the methods of an interface
• we know that if the implementation of the method is
incomplete then we are restricted to create an object of that
class.
• Thus for restricting the creation of an object of the Adapter
class we should have to use an abstract modifier with the
Adapter class.
abstract class Adapter implements Intref{
public void m1(){};
public void m2(){};
public void m3(){};
:
:
:
:
public void m1000(){};
}
• Now we have to extends this Adapter class in our Test
class and just override those required methods which
we will require in the Test class.
Program1
class Test extends Adapter{
public void m1(){
System.out.println("This is m1() method.");
}
public void m80{
System.out.println("This is m80() method.");
}
}
/*package whatever //do not write package name here */

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);
}

abstract class Adapter implements Intref {


public void addNumWith5(int num) {}
public void multiplyNumWith5(int num) {}
}
class GFG extends Adapter {
@Override public void addNumWith5(int num)
{
// adding 5 with num
int result = num + 5;
System.out.println(
"After adding 5 with num, the required number is : "
+ result);
}
public static void main(String[] args)
{
GFG obj = new GFG();
obj.addNumWith5(10);
}
}
OutPut
After adding 5 with num, the required number is : 15
Pros of using Adapter classes:
• It assists the unrelated classes to work
combinedly.
• It provides ways to use classes in different ways.
• It increases the transparency of classes.
• It provides a way to include related patterns in
the class.
• It provides a pluggable kit for developing an
application.
• It increases the reusability of the class.
• The adapter classes are found in
java.awt.event, java.awt.dnd and
javax.swing.event packages.
• The Adapter classes with their corresponding
listener interfaces are given below.
java.awt.event Adapter classes
Adapter class Listener interface

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

Adapter class Listener interface

MouseInputAdapter MouseInputListener

InternalFrameAdapter InternalFrameListener
AdapterExample.java
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;

public class AdapterExample {


// object of Frame
Frame f;
// class constructor
AdapterExample() {
// creating a frame with the title
f = new Frame ("Window Adapter");
// adding the WindowListener to the frame
// overriding the windowClosing() method
f.addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e) {
f.dispose();
}
});
// setting the size, layout and
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);
}

// main method
public static void main(String[] args) {
new AdapterExample();
}
}
Output
Java MouseAdapter Example

In the following example, we are implementing the


MouseAdapter class.
The MouseListener interface is added into the frame to
listen the mouse event in the frame.
MouseAdapterExample.java
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;

// class which inherits the MouseAdapter class


public class MouseAdapterExample extends MouseAdapter {
// object of Frame class
Frame f;
// class constructor
MouseAdapterExample() {
// creating the frame with the title
f = new Frame ("Mouse Adapter");
// adding MouseListener to the Frame
f.addMouseListener(this);
// setting the size, layout and visibility of the frame
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
// overriding the mouseClicked() method of the MouseAdapter class
public void mouseClicked (MouseEvent e) {
// creating the Graphics object and fetching them from the Frame object using g
etGraphics() method
Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor (Color.BLUE);
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 30, 30);
}
// main method
public static void main(String[] args) {
new MouseAdapterExample();
}
}
OutPut
Java MouseMotionAdapter Example
In the following example, we are implementing the
MouseMotionAdapter class and its different methods to
listen to the mouse motion events in the Frame window.
MouseMotionAdapterExample.java

// importing the necessary libraries


import java.awt.*;
import java.awt.event.*;
// class which inherits the MouseMotionAdapter class
public class MouseMotionAdapterExample extends Mous
eMotionAdapter {
// object of Frame class
Frame f;
// class constructor
MouseMotionAdapterExample() {
// creating the frame with the title
f = new Frame ("Mouse Motion Adapter");
// adding MouseMotionListener to the Frame
f.addMouseMotionListener (this);
// setting the size, layout and visibility of the frame
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
// overriding the mouseDragged() method
public void mouseDragged (MouseEvent e) {
// creating the Graphics object and fetching them from the Frame object us
ing getGraphics() method
Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor (Color.ORANGE);
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 20, 20);
}
public static void main(String[] args) {
new MouseMotionAdapterExample();
}
}
outPut
Java KeyAdapter Example

In the following example, we are implementing the


KeyAdapter class and its method.
KeyAdapterExample.java
/ importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits the KeyAdapter class
public class KeyAdapterExample extends KeyAdapter {
// creating objects of Label, TextArea and Frame
Label l;
TextArea area;
Frame f;
// class constructor
KeyAdapterExample() {
// creating the Frame with title
f = new Frame ("Key Adapter");
// creating the Label
l = new Label();
// setting the location of label
l.setBounds (20, 50, 200, 20);
// creating the text area
area = new TextArea();
// setting the location of text area
area.setBounds (20, 80, 300, 300);
// adding KeyListener to text area
area.addKeyListener(this);
// adding the label and text area to frame
f.add(l);
f.add(area);
// setting the size, layout and visibility of frame
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);
}
// overriding the keyReleased() method
public void keyReleased (KeyEvent e) {
// creating the String object to get the text fromTextArea
String text = area.getText();
// splitting the String into words
String words[] = text.split ("\\s");
// setting the label text to print the number of words and characters of given string
l.setText ("Words: " + words.length + " Characters:" + text.length());
}
// main method
public static void main(String[] args) {
new KeyAdapterExample();
}
}
outPut
Inner Class in Java

• In Java, inner class refers to the class that is declared inside


class
or interface which were mainly introduced, to sum up,
same logically relatable classes as Java is object-oriented so
bringing it closer to the real world.
Adapter class program
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;

public class AdapterExample extends JFrame {

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:

• Making code clean and readable.


• Private methods of the outer class can be
accessed, so bringing a new dimension and
making it closer to the real world.
• Optimizing the code module.
Types of Inner Classes

There are basically four types of inner classes in java.


• Nested Inner Class
• Method Local Inner Classes
• Static Nested Classes
• Anonymous Inner Classes
Nested Inner Class

• 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 {

// show() method of inner class


public void show()
{

// Print statement
System.out.println("In a nested class method");
}
}
}

// Class 2
// Main class
class Nested {

// Main driver method


public static void main(String[] args)
{

// Note how inner class object is created inside


// main()
Outer.Inner in = new Outer().new Inner();

// Calling show() method over above object created


in.show();
}
OutPut
In a nested class method
We can not have a static method in a nested inner class because an
inner class is implicitly associated with an object of its outer class so it
cannot define any static method for itself. For example, the following
program doesn’t compile. But Since JAVA Version 16 we can have static
members in our inner class also
Example 2
// Java Program to Demonstrate Nested class
// Where Error is thrown

// Class 1
// Outer class
class Outer {

// Method defined inside outer class


void outerMethod()
{

// Print statement
System.out.println("inside outerMethod");
}
// Class 2
// Inner class
class Inner {

// Main driver method


public static void main(String[] args)
{

// Display message for better readability


System.out.println("inside inner class Method");
}
}
}
• An interface can also be nested and nested interfaces have some
interesting properties.
Type 2: Method Local Inner Classes

• Inner class can be declared within a method of an outer class which


we will be illustrating in the below example where Inner is an inner
class in outerMethod().
// Java Program to Illustrate Inner class can be
// declared within a method of outer class

// Class 1
// Outer class
class Outer {

// Method inside outer class


void outerMethod()
{

// Print statement
System.out.println("inside outerMethod");
// Class 2
// Inner class
// It is local to outerMethod()
class Inner {

// Method defined inside inner class


void innerMethod()
{

// Print statement whenever inner class is


// called
System.out.println("inside innerMethod");
}
}
// Creating object of inner class
Inner y = new Inner();

// Calling over method defined inside it


y.innerMethod();
}
}

// Class 3
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{

// Creating object of outer class inside main()


// method
Outer x = new Outer();

// Calling over the same method


// as we did for inner class above
x.outerMethod();
}
}
OutPut
inside outerMethod
inside innerMethod
Method Local inner classes can’t use a local variable of the outer
method until that local variable is not declared as final
class Outer {
void outerMethod() {
int x = 98;
System.out.println("inside outerMethod");

// Local inner class


class Inner {
void innerMethod() {
// Accessing local variable x
System.out.println("x= " + x);
}
}

// Creating an instance of the local inner class


Inner y = new Inner();

// Calling the method of the inner class


y.innerMethod();
}
}

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.

• Method local inner class can’t be marked as private, protected, static,


and transient but can be marked as abstract and final, but not both at
the same time.
Static Nested Classes
• Static nested classes are not technically inner classes. They are like a static member of outer class.

// Java Program to Illustrate Static Nested Classes

// Importing required classes


import java.util.*;

// 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 inside main() method


outerMethod();
}
}
}
// Class 3
// Main class
class GFG {

// Main driver method


public static void main(String args[])
{

// Calling method static display method rather than an instance of that class.
Outer.Inner.display();
}
}
OutPut
inside inner class Method
inside outerMethod
Program

public class Outer {


static int a = 20;

public static void display() {


System.out.println(a);
}

// static inner class


static class Inner {
OutPut
20
20
This is inner class constructor
20
Here we have static variable ,staic method,static class
We can use these three as
Outer.a
outer.display
outer.Inner
Event listner
InterFaces:
ActionListener
ItemListener
MouseListener and
MouseMotionListener
TextListener
WindowListener
ActionListener interface
• The Java Abstract Window Toolkit (AWT) is a GUI framework that
provides a set of classes and methods for creating and managing user
interfaces in Java applications.
• One of the most important components in AWT is
the ActionListener interface.
• It is a key element for adding interactivity in Java applications by
handling user actions.
• The ActionListener interface is a part of the ‘java.awt.event’ package.
• When you click on a button, menu item, or a check box, the Java
ActionListener is called.
• It is notified in reference to an ActionEvent.
• It only has one method, actionPerformed().
• The principle of an ActionListener is to record and respond to user
interactions with GUI components.
Method of ActionListener

When we click on the registered component, it triggers automatically. public void


actionPerformed(ActionEvent e)

• 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");

// Set the size


f.setSize(400, 200);

// Set the layout


f.setLayout(null);

// Make the frame visible


f.setVisible(true);
// Set the background color of the frame
f.setBackground(Color.LIGHT_GRAY);

// Create a button
Button b = new Button("Click Me");

// Set the positions


b.setBounds(160, 100, 80, 40);

// Add button to the frame


f.add(b);

// Set the background color of the button


b.setBackground(Color.GREEN);
// Create a text field
TextField tf = new TextField();

// Set the positions


tf.setBounds(50, 50, 300, 30);

// Add text field to the frame


f.add(tf);

// Create a label
Label lb = new Label();
// Set the positions
lb.setBounds(100, 150, 300, 30);

// Add label to the frame


f.add(lb);

// Add an action listener to the button


b.addActionListener(new ActionListener() {
// Override the actionPerformed() method
public void actionPerformed(ActionEvent e){

// Update the text of the label


lb.setText("Hey " + tf.getText() + "! "
+ "Welcome here!");
}

});
}
}
output
Example

// Java Program to
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Main implements ActionListener {


JCheckBox cb1, cb2, cb3;

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);

// Create check boxes and set the positions


cb1 = new JCheckBox("Pizza @ 100");
cb1.setBounds(100, 100, 150, 20);
cb2 = new JCheckBox("Burger @ 30");
cb2.setBounds(100, 150, 150, 20);
cb3 = new JCheckBox("Tea @ 10");
cb3.setBounds(100, 200, 150, 20);

// Create a button and set the positions


Button b = new Button("Order");
b.setBounds(100, 250, 80, 30);

// Add action listener to the button


b.addActionListener(this);
// Add components to the frame
f.add(l);
f.add(cb1);
f.add(cb2);
f.add(cb3);
f.add(b);

// Set the size of the frame and make it visible


f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}

// Override the actionPerformed() method


public void actionPerformed(ActionEvent e){
// Calculate the total amount and display it
float amount = 0;
String msg = "";
if (cb1.isSelected()) {
amount += 100;
msg = "Pizza: 100\n";
}
if (cb2.isSelected()) {
amount += 30;
msg += "Burger: 30\n";
}
if (cb3.isSelected()) {
amount += 10;
msg += "Tea: 10\n";
}
msg += "-----------------\n";
JOptionPane.showMessageDialog(
null, msg + "Total: " + amount);
}

// Main method
public static void main(String[] args) {
new Main();
}
}
ItemListener

• The Java ItemListener user interface in Java’s Abstract Window


Toolkit (AWT) is a crucial component for managing user interactions
with elements like checkboxes and option list
• The ItemListener interface is divided into the java.awt.event package
and extends the EventListener user interface.
• To utilize the ItemListener, you need to implement this interface in a
class that processes the ItemEvent.
• The object of this class is then registered with the GUI portion that
generates the ItemEvent exploitation of the addItemListener()
method.
• When the user interacts with the part, the itemStateChanged
method of the documented physical object is invoked to respond to
the user’s actions.
Declaration of ItemListener

public interface ItemListener extends EventListener {


void itemStateChanged(ItemEvent e);

}
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

// Java AWT Program to demonstrate


// Java ItemListener
import java.awt.*;
import java.awt.event.*;

// 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");

// Create a checkbox labeled "Enable Feature."


Checkbox checkbox = new Checkbox("Enable Feature");
// Create an instance of MyItemListener to handle checkbox events.
MyItemListener itemListener = new MyItemListener();

// Register the itemListener with the checkbox to listen for


events.
checkbox.addItemListener(itemListener);
// Add the checkbox to the frame.
frame.add(checkbox);

// Set the frame size and layout.


frame.setSize(300, 200);
frame.setLayout(new FlowLayout());

// Make the frame visible.


frame.setVisible(true);
}
}
class MyItemListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
// Respond when the checkbox is selected (checked).
System.out.println("Feature is enabled.");
} else {
// Respond when the checkbox is deselected (unchecked).
System.out.println("Feature is disabled.");
}
}
}
MouseListener
MouseListener interface in AWT is an important tool for managing
mouse events in Java applications.
• The MouseListener interface is part of the ‘java.awt.event’ package.
• It is used to retrieve and respond to mouse-related events in Java
applications.
• Mouse clicks, mouse button presses and releases, mouse enter and
exit events are examples of these events. By implementing
the MouseListener interface, you can define specific actions that your
application has to perform in response to the interactions with the
mouse.
Syntax of MouseListener
public interface MouseListener extends EventListener

• Methods of MouseListener Interface


void mouseClicked(MouseEvent e)
• Triggered when the mouse button is clicked (pressed and released) on
a component.
void mousePressed(MouseEvent e)
Triggered when a mouse button is pressed on a component.

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.*;

public class Main {


public static void main(String[] args){

// Create an instance of frame


Frame f = new Frame("MouseListener Demo");

// Create a label
Label l = new Label("Welcome to GeeksforGeeks!");

// Set the properties of label


l.setBounds(80, 100, 220, 30);
l.setFont(new Font("Serif", Font.BOLD, 18));
l.setForeground(Color.GREEN);
// Add MouseListener to the label with different methods
l.addMouseListener(new MouseListener() {

public void mouseClicked(MouseEvent e){


l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e){
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e){
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e){
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e){
l.setText("Mouse Released");
}

});

// Add label to the frame


f.add(l);

// Set the properties of frame


f.setLayout(null);
f.setSize(400, 300);
f.setVisible(true);
}
}
MouseMotionListener

• MouseListener and MouseMotionListener is an interface in


java.awt.event package .
• Mouse events
are of two types. MouseListener handles the events when the mouse
is not in motion. While MouseMotionListener
handles the events when mouse is in motion.

• There are five types of events that MouseListener can generate.


• There are five abstract functions that represent these five events.
• The abstract functions are :
• void mouseReleased(MouseEvent e) : Mouse key is released
• void mouseClicked(MouseEvent e) : Mouse key is pressed/released
• void mouseExited(MouseEvent e) : Mouse exited the component
• void mouseEntered(MouseEvent e) : Mouse entered the component
• void mousepressed(MouseEvent e) : Mouse key is pressed
There are two types of events that MouseMotionListener can generate.
There are two abstract functions that represent these two events. The
abstract functions are :
• void mouseDragged(MouseEvent e) : Invoked when a mouse button
is pressed in the component and dragged. Events are passed until the
user releases the mouse button.
• void mouseMoved(MouseEvent e) : invoked when the mouse cursor
is moved from one point to another within the component, without
pressing any mouse buttons.
// Java program to handle MouseListener events
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Mouse extends Frame implements MouseListener {

// Jlabels to display the actions of events of mouseListener


// static JLabel label1, label2, label3;

// default constructor
Mouse()
{
}

// main class
public static void main(String[] args)
{
// create a frame
JFrame f = new JFrame("MouseListener");

// set the size of the frame


f.setSize(600, 100);

// close the frame when close button is pressed


f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// create a new panel


JPanel p = new JPanel();

// set the layout of the panel


p.setLayout(new FlowLayout());

// initialize the labels


label1 = new JLabel("no event ");

label2 = new JLabel("no event ");

label3 = new JLabel("no event ");

// create an object of mouse class


Mouse m = new Mouse();

// add mouseListener to the frame


f.addMouseListener(m);

// add labels to the panel


p.add(label1);
p.add(label2);
p.add(label3);

// add panel to the frame


f.add(p);

f.show();
}

// getX() and getY() functions return the


// x and y coordinates of the current
// mouse position
// getClickCount() returns the number of
// quick consecutive clicks made by the user

// this function is invoked when the mouse is pressed


public void mousePressed(MouseEvent e)
{

// show the point where the user pressed the mouse


label1.setText("mouse pressed at point:"
+ e.getX() + " " + e.getY());
}

// this function is invoked when the mouse is released


public void mouseReleased(MouseEvent e)
{

// show the point where the user released the mouse click
label1.setText("mouse released at point:"
+ e.getX() + " " + e.getY());
}

// this function is invoked when the mouse exits the component


public void mouseExited(MouseEvent e)
{

// show the point through which the mouse exited the frame
label2.setText("mouse exited through point:"
+ e.getX() + " " + e.getY());
}

// this function is invoked when the mouse enters the component


public void mouseEntered(MouseEvent e)
{

// show the point through which the mouse entered the frame
label2.setText("mouse entered at point:"
+ e.getX() + " " + e.getY());
}

// this function is invoked when the mouse is pressed or released


public void mouseClicked(MouseEvent e)
{

// getClickCount gives the number of quick,


// consecutive clicks made by the user
// show the point where the mouse is i.e
// the x and y coordinates
label3.setText("mouse clicked at point:"
+ e.getX() + " "
+ e.getY() + "mouse clicked :" + e.getClickCount());
}
}
TextListener interface
• The TextListener interface in Java is used for listening to text events in
text components,
• such as text fields and text areas.
• It is part of the java.awt.event package and is commonly used in
Swing and AWT applications to handle changes in text input.
• TextListener Interface: The TextListener interface provides a method
to listen for changes to the text in a text component.
• Event Handling: To use the TextListener, you need to implement the
interface and register it with a text component.
• The TextListener responds to text changes by handling TextEvent
objects.
Methods

• The TextListener interface has only one method that must be


implemented:

• void textValueChanged(TextEvent e);


• This method is called whenever the text in the associated text
component changes.
Program
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TextFieldExample {

public static void main(String[] args) {


// Create a new JFrame
JFrame frame = new JFrame("JTextField Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);

// Create a JTextField
JTextField textField = new JTextField(20);

// Create an ActionListener for the JTextField


ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Handle the action event
String text = textField.getText();
System.out.println("Text entered: " + text);
}
};

// Register the ActionListener with the JTextField


textField.addActionListener(actionListener);

// Add the JTextField to the JFrame


frame.getContentPane().add(textField);

// Make the frame visible


frame.setVisible(true);
}
}
OutPut

Text entered: Hello


Windows Listner Interface

• The WindowListener interface in Java is used to handle events related


to window actions in AWT and Swing applications.
• This interface provides methods to respond to various window events
such as opening, closing, minimizing, and activating.
Methods in WindowListener

The WindowListener interface includes the following methods:

void windowOpened(WindowEvent e);

Called when a window has been opened and is now visible.


void windowClosing(WindowEvent e);

Called when the user initiates a "window closing" action (e.g., clicking
the close button).
void windowClosed(WindowEvent e);

Called when a window has been closed.


void windowIconified(WindowEvent e);

Called when the window is minimized (iconified).


void windowDeiconified(WindowEvent e);

Called when the window is restored from a minimized state.

You might also like