0% found this document useful (0 votes)
115 views20 pages

Advance Java Chapter 3 Full Notes - Ur Engineering Friend

Uploaded by

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

Advance Java Chapter 3 Full Notes - Ur Engineering Friend

Uploaded by

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

Advance Java Notes

MSBTE Diploma

Chapter 3: Event Handling

• Event delegation model


• Event classes
• Adapter classes
• Inner classes
• Event Listener Interfaces

Copyright @ Ur Engineering Friend

Ur Engineering Friend is a leading learning platform for MSBTE diploma. All


the copyrights reserved for our content to UEF EdTech Pvt. Ltd.

Please visit our Youtube Channel for more MSBTE Content. Click here !

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


Event Handling

Define Event Delegation Model -:

The Event Delegation Model in Java is a design pattern used to handle events (such as
mouse clicks, key presses, etc.) in graphical user interfaces (GUIs) built using AWT or
Swing. This model provides an efficient way to manage event handling by delegating the
responsibility of responding to events to designated listeners.

Key Concepts of the Event Delegation Model:

1. Event Source:
o The component or object that generates an event. For example, a button
(JButton) or a text field (JTextField) can be event sources.
o When the user interacts with the component (e.g., clicks a button), an event is
triggered.
2. Event Object:
o A class representing the event that occurs. It encapsulates details about the
event, such as the type of event and the source of the event.
o Example event classes: ActionEvent, MouseEvent, KeyEvent.
3. Event Listener:
o An interface or class that listens for specific events and responds to them.
o An event listener is registered with an event source and contains methods that
define how to respond when an event occurs.
o Example listener interfaces: ActionListener, MouseListener, KeyListener.
4. Event Handling Process:

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


o Event Generation: When the user interacts with an event source (like clicking
a button), an event is generated.
o Event Dispatching: The event is sent to the registered listener.
o Event Handling: The event listener executes the appropriate method to
respond to the event.

Components of Event Delegation Model:

1. Event Source:
o The component that generates events.
o Examples: Button, text field, window.
2. Event Object:
o The class that represents the event.
o Contains information about the event, such as the event source, the type of
event, and any associated data.
o Examples: ActionEvent, MouseEvent, KeyEvent.
3. Event Listener:
o An interface or class that receives and handles events.
o The listener contains methods that respond to specific events (e.g.,
actionPerformed() for button clicks).
o Examples: ActionListener, MouseListener.
4. Event Handling Code:
o Code inside the event listener methods that defines how the application should
respond to the event.
o For example, in an ActionListener, the actionPerformed() method might
display a message when a button is clicked.

Steps in Event Delegation Model:

1. Registering a Listener:
o The event source must register an event listener to handle events. This is done
using the addXXXListener() method, where XXX corresponds to the event
type (e.g., addActionListener() for ActionEvent).
o Example: button.addActionListener(new ActionListener() { ... });
2. Event Occurrence:

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


o When the user interacts with the event source, an event is triggered.
3. Event Notification:
o The event is forwarded to the appropriate listener(s), and the corresponding
event-handling method (such as actionPerformed()) is executed.

Event Classes

In Java, event classes represent different types of events that can occur in a GUI-based
application. These events are triggered by user interactions with components like buttons, text
fields, windows, etc. Event classes contain information about the event, such as its source, the
type of event, and relevant data (e.g., mouse coordinates, key pressed, etc.).

Java uses the Event Delegation Model to handle events, where an event source generates
events and delegates their handling to registered listeners. Event classes encapsulate the
details of these interactions, making them easy to manage.

Event Class Hierarchy

All event classes in Java are derived from the base class java.util.EventObject, which is the
root class for all events in Java.

• EventObject: The superclass of all event classes. It contains a reference to the event
source.
• AWTEvent: The subclass of EventObject and the base class for all Abstract Window
Toolkit (AWT) events. It provides support for events occurring in the AWT-based
GUI.

Key Event Classes in Java

1. ActionEvent:

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


o Description: Represents events generated by components such as buttons,
menu items, and other elements that the user can "act upon."
o Use Case: Button clicks, menu selections, etc.
o Methods:
▪ getActionCommand(): Returns the command string associated with
this action.
▪ getModifiers(): Returns the modifier keys pressed during the event
(e.g., Shift, Ctrl).
o Example:

JButton button = new JButton("Click Me");


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});

2. MouseEvent:
o Description: Represents mouse-related events like clicks, presses, releases,
movement, and drags.
o Use Case: Mouse clicks, dragging, entering, and exiting components.
o Methods:
▪ getX(), getY(): Returns the X and Y coordinates of the mouse event.
▪ getClickCount(): Returns the number of times the mouse was clicked.
▪ getButton(): Returns which mouse button was pressed (e.g., left or
right button).
o Example:

addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at: " + e.getX() + ", " + e.getY());
}
});

3. KeyEvent:

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


o Description: Represents events generated by keyboard actions such as key
presses and releases.
o Use Case: Key typing, detecting key combinations, etc.
o Methods:
▪ getKeyCode(): Returns the code of the key that was pressed.
▪ getKeyChar(): Returns the character of the key that was pressed.
▪ isActionKey(): Checks whether the key event corresponds to an action
key (e.g., arrow keys).
o Example:

addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed: " + e.getKeyCode());
}
});

4. WindowEvent:
o Description: Represents events related to window operations such as opening,
closing, minimizing, and maximizing.
o Use Case: Closing a window, minimizing, restoring, etc.
o Methods:
▪ getWindow(): Returns the Window that generated the event.
o Example:

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("Window is closing.");
System.exit(0);
}
});

5. FocusEvent:
o Description: Represents events that occur when a component gains or loses
focus (e.g., switching between input fields).
o Use Case: Focus transitions between UI components like text fields.

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


o Methods:
▪ isTemporary(): Determines if the focus change is temporary.
o Example:

addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
System.out.println("Component gained focus.");
}
});

6. ItemEvent:
o Description: Represents events generated by components like checkboxes and
radio buttons when the state changes.
o Use Case: Selection or deselection of an item.
o Methods:
▪ getStateChange(): Returns the state change (ItemEvent.SELECTED or
ItemEvent.DESELECTED).
o Example:

checkbox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
System.out.println("Checkbox state changed.");
}
});

7. AdjustmentEvent:
o Description: Represents events from adjustable components like scrollbars.
o Use Case: Adjusting a scrollbar's position.
o Methods:
▪ getValue(): Returns the current value of the scrollbar.
o Example:

scrollbar.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println("Scrollbar adjusted to: " + e.getValue());

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


}
});

8. TextEvent:
o Description: Represents events related to changes in the text of a component,
like typing in a text field.
o Use Case: Text modification in text fields or text areas.
o Methods:
▪ getSource(): Returns the text component that triggered the event.
o Example:

textField.addTextListener(new TextListener() {
public void textValueChanged(TextEvent e) {
System.out.println("Text changed.");
}
});

Adapter Classes

Adapter classes in Java are special classes provided in the Abstract Window Toolkit (AWT)
and Swing frameworks that make it easier to handle events in GUI-based applications. These
classes are part of the Event Handling mechanism in Java's Event Delegation Model. They
provide default implementations for all the methods of an event listener interface, allowing
you to override only the methods you need.

Purpose of Adapter Classes

• Simplify Event Handling: Many event listener interfaces have multiple methods that
you must implement even if you only need one or two of them. For example,
MouseListener has five methods, but often you only care about one, like

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


mouseClicked(). Using an adapter class allows you to avoid writing empty method
implementations for the methods you don't need.
• Selective Override: By extending an adapter class, you only override the methods
that you are interested in, and the rest of the methods (which you don't need) can be
left unimplemented.

Key Features of Adapter Classes

1. Predefined Empty Methods: Adapter classes provide an empty implementation for


all methods in the corresponding listener interface. You don't have to write empty
methods for unused events.
2. Extend Adapter Classes: To use adapter classes, you extend them and override only
the methods you are interested in.
3. Convenience: Adapter classes make the code cleaner and easier to read by removing
unnecessary method implementations.

Commonly Used Adapter Classes

1. MouseAdapter:
o Adapts the MouseListener and MouseMotionListener interfaces. Provides
empty implementations for the methods in these interfaces.
o Interfaces:
▪ MouseListener: Handles events such as mouse clicks, presses, and
releases.
▪ MouseMotionListener: Handles mouse movement and dragging
events.
o Example methods:
▪ mouseClicked(), mouseEntered(), mouseExited(), mousePressed(),
mouseReleased().
▪ mouseMoved(), mouseDragged().
2. KeyAdapter:
o Adapts the KeyListener interface, providing empty implementations for its
methods.
o Interface:

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


▪ KeyListener: Handles keyboard events such as key presses and
releases.
o Example methods:
▪ keyPressed(), keyReleased(), keyTyped().
3. WindowAdapter:
o Adapts the WindowListener interface, providing empty implementations for
window-related events.
o Interface:
▪ WindowListener: Handles window events such as opening, closing,
and minimizing windows.
o Example methods:
▪ windowOpened(), windowClosing(), windowClosed(),
windowIconified(), windowDeiconified(), windowActivated(),
windowDeactivated().
4. FocusAdapter:
o Adapts the FocusListener interface, providing empty implementations for
focus-related events.
o Interface:
▪ FocusListener: Handles events when a component gains or loses focus.
o Example methods:
▪ focusGained(), focusLost().
5. ComponentAdapter:
o Adapts the ComponentListener interface, providing empty implementations
for component-related events.
o Interface:
▪ ComponentListener: Handles events related to changes in component
size, position, or visibility.
o Example methods:
▪ componentResized(), componentMoved(), componentShown(),
componentHidden().
6. WindowFocusAdapter:
o Adapts the WindowFocusListener interface.
o Handles focus changes in a window.

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


Example of Using Adapter Classes

Let’s look at how you can use the MouseAdapter class. In this example, we'll handle a
mouse click event without implementing the other MouseListener methods.

Without Adapter Class (Implementing Full Listener Interface)


import javax.swing.*;
import java.awt.event.*;

public class WithoutAdapterExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Without Adapter");
JButton button = new JButton("Click Me");

// Implementing all methods of MouseListener


button.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked!");
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
});

frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

In this example, you have to implement all the methods in MouseListener, even if you only
care about mouseClicked().

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


With Adapter Class (Using MouseAdapter)
import javax.swing.*;
import java.awt.event.*;

public class WithAdapterExample {


public static void main(String[] args) {
JFrame frame = new JFrame("With Adapter");
JButton button = new JButton("Click Me");

// Using MouseAdapter, only implementing the method we need


button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked!");
}
});

frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Here, using MouseAdapter, you only need to override the mouseClicked() method and can
ignore the others. This approach is much cleaner.

Other Examples of Adapter Classes

1. KeyAdapter Example:

import java.awt.event.*;
import javax.swing.*;

public class KeyAdapterExample {


public static void main(String[] args) {

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


JFrame frame = new JFrame("Key Adapter Example");
JTextField textField = new JTextField(20);

// Using KeyAdapter, only implementing the method we need


textField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed: " + e.getKeyChar());
}
});

frame.add(textField);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

2. WindowAdapter Example:

import java.awt.event.*;
import javax.swing.*;

public class WindowAdapterExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Window Adapter Example");

// Using WindowAdapter, only implementing windowClosing method


frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("Window is closing");
System.exit(0);
}
});

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


frame.setSize(300, 200);
frame.setVisible(true);
}
}

Event Listener Interfaces

Event listener interfaces in Java are part of the event-handling mechanism provided by the
Abstract Window Toolkit (AWT) and Swing frameworks. These interfaces define methods
that must be implemented to respond to different types of events in a graphical user interface
(GUI), such as button clicks, mouse movements, or key presses. Event listeners are based on
the Event Delegation Model, which separates the logic for event generation from the logic
for event handling.

Event Delegation Model Recap

• Source: The component that generates an event (e.g., a button being clicked).
• Listener: The object that listens for and handles the event.
• Event: The actual event object that gets passed from the source to the listener (e.g., an
ActionEvent for a button click).

Key Event Listener Interfaces

Here are some commonly used event listener interfaces in Java:

1. ActionListener

• Handles action events like button clicks.


• Interface:

public interface ActionListener extends EventListener {


void actionPerformed(ActionEvent e);

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


}

• Example use case: When a button is clicked in a GUI.


• Method: actionPerformed(ActionEvent e) – This method is called when an action
occurs (e.g., when a button is clicked).

Example:

import javax.swing.*;
import java.awt.event.*;

public class ActionListenerExample {


public static void main(String[] args) {
JButton button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});

JFrame frame = new JFrame("ActionListener Example");


frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

2. MouseListener

• Handles mouse events such as clicks, presses, and releases.


• Interface:

public interface MouseListener extends EventListener {


void mouseClicked(MouseEvent e);
void mousePressed(MouseEvent e);

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


void mouseReleased(MouseEvent e);
void mouseEntered(MouseEvent e);
void mouseExited(MouseEvent e);
}

• Example use case: Detecting when a user clicks a button or hovers over a component.
• Methods:
o mouseClicked(MouseEvent e) – Called when the mouse is clicked.
o mousePressed(MouseEvent e) – Called when a mouse button is pressed.
o mouseReleased(MouseEvent e) – Called when a mouse button is released.
o mouseEntered(MouseEvent e) – Called when the mouse enters a component.
o mouseExited(MouseEvent e) – Called when the mouse exits a component.

Example:

import java.awt.event.*;
import javax.swing.*;

public class MouseListenerExample {


public static void main(String[] args) {
JButton button = new JButton("Hover or Click Me");
button.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked!");
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entered!");
}
public void mouseExited(MouseEvent e) {
System.out.println("Mouse exited!");
}
});

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


JFrame frame = new JFrame("MouseListener Example");
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

3. KeyListener

• Handles keyboard events such as key presses and releases.


• Interface:

public interface KeyListener extends EventListener {


void keyPressed(KeyEvent e);
void keyReleased(KeyEvent e);
void keyTyped(KeyEvent e);
}

• Example use case: Responding to user input through the keyboard.


• Methods:
o keyPressed(KeyEvent e) – Called when a key is pressed.
o keyReleased(KeyEvent e) – Called when a key is released.
o keyTyped(KeyEvent e) – Called when a key is typed (combines key press and
release events).

Example:

import java.awt.event.*;
import javax.swing.*;

public class KeyListenerExample {


public static void main(String[] args) {
JTextField textField = new JTextField(20);
textField.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


System.out.println("Key Pressed: " + e.getKeyChar());
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
});

JFrame frame = new JFrame("KeyListener Example");


frame.add(textField);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

4. WindowListener

• Handles window events like opening, closing, minimizing, and maximizing a


window.
• Interface:

public interface WindowListener extends EventListener {


void windowOpened(WindowEvent e);
void windowClosing(WindowEvent e);
void windowClosed(WindowEvent e);
void windowIconified(WindowEvent e);
void windowDeiconified(WindowEvent e);
void windowActivated(WindowEvent e);
void windowDeactivated(WindowEvent e);
}

• Example use case: Performing actions when a window is closed or minimized.


• Methods:
o windowOpened(WindowEvent e) – Called when a window is opened.
o windowClosing(WindowEvent e) – Called when a window is about to close.
o windowClosed(WindowEvent e) – Called after a window has closed.

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


o windowIconified(WindowEvent e) – Called when a window is minimized.
o windowDeiconified(WindowEvent e) – Called when a window is restored
from minimized state.
o windowActivated(WindowEvent e) – Called when a window gains focus.
o windowDeactivated(WindowEvent e) – Called when a window loses focus.

Example:

import java.awt.event.*;
import javax.swing.*;

public class WindowListenerExample {


public static void main(String[] args) {
JFrame frame = new JFrame("WindowListener Example");
frame.addWindowListener(new WindowListener() {
public void windowClosing(WindowEvent e) {
System.out.println("Window is closing");
System.exit(0);
}
public void windowOpened(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
});

frame.setSize(300, 200);
frame.setVisible(true);
}
}

5. FocusListener

• Handles focus events, such as when a component gains or loses focus.

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend


• Interface:

public interface FocusListener extends EventListener {


void focusGained(FocusEvent e);
void focusLost(FocusEvent e);
}

• Example use case: Reacting when a text field gains focus.


• Methods:
o focusGained(FocusEvent e) – Called when a component gains focus.
o focusLost(FocusEvent e) – Called when a component loses focus.

Example:

import javax.swing.*;
import java.awt.event.*;

public class FocusListenerExample {


public static void main(String[] args) {
JTextField textField = new JTextField(20);
textField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
System.out.println("Focus gained");
}
public void focusLost(FocusEvent e) {
System.out.println("Focus lost");
}
});

JFrame frame = new JFrame("FocusListener Example");


frame.add(textField);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}}

Maharashtra’s No.1 Learning Platform For MSBTE Ur Engineering Friend

You might also like