Unit 4 and 5
Unit 4 and 5
frame.add(panel);
frame.setVisible(true);
}
}
3. Event Delegation Model
The Event Delegation Model in Java is a design pattern for handling events like button clicks or
mouse movements. It consists of:
Event Source: The component (e.g., JButton) that generates the event.
Event Listener: The object that listens for and handles the event.
Event Object: Encapsulates information about the event (e.g., ActionEvent for button clicks).
Steps in the Event Delegation Model:
Register a Listener: Attach a listener to the source using methods like addActionListener.
Event Occurs: The source generates an event object.
Listener Handles the Event: The event object is passed to the listener's handler method (e.g.,
actionPerformed).
4. Event Handling
Event handling involves writing code to define what happens when an event occurs.
frame.add(panel);
frame.setVisible(true);
}
}
Handling Mouse Events
Mouse events include actions like clicks, movements, and releases. The MouseListener
interface is used for handling these.
import javax.swing.*;
import java.awt.event.*;
frame.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
label.setText("Mouse clicked at: " + e.getX() + ", " + e.getY());
}
frame.add(label);
frame.setVisible(true);
}
}
Summary of Key Concepts:
File Handling: Use classes like File, FileReader, and FileWriter for working with files.
Basic GUI Elements: Swing components like JButton, JLabel, JTextField for building user
interfaces.
Event Delegation Model: Separates event generation (source) from handling (listener).
Event Handling: Use interfaces like ActionListener and MouseListener to define behavior for
specific events.
import javax.swing.*;
import java.awt.event.*;
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("Button Clicked!");
}
});
frame.setLayout(new FlowLayout());
frame.add(button);
frame.add(label);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
2. MouseListener
Handles mouse events like clicks, movements, and entering or exiting a component.
Methods:
mouseClicked(MouseEvent e)
mouseEntered(MouseEvent e)
mouseExited(MouseEvent e)
mousePressed(MouseEvent e)
mouseReleased(MouseEvent e)
Example: Mouse Click Handling
import javax.swing.*;
import java.awt.event.*;
frame.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
label.setText("Mouse clicked at: " + e.getX() + ", " + e.getY());
}
});
frame.add(label);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
3. KeyListener
Handles keyboard events like key presses or releases.
Methods:
keyPressed(KeyEvent e)
keyReleased(KeyEvent e)
keyTyped(KeyEvent e)
Example: Key Press Handling
import javax.swing.*;
import java.awt.event.*;
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
label.setText("Key typed: " + e.getKeyChar());
}
});
frame.setLayout(new FlowLayout());
frame.add(textField);
frame.add(label);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
4. WindowListener
Handles window events like opening, closing, or minimizing.
Methods:
windowOpened(WindowEvent e)
windowClosing(WindowEvent e)
windowClosed(WindowEvent e)
windowIconified(WindowEvent e)
windowDeiconified(WindowEvent e)
windowActivated(WindowEvent e)
windowDeactivated(WindowEvent e)
Example: Window Close Handling
import javax.swing.*;
import java.awt.event.*;
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("Window is closing");
System.exit(0);
}
});
frame.setSize(400, 300);
frame.setVisible(true);
}
}
Event Handling Using Lambda Expressions (Java 8+)
Java 8 introduced lambda expressions, which simplify event handling by removing the need for
anonymous inner classes.
Example: Button Click Handling with Lambda
import javax.swing.*;
frame.setLayout(new FlowLayout());
frame.add(button);
frame.add(label);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Key Points About Event Handling
Anonymous Inner Classes:
Simplify handling by allowing event listeners to be defined inline.
Adapter Classes:
For interfaces with multiple methods, adapter classes like MouseAdapter or KeyAdapter can be
used to override only the necessary methods.
Lambda Expressions:
Provide a concise way to handle events in Java 8 and later.
Event handling is a critical part of building responsive and interactive applications. By
😊
understanding these concepts, developers can create robust GUI-based applications in Java.
Let me know if you need more examples or further clarifications!
import javax.swing.*;
import javax.swing.*;
import javax.swing.*;
import java.awt.event.*;
frame.setLayout(new FlowLayout());
frame.add(button);
frame.add(label);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
4. JTextField
A single-line text input component.
Example:
import javax.swing.*;
frame.setLayout(new FlowLayout());
frame.add(textField);
frame.add(button);
frame.add(label);
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
5. JTextArea
A multi-line text input component.
Example:
import javax.swing.*;
frame.setLayout(new FlowLayout());
frame.add(new JScrollPane(textArea)); // Adds a scroll bar
frame.add(button);
frame.add(label);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
6. JCheckBox
A box that can be checked or unchecked to represent a choice.
Example:
import javax.swing.*;
button.addActionListener(e -> {
if (box1.isSelected()) System.out.println("Option 1 selected");
if (box2.isSelected()) System.out.println("Option 2 selected");
});
frame.setLayout(new FlowLayout());
frame.add(box1);
frame.add(box2);
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
7. JRadioButton
Represents one choice in a group where only one option can be selected at a time.
Example:
import javax.swing.*;
button.addActionListener(e -> {
if (rb1.isSelected()) label.setText("Male selected");
if (rb2.isSelected()) label.setText("Female selected");
});
frame.setLayout(new FlowLayout());
frame.add(rb1);
frame.add(rb2);
frame.add(button);
frame.add(label);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Scheduling in Java
Scheduling determines how threads are managed and executed by the CPU. Java uses a
priority-based scheduling model where threads with higher priorities are more likely to execute
first. The actual behavior of thread scheduling depends on the JVM and underlying operating
system.
Threads share CPU time in small slices, giving the appearance of concurrency.
Thread Scheduling Example
Example: Using Priorities
t1.setPriority(Thread.MIN_PRIORITY); // Priority 1
t2.setPriority(Thread.MAX_PRIORITY); // Priority 10
t1.start();
t2.start();
}
}
Thread Yield
A thread can voluntarily release the CPU using Thread.yield(), allowing other threads of equal
priority to execute.
Example:
t1.start();
t2.start();
}
}
Thread Sleep
A thread can pause its execution for a specific period using Thread.sleep(milliseconds).
Example:
t1.start();
}
}
Summary
GUI Elements: Provide interactivity and visualization in applications using components like
JButton, JTextField, etc.
Scheduling: Determines how threads execute, influenced by priorities, sleep, and yield
mechanisms.
Let me know if you'd like more in-depth examples or explanations!
Detailed Explanation: Exceptions and Multithreading in Java
1. Exceptions in Java
Types of Exceptions
1. Checked Exceptions:
Compile-Time Yes No
Check
Java allows developers to create their own exceptions by extending the Exception or
RuntimeException class.
Example:
2. Multithreading in Java
Introduction
Benefits of Multithreading
1. Improved performance through parallelism.
2. Efficient CPU utilization.
3. Simplifies the program structure for handling multiple tasks.
1. New: Thread is created but not started (e.g., Thread t = new Thread();).
2. Runnable: Thread is ready to run but waiting for CPU (after calling start()).
3. Running: The thread is executing its run() method.
4. Waiting/Blocked: Thread is paused due to resource unavailability or conditions.
5. Terminated: Thread has completed execution or stopped.
1. Priorities:
○ Threads have priorities ranging from 1 (MIN_PRIORITY) to 10
(MAX_PRIORITY).
○ Default priority is 5 (NORM_PRIORITY).
○ Higher-priority threads are executed before lower-priority threads, but this
depends on the OS and JVM.
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}
2. Scheduling:
○ The JVM thread scheduler determines which thread runs based on priorities.
○ Two main approaches:
■ Preemptive Scheduling: Higher-priority threads preempt lower-priority
threads.
■ Time-Slicing: Threads share CPU time in a round-robin manner.
Thread Synchronization
Synchronization ensures that multiple threads can access shared resources without conflicts.
Why Needed?
● To prevent race conditions, where multiple threads modify shared data simultaneously,
leading to inconsistent results.
1. Synchronized Methods:
synchronized (object) {
// Critical section
}
4.
Example:
class Counter {
private int count = 0;
t1.start();
t2.start();
t1.join();
t2.join();
Inter-Thread Communication
Inter-thread communication allows threads to communicate and coordinate tasks using methods
like wait(), notify(), and notifyAll().
Key Points:
● wait(): A thread releases the lock and enters the waiting state.
● notify(): Wakes up one thread waiting on the same object.
● notifyAll(): Wakes up all threads waiting on the same object.
class SharedResource {
private int value = 0;
private boolean available = false;
producer.start();
consumer.start();
}
}
Summary
Exceptions:
Multithreading:
1. Introduction to Multithreading
Definition:
Multithreading in Java is the concurrent execution of multiple threads (independent units of a
program). Threads share the same memory space but execute independently.
● Create a class that extends the Thread class and overrides the run() method.
● Start the thread using the start() method.
Example:
● Create a class that implements the Runnable interface and defines the run() method.
● Pass the instance of this class to a Thread object and call start().
Example:
Thread Priorities
1. Priority Levels:
Example:
t1.setPriority(Thread.MIN_PRIORITY); // Priority 1
t2.setPriority(Thread.MAX_PRIORITY); // Priority 10
t1.start();
t2.start();
}
}
Thread Scheduling
1. Preemptive Scheduling:
○ Higher-priority threads interrupt lower-priority threads.
2. Time-Slicing:
○ Threads of the same priority share CPU time in a round-robin fashion.
1. New:
○Thread is ready to execute after calling start(), but it may not be running if
CPU is busy.
○ Example: t.start();
3. Running:
4. Thread Synchronization
Definition:
Thread synchronization ensures that multiple threads access shared resources without
conflicts, avoiding race conditions.
Types of Synchronization
1. Synchronized Methods:
○ Ensures that only one thread can execute a method of an object at a time.
○ Declared using the synchronized keyword.
Example:
class Counter {
private int count = 0;
t1.start();
t2.start();
t1.join();
t2.join();
2. Synchronized Blocks:
○ Synchronizes a specific block of code rather than the entire method.
Example:
class SharedResource {
void display(String message) {
synchronized (this) {
System.out.println("[");
System.out.println(message);
System.out.println("]");
}
}
}
public class SynchronizedBlockExample {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
t1.start();
t2.start();
}
}
3. Static Synchronization:
○ Used for synchronizing static methods.
○ Locks the class object rather than an instance.
Example:
class SharedResource {
public static synchronized void staticDisplay(String message) {
System.out.println("[");
System.out.println(message);
System.out.println("]");
}
}
5. Inter-Thread Communication
Java provides methods like wait(), notify(), and notifyAll() for communication
between threads.
Methods:
1. wait(): Causes the current thread to wait until another thread calls notify() or
notifyAll() on the same object.
2. notify(): Wakes up one thread waiting on the object's monitor.
3. notifyAll(): Wakes up all threads waiting on the object's monitor.
Summary
Multithreading Concepts: