0% found this document useful (0 votes)
42 views34 pages

Understanding Java Threads and Multi-threading

The document provides an overview of threading in Java, including concepts like threads, multi-threading, and the differences between multi-threading and multi-tasking. It explains thread lifecycle states, methods for creating threads, synchronization mechanisms, and examples of thread management in applications such as banking transactions and inventory management. Additionally, it covers event handling in Java using AWT and Swing, along with listener interfaces and event delegation models.

Uploaded by

yashwanth18.d
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)
42 views34 pages

Understanding Java Threads and Multi-threading

The document provides an overview of threading in Java, including concepts like threads, multi-threading, and the differences between multi-threading and multi-tasking. It explains thread lifecycle states, methods for creating threads, synchronization mechanisms, and examples of thread management in applications such as banking transactions and inventory management. Additionally, it covers event handling in Java using AWT and Swing, along with listener interfaces and event delegation models.

Uploaded by

yashwanth18.d
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

Thread:

A thread is the smallest unit of execution within a process. It allows concurrent execution of
multiple parts of a program. Threads share memory within a process, making them lightweight
compared to processes that require separate memory.

Multi-threading

Multi-threading is the ability of a program to execute multiple threads simultaneously,


improving performance and responsiveness.

Difference between Multi-threading and Multi-tasking

Feature Multi-threading Multi-tasking

Execution Multiple threads in one process Multiple processes running separately

Resource usage Shares memory within a process Uses more system resources

Speed Faster due to shared memory Slower due to process switching

Example Running multiple tasks in one app Running multiple applications

Threads creation

Threads can be created in two ways:

1. Extending Thread class

2. Implementing Runnable interface

class MyThread extends Thread {

public void run() {

[Link]("Thread is running...");

public static void main(String[] args) {

Thread t = new Thread();

[Link]();

}}
Output:

Thread is running...

Thread Lifecycle

New (Created): The thread is created but not started. (Thread t = new Thread();)
Runnable: The thread is ready to run but waiting for CPU allocation. ([Link]();)

Blocked: The thread is waiting to acquire a lock.

Waiting: The thread is waiting indefinitely for another thread to signal it. (wait())

Timed Waiting: The thread waits for a specified time (sleep(), join(time), wait(time)).

Terminated: The thread has finished execution.

run() and start() methods? Can we use only run()?

• The start() method is used to start a new thread and calls the run() method internally.

• If we call run() directly instead of start(), it will execute in the main thread rather than
creating a new one.

Example:

class MyThread extends Thread {

public void run() {

[Link]("Thread is running...");

public class Main {

public static void main(String[] args) {

MyThread t = new MyThread();

[Link](); // Creates a new thread

// [Link](); // Runs in the main thread

}
Difference Between AWT and Swing

Feature AWT (Abstract Window Toolkit) Swing ([Link])

Components Heavyweight (OS-dependent) Lightweight (pure Java)

Look and Feel Native OS-based UI Customizable UI

Performance Slower due to OS calls Faster since it runs on JVM

Extensibility Less flexible More flexible and feature-rich

Thread Safety Not thread-safe Mostly thread-safe

Java Graphics Method to Draw "Hello World" at (100,200)

import [Link].*;

public class HelloWorldGraphics extends Frame {

public HelloWorldGraphics() {

setSize(400, 400);

setVisible(true);

public void paint(Graphics g) {

[Link]("Hello World", 100, 200);

public static void main(String[] args) {

new HelloWorldGraphics();

}
UI Components in AWT

Some commonly used AWT components are:

• Button

• Label

• TextField

• TextArea

• Checkbox

• CheckboxGroup

• Choice (Dropdown)

• List

• Canvas

• ScrollPane

• Panel

• Frame

Listener Methods for KeyListener Interface

The KeyListener interface has the following methods:

void keyPressed(KeyEvent e); // Invoked when a key is pressed

void keyReleased(KeyEvent e); // Invoked when a key is released

void keyTyped(KeyEvent e); // Invoked when a key is typed

Java uses the Event Delegation Model to handle events. It consists of:

• Event Source: The component that generates an event (e.g., Button, TextField).

• Event Listener: The interface that listens to events (e.g., ActionListener,


MouseListener).

• Event Object: The event itself (e.g., ActionEvent, MouseEvent).


Java Program for Mouse Event Handling

import [Link].*;

import [Link].*;

public class MouseEventDemo extends Frame implements MouseListener {

String msg = "";

public MouseEventDemo() {

addMouseListener(this);

setSize(400, 400);

setVisible(true);

public void paint(Graphics g) {

[Link](msg, 100, 200);

public void mouseClicked(MouseEvent e) {

msg = "Mouse Clicked";

repaint();

Relationship between an event- listener interface and an event adapter class


1. Event Listener Interface
• In Java, an event listener interface defines methods that must be implemented to handle
specific events.
• Example: MouseListener, KeyListener, WindowListener, etc.
• If you implement a listener interface, you must override all methods, even if you need
only one.
2. Event Adapter Class
• An event adapter class is a pre-defined helper class that provides empty (default)
implementations for all methods of a listener interface.
• If you extend an adapter class, you can override only the required methods instead of
implementing all.
Thread Synchronization:
Synchronization in Java is a mechanism that ensures that multiple threads do not access shared
resources simultaneously, which can lead to data inconsistency. It is typically implemented
using the synchronized keyword or Lock classes from [Link].
Synchronization helps in maintaining thread safety in multithreaded applications.

there are two ways to create a thread:

1. Extending the Thread class

• In this method, a class extends the Thread class and overrides the run() method.

• The thread is started using the start() method.

Example:

class MyThread extends Thread {

public void run() {

for (int i = 1; i <= 5; i++) {

[Link]("Thread: " + i);

try {

[Link](500); // Pause for 500ms

} catch (InterruptedException e) {

[Link](e);

} }}}

public class ThreadExample {

public static void main(String[] args) {

MyThread t1 = new MyThread();

[Link](); // Start the thread

}
• MyThread extends Thread and overrides the run() method.

• start() calls run() internally and creates a new thread.

2. Implementing the Runnable Interface

• The class implements Runnable and overrides the run() method.

• A Thread object is created by passing the Runnable instance.

Example:

class MyRunnable implements Runnable {

public void run() {

for (int i = 1; i <= 5; i++) {

[Link]("Runnable Thread: " + i);

try {

[Link](500);

} catch (InterruptedException e) {

[Link](e);

}}}}

public class RunnableExample {

public static void main(String[] args) {

MyRunnable obj = new MyRunnable();

Thread t1 = new Thread(obj); // Pass the Runnable object to Thread

[Link]();

• MyRunnable implements Runnable and overrides run().

• A Thread object is created using new Thread(obj).

• start() method is used to run the thread.


Thread lifecycle

A thread in Java goes through five states in its lifecycle:

1. New (Created)
• A thread is in this state when it is created but has not started yet.
• This happens when you create a Thread object but do not call start().
Thread t = new Thread();
2. Runnable
• The thread moves to the runnable state when start() is called.
• It is ready to run, but the CPU may or may not schedule it immediately.
[Link](); // Moves to Runnable state
3. Running
• The thread is in the running state when it is executing the run() method.
• The CPU scheduler selects it for execution.
public void run() {
[Link]("Thread is running...");
}
4. Blocked/Waiting
• A thread moves to this state when it is waiting for a resource (e.g., I/O, lock).
• Example cases:
o Blocked: Waiting to acquire a lock.
o Waiting: Waiting indefinitely for another thread to notify it (wait()).
o Timed Waiting: Waiting for a specific amount of time (sleep(time),
join(time)).
[Link](1000); // Timed Waiting
synchronized(obj) {
[Link](); // Waiting
}
5. Terminated (Dead)
• The thread moves to the terminated state when it finishes execution.
• It cannot be restarted.
public void run() {
[Link]("Thread finished!");
}
Various Thread Methods
1. Thread Creation & Start

Method Description

start() Starts the thread and moves it to Runnable state.

run() The method executed when the thread starts.

2. Thread Control

Method Description

sleep(ms) Pauses the thread for a specific time (in milliseconds).

yield() Allows other threads of the same priority to execute.

join() Waits for another thread to finish execution.

3. Synchronization & Communication


Method Description

wait() The thread waits until another thread calls notify().

notify() Wakes up a single waiting thread.

notifyAll() Wakes up all waiting threads.

4. Thread State Checking

Method Description

isAlive() Checks if the thread is still running.

getState() Returns the current state of the thread.

5. Thread Priority

Method Description

Sets thread priority (MIN_PRIORITY = 1,


setPriority(int p)
NORM_PRIORITY = 5, MAX_PRIORITY = 10).

getPriority() Returns the thread priority.

Example Program Demonstrating Thread Lifecycle


class MyThread extends Thread {
public void run() {
[Link]("Thread is running...");
try {
[Link](2000); // Moves to Timed Waiting
} catch (InterruptedException e) {
[Link](e);
}
[Link]("Thread finished!");
}
}

public class ThreadLifecycleExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]("Thread State: " + [Link]()); // New
[Link]();
[Link]("Thread State after start(): " + [Link]()); // Runnable
try {
[Link](100);
[Link]("Thread State while sleeping: " + [Link]()); // Timed
Waiting
[Link](); // Wait for t1 to finish
} catch (InterruptedException e) {
[Link](e);
}
[Link]("Thread State after completion: " + [Link]()); // Terminated
}
}
Output:
Thread State: NEW
Thread State after start(): RUNNABLE
Thread is running...
Thread State while sleeping: TIMED_WAITING
Thread finished!
Thread State after completion: TERMINATED

Write a java program that synchronizes three different threads of the same program
and displays the contents of the text supplies through the threads.

class BankAccount {
private int balance = 1000; // Initial balance
// Synchronized method to withdraw money
synchronized void withdraw(int amount) {
if (balance >= amount) {
[Link]([Link]().getName() + " is withdrawing " +
amount);
balance -= amount;
[Link]("New balance after withdrawal: " + balance);
} else {
[Link]([Link]().getName() + " - Insufficient
funds!");
}
}
// Synchronized method to deposit money
synchronized void deposit(int amount) {
[Link]([Link]().getName() + " is depositing " +
amount);
balance += amount;
[Link]("New balance after deposit: " + balance);
}
int getBalance() {
return balance;
}
}
// Runnable class for withdrawing money
class WithdrawTask implements Runnable {
private BankAccount account;
private int amount;
public WithdrawTask(BankAccount account, int amount) {
[Link] = account;
[Link] = amount;
}
public void run() {
[Link](amount);
}
}
// Runnable class for depositing money
class DepositTask implements Runnable {
private BankAccount account;
private int amount;
public DepositTask(BankAccount account, int amount) {
[Link] = account;
[Link] = amount;
}
public void run() {
[Link](amount);
}
}
public class BankTransactionExample {
public static void main(String[] args) {
BankAccount account = new BankAccount();
// Creating Runnable objects
WithdrawTask withdrawTask = new WithdrawTask(account, 800);
DepositTask depositTask = new DepositTask(account, 500);
// Creating Threads and assigning Runnable objects
Thread t1 = new Thread(withdrawTask, "Thread 1");
Thread t2 = new Thread(depositTask, "Thread 2");
// Starting Threads
[Link]();
[Link]();
try {
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted");
}
[Link]("Final Balance: " + [Link]());
}}
Output:

Thread 1 is withdrawing 800

New balance after withdrawal: 200

Thread 2 is depositing 500

New balance after deposit: 700

Final Balance: 700

Java program that demonstrates the inventory problem using threads, synchronization
(synchronized keyword), and inter-thread communication (wait() and notify()).

• Stock: A shared resource that maintains the inventory.

• Producer: Adds items to the stock.

• Consumer: Removes items from the stock.

• Synchronization: Ensures proper handling of shared resources.

• Inter-thread communication: Prevents unnecessary waiting using wait() and notify().

Program

class Stock {

private int items = 0; // Current inventory count

private final int capacity = 5; // Maximum capacity

// Synchronized method for adding items to stock

public synchronized void produce() {

while (items == capacity) {

try {

[Link]("Stock is full. Producer is waiting...");

wait(); // Wait until items are consumed

} catch (InterruptedException e) {

[Link](e);

}
}

items++;

[Link]("Producer added an item. Current stock: " + items);

notify(); // Notify the consumer

// Synchronized method for consuming items from stock

public synchronized void consume() {

while (items == 0) {

try {

[Link]("Stock is empty. Consumer is waiting...");

wait(); // Wait until items are produced

} catch (InterruptedException e) {

[Link](e);

items--;

[Link]("Consumer removed an item. Current stock: " + items);

notify(); // Notify the producer

// Producer class implementing Runnable

class Producer implements Runnable {

private Stock stock;

public Producer(Stock stock) {

[Link] = stock;
}

public void run() {

for (int i = 0; i < 10; i++) {

[Link]();

try {

[Link](500); // Simulate production delay

} catch (InterruptedException e) {

[Link](e);

}}}}

// Consumer class implementing Runnable

class Consumer implements Runnable {

private Stock stock;

public Consumer(Stock stock) {

[Link] = stock;

public void run() {

for (int i = 0; i < 10; i++) {

[Link]();

try {

[Link](700); // Simulate consumption delay

} catch (InterruptedException e) {

[Link](e);

}}}}
// Main class

public class InventoryProblem {

public static void main(String[] args) {

Stock stock = new Stock();

Producer producer = new Producer(stock);

Consumer consumer = new Consumer(stock);

Thread producerThread = new Thread(producer, "Producer Thread");

Thread consumerThread = new Thread(consumer, "Consumer Thread");

[Link]();

[Link]();

try {

[Link]();

[Link]();

} catch (InterruptedException e) {

[Link]("Main thread interrupted");

[Link]("Inventory processing completed.");

Explanation

1. Stock Class (Shared Resource)

o produce(): Adds an item if not full. If full, waits for space.

o consume(): Removes an item if available. If empty, waits for items.

o Uses synchronized, wait(), and notify() for thread synchronization.


2. Producer Class

o Calls [Link]() to add items.

o Sleeps for 500ms to simulate time taken for production.

3. Consumer Class

o Calls [Link]() to remove items.

o Sleeps for 700ms to simulate time taken for consumption.

4. Main Class

o Creates Stock, Producer, and Consumer.

o Starts two threads: producerThread and consumerThread.

o Uses join() to wait for threads to finish.

Output

Producer added an item. Current stock: 1

Producer added an item. Current stock: 2

Consumer removed an item. Current stock: 1

Producer added an item. Current stock: 2

Consumer removed an item. Current stock: 1

Producer added an item. Current stock: 2

Producer added an item. Current stock: 3

Consumer removed an item. Current stock: 2

Producer added an item. Current stock: 3

Consumer removed an item. Current stock: 2

Producer added an item. Current stock: 3

Producer added an item. Current stock: 4

Producer added an item. Current stock: 5

Stock is full. Producer is waiting...


Consumer removed an item. Current stock: 4

Producer added an item. Current stock: 5

Consumer removed an item. Current stock: 4

Consumer removed an item. Current stock: 3

Consumer removed an item. Current stock: 2

Consumer removed an item. Current stock: 1

Consumer removed an item. Current stock: 0

Stock is empty. Consumer is waiting...

Producer added an item. Current stock: 1

...

Inventory processing completed.

Event Delegation Model

The Event Delegation Model is a mechanism in Java where event handling is delegated to a
separate object known as a listener. Instead of handling events in the source component itself,
Java follows a "publish-subscribe" model, where:

1. An event source (like a button) generates events.

2. A listener object listens for these events.

3. An event-handling method in the listener processes the event.

This model improves efficiency by avoiding unnecessary event handling and making the code
more modular.

How It Works?

1. Event Source

o Generates events (e.g., a Button click).

o Registers a listener.

2. Event Listener

o Implements a specific event interface.


o Defines event-handling methods.

3. Event Object

o Carries event-related information.

Example Flow:

• When a user clicks a button (source), an ActionEvent is generated.

• The event gets passed to the registered ActionListener.

• The actionPerformed() method inside the ActionListener handles the event.

Event Classes in Java

Java provides several event classes inside the [Link] package. These classes represent
different types of events.

Event Class Description

ActionEvent Generated when a button is clicked, menu item is selected, etc.

Represents mouse actions like clicks, movement, entering/exiting a


MouseEvent
component.

KeyEvent Represents keyboard actions (key press, release, typing).

WindowEvent Used for window-related events (open, close, minimize, etc.).

ItemEvent Generated when a checkbox, radio button, or list item is selected/deselected.

FocusEvent Indicates when a component gains or loses focus.

TextEvent Fired when the value of a text field or text area changes.

AdjustmentEvent Occurs when scrollbar values change.

ComponentEvent Generated when a component is resized, shown, hidden, or moved.

ContainerEvent Occurs when a component is added or removed from a container.


Event Interfaces in Java

Java provides several event listener interfaces that must be implemented to handle events. These
interfaces are part of the [Link] package.

Listener Interface Description

ActionListener Handles button clicks and menu selections (actionPerformed()).

Handles mouse events like clicks, entering, exiting (mouseClicked(),


MouseListener
mouseEntered(), etc.).

MouseMotionListener Tracks mouse movement (mouseMoved(), mouseDragged()).

KeyListener Handles keyboard events (keyPressed(), keyReleased(), keyTyped()).

Listens for window events like closing, opening, minimizing


WindowListener
(windowClosing(), windowOpened(), etc.).

ItemListener Listens for checkbox and radio button changes (itemStateChanged()).

FocusListener Handles focus gained/lost events (focusGained(), focusLost()).

Detects component resize, show, hide, and move


ComponentListener
(componentResized(), etc.).

Listens for components being added/removed (componentAdded(),


ContainerListener
componentRemoved()).

Example: Implementing Event Delegation Model

Below is a simple Java program that demonstrates the event delegation model using
ActionListener with AWT.

import [Link].*;

import [Link].*;

class EventDelegationExample extends Frame implements ActionListener {

Button button;

EventDelegationExample() {
// Create a button

button = new Button("Click Me");

// Set button position and size

[Link](100, 100, 100, 50);

// Register the event listener

[Link](this);

// Add button to frame

add(button);

// Frame settings

setSize(300, 300);

setLayout(null);

setVisible(true);

// Implement the event handler method

public void actionPerformed(ActionEvent e) {

[Link]("Button Clicked!");

public static void main(String[] args) {

new EventDelegationExample();

1. Frame is created with a button.

2. Event listener (ActionListener) is registered using [Link](this).

3. actionPerformed() is executed when the button is clicked.

4. Window closing is handled using WindowAdapter.


Output

When you click the "Click Me" button, the console prints:

Button Clicked!

Different layout in Java GUI. Which layout is the default one

In Java AWT, layout managers are used to arrange components (such as buttons, labels, text
fields) inside a container (Frame, Panel, etc.). Layout managers automatically handle
component positioning and resizing, making GUI design more flexible and platform-
independent.

1. FlowLayout (Default for Panel)

• Arranges components from left to right, wrapping to the next row when space runs out.

• Can be aligned left, center (default), or right.

• Components maintain their preferred size.

Constructors:

FlowLayout() // Default: center alignment, 5px horizontal & vertical gap

FlowLayout(int align) // LEFT, CENTER, RIGHT

FlowLayout(int align, int hgap, int vgap) // Custom gaps

2. BorderLayout (Default for Frame, Dialog, Window)

• Divides the container into five regions:

o NORTH, SOUTH, EAST, WEST, CENTER

• Each region can hold one component.

• Components in NORTH & SOUTH expand horizontally, EAST & WEST expand
vertically, and CENTER fills the remaining space.

Constructors:

BorderLayout() // Default: 0px horizontal & vertical gap

BorderLayout(int hgap, int vgap) // Custom gaps


3. GridLayout

• Arranges components in a grid (rows & columns).

• Each cell in the grid is equal in size.

• Components are placed row-wise from left to right.

Constructors:

GridLayout(int rows, int cols) // Default: no gaps

GridLayout(int rows, int cols, int hgap, int vgap) // Custom gaps

4. CardLayout

• Works like a stack of cards, showing only one component at a time.

• Useful for tabbed interfaces or wizard-style forms.

Constructors:

CardLayout()

CardLayout(int hgap, int vgap) // Custom gaps

5. GridBagLayout

• More flexible than GridLayout, allowing different component sizes.

• Requires GridBagConstraints to specify component position and behavior.

[Link] = 0; // Column index [Link] = 0; // Row index [Link] = 1; // Number of


columns the component spans [Link] = 1; // Number of rows the component spans

6. Null Layout (Manual Positioning)

• No layout manager; components are placed manually using setBounds(x, y, width,


height).

• Not recommended due to difficulty in handling resizing.

1. FlowLayout Example Output

[Button 1] [Button 2] [Button 3]

• Buttons are arranged left to right.


• If the window is resized, buttons may wrap to the next row.

2. BorderLayout Example Output

-----------------------

| North |

-----------------------

| West | Center | East |

-----------------------

| South |

-----------------------

• North and South buttons stretch horizontally.

• East and West buttons stretch vertically.

• Center expands to fill remaining space.

3. GridLayout Example Output

-----------------

| Button 1 | Button 2 |

-----------------

| Button 3 | Button 4 |

-----------------

• Equally sized buttons in a 2×2 grid.

• All buttons resize equally when the window resizes.

4. CardLayout Example Output

Initially

[ Card 1 ]

• Only Card 1 is visible.


After Clicking the Button

[ Card 2 ]

• [Link](f); switches to Card 2.

After Another Click

[ Card 3 ]

• Switches to Card 3.

• After the next click, it loops back to Card 1.

5. GridBagLayout Example Output

-----------------------

| Button 1 | Button 2 |

-----------------------

| Button 3 (spans 2 columns) |

-----------------------

• Button 3 spans two columns.

• Other buttons take equal space.

6. Null Layout Example Output

(Empty window with one button)

[ Click Me ] // Positioned manually at (50,50)

• Button is placed at (50,50) manually.

• Window resizing does not affect button position.

java program that have 11 text fields one submit button. When you press the button first
10 text field’s average has to be displayed in the 11th text field.

import [Link].*;

import [Link].*;

public class SimpleAverageCalculator {


public static void main(String[] args) {

// Create frame

Frame frame = new Frame("Average Calculator");

[Link](400, 300);

[Link](new FlowLayout());

// Create 10 input text fields and 1 result text field

TextField[] textFields = new TextField[11];

for (int i = 0; i < 11; i++) {

textFields[i] = new TextField(5);

[Link](textFields[i]);

// 11th field should be read-only

textFields[10].setEditable(false);

// Create Submit button

Button submitButton = new Button("Calculate Average");

[Link](submitButton);

// Directly implementing ActionListener

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

double sum = 0;

int count = 0;

// Read values from first 10 text fields

for (int i = 0; i < 10; i++) {

try {

sum += [Link](textFields[i].getText());
count++;

} catch (NumberFormatException ex) {

textFields[10].setText("Error");

return;

// Calculate and display average

textFields[10].setText([Link]("%.2f", sum / count));

});

// Show frame

[Link](true);

How will you display an image on the frame in a window using java?
ImageIO methods from [Link] are commonly used for reading and writing
images in Java.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class ImageDisplay extends Frame {
BufferedImage img;
// Constructor
public ImageDisplay() {
try {
img = [Link](new File("[Link]")); // Load image using ImageIO
} catch (IOException e) {
[Link]("Image not found!");
}
// Set frame properties
setSize(500, 500);
setVisible(true);

// Override paint() method to draw image


public void paint(Graphics g) {
if (img != null) {
[Link](img, 50, 50, this); // Draw image at (50,50)
}
}
public static void main(String[] args) {
new ImageDisplay(); // Create frame instance
}}

MouseListener and MouseMotionListener in Java


In Java AWT (Abstract Window Toolkit), we use MouseListener and MouseMotionListener
to handle mouse events in a GUI application.

1. MouseListener
The MouseListener interface is used to handle mouse click-related events. It provides the
following five methods:

Method Description

mouseClicked(MouseEvent e) Invoked when the mouse is clicked (pressed and released).

mousePressed(MouseEvent e) Invoked when a mouse button is pressed.

mouseReleased(MouseEvent e) Invoked when a mouse button is released.

mouseEntered(MouseEvent e) Invoked when the mouse enters a component.

mouseExited(MouseEvent e) Invoked when the mouse exits a component.


2. MouseMotionListener
The MouseMotionListener interface is used to handle mouse movement-related events. It
has two methods:

Method Description

mouseMoved(MouseEvent e) Invoked when the mouse moves over a component.

mouseDragged(MouseEvent Invoked when the mouse is dragged while a button is


e) pressed.

Example Program Using Both Listeners


import [Link].*;
import [Link].*;
public class MouseEventExample extends Frame implements MouseListener,
MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0;
public MouseEventExample()
{
setSize(500, 500);
setTitle("Mouse Event Example");
setVisible(true);
// Add mouse listeners
addMouseListener(this);
addMouseMotionListener(this);}

// Implementing MouseListener methods


public void mouseClicked(MouseEvent e) {
msg = "Mouse Clicked";
repaint();
}

public void mousePressed(MouseEvent e) {


msg = "Mouse Pressed";
repaint();
}

public void mouseReleased(MouseEvent e) {


msg = "Mouse Released";
repaint();
}

public void mouseEntered(MouseEvent e) {


msg = "Mouse Entered";
repaint();
}

public void mouseExited(MouseEvent e) {


msg = "Mouse Exited";
repaint();
}
// Implementing MouseMotionListener methods
public void mouseMoved(MouseEvent e) {
msg = "Mouse Moved";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
public void mouseDragged(MouseEvent e) {
msg = "Mouse Dragged";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
// Overriding paint() method to display messages
public void paint(Graphics g) {
[Link](new Font("Arial", [Link], 16));
[Link](msg, mouseX, mouseY);
}
public static void main(String[] args) {
new MouseEventExample();
}
}

Explanation of the Code


1. Frame Initialization:
o MouseEventExample extends Frame to create a GUI window.
o The window size is set to 500x500 pixels.
2. Adding Mouse Listeners:
o addMouseListener(this); → Registers MouseListener to handle mouse clicks
and entry/exit events.
o addMouseMotionListener(this); → Registers MouseMotionListener to track
mouse movement and dragging.
3. Handling Mouse Events:
o mouseClicked(), mousePressed(), mouseReleased(), mouseEntered(), and
mouseExited() update the msg variable and call repaint().
o mouseMoved() and mouseDragged() update mouseX and mouseY to track
mouse movement.
4. Overriding paint(Graphics g):
o Displays the message (msg) at the latest mouse position (mouseX, mouseY).
5. Closing the Window:
o A WindowAdapter is used to close the frame when the user clicks the close
(X) button.
How It Works
1. Run the program. A window appears.
2. Move or click the mouse inside the window:
o Clicking displays "Mouse Clicked" at the clicked position.
o Moving the mouse displays "Mouse Moved" at the current position.
o Dragging displays "Mouse Dragged" at the dragged position.
o Entering or exiting the window displays "Mouse Entered" or "Mouse
Exited".

Code a java program to implement the following: Create four check boxes. The initial
state of the first box should be in the checked state. The status of each checkbox should be
displayed. when we change the state of a check box, status should be display is updated

import [Link].*;
import [Link].*;
public class CheckboxExample extends Frame implements ItemListener {
Checkbox checkbox1, checkbox2, checkbox3, checkbox4;
Label statusLabel;
public CheckboxExample() {
// Set up frame
setTitle("Checkbox Example");
setSize(300, 200);
setLayout(new FlowLayout());

// Create checkboxes
checkbox1 = new Checkbox("Option 1", true); // Initially checked
checkbox2 = new Checkbox("Option 2");
checkbox3 = new Checkbox("Option 3");
checkbox4 = new Checkbox("Option 4");
// Create label to display checkbox status
statusLabel = new Label("Option 1: Checked, Option 2: Unchecked, Option 3:
Unchecked, Option 4: Unchecked");
// Add item listeners directly
[Link](this);
[Link](this);
[Link](this);
[Link](this);
// Add components to frame
add(checkbox1);
add(checkbox2);
add(checkbox3);
add(checkbox4);
add(statusLabel);
// Make frame visible
setVisible(true);
}
// Handle item state changes
public void itemStateChanged(ItemEvent e) {
String status = "Option 1: " + ([Link]() ? "Checked" : "Unchecked")
+ ", " +
"Option 2: " + ([Link]() ? "Checked" : "Unchecked") + ", "
+
"Option 3: " + ([Link]() ? "Checked" : "Unchecked") + ", "
+
"Option 4: " + ([Link]() ? "Checked" : "Unchecked");
[Link](status);
}
public static void main(String[] args) {
new CheckboxExample();
}}
Initial Output (When the window opens):
A window appears with:
• Four checkboxes:
Option 1 (Initially checked)
Option 2 (Unchecked)
Option 3 (Unchecked)
Option 4 (Unchecked)
• A label at the bottom displaying:

Option 1: Checked, Option 2: Unchecked, Option 3: Unchecked,


Option 4: Unchecked

You might also like