0% found this document useful (0 votes)
8 views50 pages

Module IV Multithreading, Event Handling

The document covers multithreading and event handling in Java, explaining concepts such as thread lifecycle, creation methods (implementing Runnable interface and extending Thread class), and thread synchronization. It details the states of a thread (New, Runnable, Running, Blocked, Terminated) and provides examples of multithreaded applications, including inter-thread communication methods like wait(), notify(), and notifyAll(). Additionally, it discusses thread priorities and the importance of efficient CPU usage through multithreading.

Uploaded by

mannnybabe3307
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)
8 views50 pages

Module IV Multithreading, Event Handling

The document covers multithreading and event handling in Java, explaining concepts such as thread lifecycle, creation methods (implementing Runnable interface and extending Thread class), and thread synchronization. It details the states of a thread (New, Runnable, Running, Blocked, Terminated) and provides examples of multithreaded applications, including inter-thread communication methods like wait(), notify(), and notifyAll(). Additionally, it discusses thread priorities and the importance of efficient CPU usage through multithreading.

Uploaded by

mannnybabe3307
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

CGB1201-JAVA PROGRAMMING

Module IV
MULTITHREADING , EVENT HANDLING
Syllabus

Multithreading Thread life cycle Creating Threads Inter-thread


Communication - Java AWT & Event handling mechanisms-Java Swing

Multithreading in java :
Multithreading in Java is a process of executing multiple threads simultaneously.

What are Threads in Java?


● In java, a thread is a lightweight process.
● Every java program executes by a thread called the main thread.
● When a java program gets executed, the main thread is created automatically.
● All other threads called from the main thread..
● A thread class belongs to [Link] package.
● When an application first begins, user thread is created.

Module IV Page 1
CGB1201-JAVA PROGRAMMING

● Threads consume CPU in the best possible manner, hence enables multi
processing. Multi threading reduces idle time of CPU which improves performance
of application.

Single Thread Example:

package demotest;

public class singleThread


{
public static void main(String[] args)
{
[Link]("Single Thread");
}
}

What is Multithreading in Java?


● Multithreading in Java is a process of executing two or more threads
simultaneously to maximum utilization of CPU.
● Multithreaded applications execute two or more threads run concurrently. Hence, it
is also known as Concurrency in Java.
● Each thread runs parallel to each other.
● Multiple threads don’t allocate separate memory area, hence they save memory.
● Also, context switching between threads takes less time.

How to create a thread in Java


There are two ways to create a thread:

1. By implementing Runnable interface.


Module IV Page 2
CGB1201-JAVA PROGRAMMING

2. By extending Thread class

1. Implementing Runnable interface

The java contains a built-in interface Runnable inside the [Link] package.

The Runnable interface implemented by the Thread class that contains all the methods that
are related to the threads.

To create a thread using Runnable interface, follow the step given below.

● Step-1: Create a class that implements Runnable interface.


● Step-2: Override the run( ) method with the code that is to be executed by the
thread. The run( ) method must be public while overriding.
● Step-3: Create the object of the newly created class in the main( ) method.
● Step-4: Create the Thread class object by passing above created object as parameter
to the Thread class constructor.
● Step-5: Call the start( ) method on the Thread class object created in the above step.

Look at the following example program.

class SampleThread implements Runnable{

public void run() {


[Link]("Thread is under Running...");
}
}

public class MyThreadTest {

public static void main(String[] args) {


SampleThread threadObject = new SampleThread();
Thread t = new Thread(threadObject);
[Link]("Thread about to start...");
[Link]();
}
}

Output
Module IV Page 3
CGB1201-JAVA PROGRAMMING

Thread about to start…


Thread is under Running...

[Link] Thread class:

Thread class provide constructors and methods to create and perform operations on
a [Link] class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

● Thread( )

● Thread( String threadName )

● Thread( Runnable objectName )

● Thread( Runnable objectName, String threadName )

Extending Thread class


The java contains a built-in class Thread inside the [Link] package. The Thread
class contains all the methods that are related to the threads.

To create a thread using Thread class, follow the step given below.

● Step-1: Create a class as a child of Thread class. That means, create a class that
extends Thread class.
● Step-2: Override the run( ) method with the code that is to be executed by the
thread. The run( ) method must be public while overriding.
● Step-3: Create the object of the newly created class in the main( ) method.
● Step-4: Call the start( ) method on the object created in the above step.

Look at the following example program.

class SampleThread extends Thread{

public void run() {


[Link]("Thread is under Running...");

Module IV Page 4
CGB1201-JAVA PROGRAMMING

}
}

public class MyThreadTest {

public static void main(String[] args) {


SampleThread t1 = new SampleThread();
[Link]("Thread about to start...");
[Link]();
}
}

Output

Thread about to start…


Thread is under Running...

Thread Class Methods

Thread class also defines many methods for managing threads. Some of them are,

Method Description

setName() to give thread a name

getName() return thread's name

getPriority() return thread's priority

isAlive() checks if thread is still running or not

join() Wait for a thread to end

run() Entry point for a thread

sleep() suspend thread for a specified time

Module IV Page 5
CGB1201-JAVA PROGRAMMING

start() start a thread by calling run() method

currentThread() Returns a reference to the currently executing thread object.

interrupt() Interrupts this thread.

interrupted() Tests whether the current thread has been interrupted.

setPriority(int Changes the priority of this thread.


newPriority)

The Thread class in java also contains methods like stop( ), destroy( ), suspend( ), and
resume( ). But they are deprecated.

Example program for Multithreading :

// Two threads performing two tasks at a time.


public class MyThread extends Thread
{
String task; // Declare a String variable to represent the task.
MyThread(String task)
{
[Link] = task;
}
public void run()
{
for(int i = 1; i <= 5; i++)
{
[Link](task+ " : " +i);
try

Module IV Page 6
CGB1201-JAVA PROGRAMMING

{
[Link](1000); // Pause the thread execution for 1000
milliseconds.
}
catch(InterruptedException e) {
[Link]([Link]());
}
}
}
public static void main(String[] args)
{
MyThread t1 = new MyThread("Cut the ticket");
MyThread t2 = new MyThread("Show your seat number");
[Link]();
[Link]();
}
}

Output:

Cut the ticket : 1


Show your seat number : 1
Cut the ticket : 2
Show your seat number : 2
Cut the ticket : 3
Show your seat number : 3
Cut the ticket : 4
Show your seat number : 4
Cut the ticket : 5
Show your seat number : 5

Module IV Page 7
CGB1201-JAVA PROGRAMMING

Explanation:

1. In the preceding example program, we have created two threads on two objects of
MyThread class. Here, we created two objects to represent two tasks. When we will run the
above program, the main thread starts running immediately. Two threads will generate
from the main thread that will perform two different tasks.

2. When [Link](); is executed by JVM, it starts execution of code inside run() method and
print the statement “Cut the ticket” on the console.

3. When JVM executes [Link](1000); inside the try block, it pauses the thread
execution for 1000 milliseconds. Here. sleep() method is a static method that is used to
pauses the execution of thread for a specified amount of time.

For example, [Link](1000); will pause the execution of thread for 1000 milliseconds
(1 sec). 1000 milliseconds means 1 second. Since sleep() method can throw an exception
named InterruptedException, we will catch it into catch block.

4. Meanwhile, JVM executes [Link](); and second thread starts execution of code inside the
run() method almost simultaneously. It will print the statement “Show your seat number”.
Now, the second thread will undergo to sleep for 1000 milliseconds.

5. When the pause time period of the first thread is elapsed, it will reenter into running
state and starts the execution of code inside run() method. The same process will also
happen for second thread. In this manner, both threads will perform two tasks almost
simultaneously.

Life cycle of a Thread (Thread States)


In Java, a thread always exists in any one of the following states. These states are:

1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Terminated

Module IV Page 8
CGB1201-JAVA PROGRAMMING

New state
When a thread instance/object is created, thread will be created and moved to “new” state.

Thread obj = new Thread(new MyRunnable()); //thread will be created and moved to

“new” state.

Runnable state
When start() method is called, thread moves to runnable state. A separate method

call stack will be created with run method being at the bottom of the call stack.

Runnable runnable = new NewState();

Thread t = new Thread(runnable);

[Link](); // new moves to runnable state

[Link]([Link]());

Module IV Page 9
CGB1201-JAVA PROGRAMMING

A thread can also return to the “runnable state” after coming back from a running,
sleeping, waiting or blocked state.

Running state
● In running state, thread will be running, in fact code present inside run() method
will be executing.

● A thread can move out of the “running state” to runnable, non-runnable or dead
state for various reasons.

● Also we can move running thread to other state explicitly by calling yield(), sleep(),
wait(), join or stop() method etc.

Non runnable state (Sleeping state, Waiting state and Blocked state)
● A non-runnable thread is a paused thread because of certain reasons like
unavailability of resources, waiting for another thread to finish, user explicitly
paused etc...

● When this non runnable thread is ready for re-run it will move to runnable state, but
not to running state.

We have three types of non-runnable threads

1. Sleeping state: A thread moves into the “sleeping state “when sleep() is called on a

running thread.
2. Waiting state: A thread moves into the “waiting state” when wait() is called on a

running Thread
3. Blocked state: A thread moves into the “blocked state” when join() is called or

when a resource is not available.

Module IV Page 10
CGB1201-JAVA PROGRAMMING

Dead state
● When run method execution is completes, thread moves to dead state.

● We can also call stop() or destroy() method explicitly to move a running thread
into “dead state” but the methods have been deprecated.
Program:

class ThreadLifecycle extends Thread {

public void run() {


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

try {
// Thread is in waiting state (sleep)
[Link]("Thread is going to sleep...");
[Link](1000);

// After sleep, it goes back to runnable


[Link]("Thread is awake and runnable again.");

} catch (InterruptedException e) {
[Link]("Thread is interrupted.");
}

[Link]("Thread is terminated.");
}

public static void main(String[] args) {


// New state
ThreadLifecycle t1 = new ThreadLifecycle();
[Link]("Thread is in NEW state.");

// Runnable state
[Link]();
[Link]("Thread is now RUNNABLE.");
}
}

Module IV Page 11
CGB1201-JAVA PROGRAMMING

Output:

Thread is in NEW state.


Thread is now RUNNABLE.
Thread is running...
Thread is going to sleep...
Thread is awake and runnable again.
Thread is terminated.

Differences

Aspect sleep() wait() join()


Pauses the current thread Pauses the current thread
Purpose Pauses the current thread until another thread notifies it until the target thread
for a specific time. or until a timeout expires. completes.
Lock Releases the lock on the
Behavior Does not release any locks. object it is called on. Does not release any locks.
Class Thread class Object class Thread class
Synchronizat Must be called within a
ion synchronized block on the
Requirement No synchronization needed same object. No synchronization need

Module IV Page 12
CGB1201-JAVA PROGRAMMING

Thread Priority

In java, the thread priority range from 1 to 10. Priority 1 is considered as the
lowest priority, and priority 10 is considered as the highest priority. The thread with
more priority allocates the processor first.

he java programming language Thread class provides two methods setPriority(int), and
getPriority( ) to handle thread priorities.

The Thread class also contains three constants that are used to set the thread priority, and
they are listed below.

● MAX_PRIORITY - It has the value 10 and indicates highest priority.

● NORM_PRIORITY - It has the value 5 and indicates normal priority.

● MIN_PRIORITY - It has the value 1 and indicates lowest priority.

setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread. It takes
an integer range from 1 to 10 as an argument and returns nothing (void).

Example

[Link](4);
or
[Link](MAX_PRIORITY);

getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread. It
does not take any argument and returns the name of the thread as String.

Module IV Page 13
CGB1201-JAVA PROGRAMMING

Example

String threadName = [Link]();

Program

class SampleThread extends Thread{


public void run() {
[Link]("Inside SampleThread");
[Link]("Current Thread: " +
[Link]().getName());
}
}
public class My_Thread_Test {
public static void main(String[] args) {
SampleThread threadObject1 = new SampleThread();
SampleThread threadObject2 = new SampleThread();

[Link]("first");
[Link]("second");

[Link](4);
[Link](Thread.MAX_PRIORITY);

[Link]();
[Link]();
}
}

Output:
Module IV Page 14
CGB1201-JAVA PROGRAMMING

Inside SampleThread
Current Thread: second
Inside SampleThread
Current Thread: first

Thread Synchronization
The synchronization is the process of allowing only one thread to access a
shared resource at a time.

In java, the synchronization is achieved using the following concepts.

● Inter thread communication

Inter-thread Communication in Java


Inter-thread communication is all about allowing synchronized threads to communicate
with each other.

Inter-thread communication is a mechanism in which a thread is paused running in its


critical section and another thread is allowed to enter (or lock) in the same critical section
to be executed.

Java provides the following methods to achieve inter thread communication.

Method Description

void wait( ) It makes the current thread to pause its execution until other thread in the same
monitor calls notify( )

void notify( ) It wakes up the thread that called wait( ) on the same object.

void notifyAll() It wakes up all the threads that called wait( ) on the same object.

Example of Inter Thread Communication in Java


Program
Module IV Page 15
CGB1201-JAVA PROGRAMMING

class Customer {

int amount = 10000;

synchronized void withdraw(int amount) {

[Link]("Going to withdraw...");

// Check if the balance is insufficient

if ([Link] < amount) {

[Link]("Less balance; waiting for deposit...");

try {

wait(); // Wait for deposit notification

} catch (InterruptedException e) {

[Link]();

[Link] -= amount; // Deduct the amount

[Link]("Withdrawal completed. Remaining balance: " + [Link]);

synchronized void deposit(int amount) {

[Link]("Going to deposit...");

[Link] += amount;

[Link]("Deposit completed. New balance: " + [Link]);

notify(); // Notify waiting threads

Module IV Page 16
CGB1201-JAVA PROGRAMMING

class Test {

public static void main(String[] args) {

Customer customer = new Customer();

// Withdraw thread

Thread withdrawThread = new Thread(() -> {

[Link](15000); // Attempt to withdraw 15000

});

// Deposit thread

Thread depositThread = new Thread(() -> {

[Link](10000); // Deposit 10000

});

[Link](); // Start the withdraw thread

[Link](); // Start the deposit thread

Output:

Attempting to withdraw: 15000


Insufficient balance; waiting for deposit...
Depositing: 10000
Deposit completed. New balance: 20000
Module IV Page 17
CGB1201-JAVA PROGRAMMING

Withdrawal completed. Remaining balance: 5000

Case study:
a) Write a java program that implements a multi-threaded application that has three
threads. First thread generates a random integer every 1 second and if the value is
even, the second thread computes the square of the number and prints. If the value is
odd, the third thread will print the value of the cube of the number.

Program:

import [Link].*;
class NumberGenerator extends Thread {
public void run() {
Random random = new Random();
while (true) {
int num = [Link](100);
[Link]("Generated Number: " + num);
if (num % 2 == 0) {
[Link]("Square of " + num + " is: " + (num * num));
} else {
[Link]("Cube of " + num + " is: " + (num * num * num));
}
try {
[Link](1000);
} catch (InterruptedException e) {
[Link](e);
}
}

Module IV Page 18
CGB1201-JAVA PROGRAMMING

}
}
public class MultiThreadedApp {
public static void main(String[] args) {
new NumberGenerator().start();
}
}

Output:

Generated Number: 12
Square of 12 is: 144
Generated Number: 7
Cube of 7 is: 343
Generated Number: 4
Square of 4 is: 16
Generated Number: 15
Cube of 15 is: 3375
Generated Number: 8
Square of 8 is: 64
Generated Number: 9
Cube of 9 is: 729

Explanation:

● The NumberGenerator thread generates a random integer every second and


prints it.
● If the number is even, it directly computes and prints its square.
● If the number is odd, it directly computes and prints its cube.
● The program is shorter because we removed the additional classes for separate
threads, handling everything in the NumberGenerator class itself.

Module IV Page 19
CGB1201-JAVA PROGRAMMING

Output Explanation:

For each randomly generated number:

● Generated Number: 12 → It's even, so the program prints Square of 12 is: 144.
● Generated Number: 7 → It's odd, so the program prints Cube of 7 is: 343.

This pattern continues, printing the square for even numbers and the cube for odd
numbers.

Java AWT
Java AWT (Abstract Window Toolkit) is a GUI (Graphical User Interface) toolkit for
Java applications, allowing developers to create windowed applications. It's part of Java's
standard library and provides components like buttons, text fields, and labels to create user
interfaces.

Java AWT Hierarchy

Module IV Page 20
CGB1201-JAVA PROGRAMMING

Button

In Java AWT, the Button class is a fundamental GUI component used to create a
clickable button. It is commonly used to trigger actions or events when clicked by the user.
Here’s an in-depth look at its features, methods, and an example of usage:

Overview of the Button Class

● Package: [Link]
● Superclass: [Link]
● Constructor: Button() or Button(String label)
● Purpose: The Button class is used for creating interactive buttons in Java AWT
applications. It enables users to perform an action by clicking on the button, which
can then trigger an event.

Key Constructors of Button

Constructor Description Example Usage


Creates an empty
Button() button without any Button button1 = new Button();
label.
Button(Strin Creates a button with Button button2 = new
g label) the specified label text. Button("Submit");

Key Methods of Button

Method Description Example Usage


Sets or changes the
void setLabel(String label) text label of the [Link]("Click Me");
button.

String getLabel() Returns the current String label = [Link]();

Module IV Page 21
CGB1201-JAVA PROGRAMMING

label text of the


button.
Adds an
void
ActionListener to [Link](new
addActionListener(ActionListener
the button to ActionListener() {...});
l)
handle click events.
Removes the
void
specified [Link](lis
removeActionListener(ActionListen
ActionListener tener);
er l)
from the button.

Program

import [Link].*;
import [Link].*;
public class ButtonExample extends Frame {
// Label to show output in the window
Label label;
public ButtonExample() {
// Setup frame
setTitle("Button Example");
setSize(300, 200);
setLayout(new FlowLayout());
// Create and add button with ActionListener
Button button = new Button("Click Me");
[Link](e -> [Link]("Button
clicked!"));

// Create label to display output


label = new Label("Waiting for button click...");

// Add components to the frame


add(button);
add(label);
setVisible(true);
}
public static void main(String[] args) {
new ButtonExample();

Module IV Page 22
CGB1201-JAVA PROGRAMMING

}
}

Output:

Explanation of the Example

1. Label: A Label is added to the frame to display the message.


2. Button ActionListener: The ActionListener listens for the button click and
updates the label text to "Button clicked!" when the button is clicked.
3. Window Update: The Label is updated inside the action event, making the
message appear in the window..

Label

In Java AWT, the Label class is used to display a single line of non-editable text.
Labels are typically used to show messages, instructions, or to identify other components in
a GUI (like text fields or buttons).

Key Constructors of Label

Constructor Description Example Usage

Module IV Page 23
CGB1201-JAVA PROGRAMMING

Creates an empty label with


Label() Label label1 = new Label();
no text.
Creates a label with the Label label2 = new Label("Hello
Label(String text)
specified text. World");
Creates a label with
specified text and alignment.
Label(String text, int Label label3 = new
Alignment options are
alignment) Label("Hello", [Link]);
[Link], [Link],
and [Link].

Key Methods of Label

Method Description Example Usage


Sets or changes the text
void setText(String text) [Link]("New Text");
displayed on the label.
Returns the current text of
String getText() String text = [Link]();
the label.
Sets the alignment of the
void setAlignment(int text on the label. Options are [Link]([Link]
alignment) [Link], [Link], );
and [Link].
Returns the current int alignment =
int getAlignment()
alignment of the label text. [Link]();

Program

import [Link].*;

public class LabelExample extends Frame {


public LabelExample() {
setTitle("Label Example");
setSize(300, 200);
setLayout(new FlowLayout());

Module IV Page 24
CGB1201-JAVA PROGRAMMING

// Create labels
Label label1 = new Label("Label with default alignment");
Label label2 = new Label("Centered Label", [Link]);
Label label3 = new Label("Right-aligned Label", [Link]);

// Add labels to frame


add(label1);
add(label2);
add(label3);

setVisible(true);
}

public static void main(String[] args) {


new LabelExample();
}
}
Output:

Explanation of the Example

1. Label Creation:
○ Label label1 = new Label("Label with default
alignment"); creates a left-aligned label (default alignment).
○ Label label2 = new Label("Centered Label",
[Link]); creates a label with centered text.

Module IV Page 25
CGB1201-JAVA PROGRAMMING

○ Label label3 = new Label("Right-aligned Label",


[Link]); creates a right-aligned label.
2. Adding to Frame:
○ Each label is added to the frame using add(label);, making them visible in
the GUI.
3. Output:
○ The GUI window displays three labels, each with different text alignment.

Checkbox

In Java AWT, the Checkbox class is used to create a checkable box that represents a
binary choice, meaning it can be either selected (checked) or unselected (unchecked).
Checkboxes are often used to gather multiple-choice selections from users.

Key Constructors of Checkbox

Constructor Description Example Usage


Creates an empty checkbox
Checkbox() with no label and unchecked Checkbox cb1 = new Checkbox();
by default.
Creates a checkbox with the
Checkbox cb2 = new
Checkbox(String label) specified label text and
Checkbox("Accept Terms");
unchecked by default.
Creates a checkbox with
Checkbox(String label, specified label and initial Checkbox cb3 = new
boolean state) state (true for checked, false Checkbox("Subscribe", true);
for unchecked).

Key Methods of Checkbox

Method Description Example Usage

Module IV Page 26
CGB1201-JAVA PROGRAMMING

Sets the state of the


void setState(boolean
checkbox (true for checked, [Link](true);
state)
false for unchecked).
Returns the current state of
boolean isChecked =
boolean getState() the checkbox (true if
[Link]();
checked, false if unchecked).
Sets or changes the label of [Link]("New
void setLabel(String label)
the checkbox. Label");
Returns the current label String label =
String getLabel()
text of the checkbox. [Link]();
void Adds an ItemListener to
[Link](listen
addItemListener(ItemListe handle state changes for the
er);
ner l) checkbox.

Program

import [Link].*;
import [Link].*;
public class SimpleCheckboxExample extends Frame {
public SimpleCheckboxExample() {
// Setup frame
setTitle("Checkbox Example");
setSize(250, 100);
setLayout(new FlowLayout());
// Create checkbox
Checkbox checkbox = new Checkbox("Subscribe");
Label statusLabel = new Label("Checkbox state: Off");

// Add item listener to update label based on checkbox state


[Link](e -> [Link]("Checkbox state: " +
([Link]() ? "On" : "Off")));
// Add components to the frame
add(checkbox);
add(statusLabel);
// Make window visible
setVisible(true);

Module IV Page 27
CGB1201-JAVA PROGRAMMING

}
public static void main(String[] args) {
new SimpleCheckboxExample();
}
}

Output

Explanation

Window Setup: The window (Frame) is titled "Checkbox Example" and has a size of
250x100 pixels, with components arranged in a flow (left to right).

Components:

● A checkbox labeled "Subscribe" is created.


● A label displays the current state of the checkbox ("Checkbox state: Off").

Event Handling: An ItemListener is added to the checkbox. When the checkbox is


checked or unchecked, the label updates to display "Checkbox state: On" or
"Checkbox state: Off" based on the checkbox state.

Choice
In Java AWT, the Choice class is used to create a dropdown list (also called a combo
box) that allows the user to choose one item from a list of options. The Choice component
is useful when you want to limit the user to selecting only one item from a predefined set of
choices.

Module IV Page 28
CGB1201-JAVA PROGRAMMING

Key Constructors of Choice

Constructor Description Example Usage


Creates an empty dropdown
Choice() Choice choice = new Choice();
list.

Key Methods of Choice

Method Description

add(String item) Adds an item to the dropdown list.

remove(String item) Removes the specified item.

getItemCount() Returns the number of items in the list.

getSelectedItem() Returns the currently selected item.

Adds an ItemListener to handle selection


addItemListener(ItemListener l)
events.

Program

package m4;
import [Link].*;
import [Link].*;
public class SimpleChoiceExample extends Frame {
private Label colorLabel;
public SimpleChoiceExample() {
setTitle("Choice Example");
setSize(250, 150);
setLayout(new FlowLayout());
// Create a Choice component
Choice colorChoice = new Choice();

// Add items to the Choice

Module IV Page 29
CGB1201-JAVA PROGRAMMING

[Link]("Red");
[Link]("Green");
[Link]("Blue");
// Create a Label to display the selected color
colorLabel = new Label("Selected Color: None");
// Add ItemListener to handle selection and update label
[Link](e ->
[Link]("Selected Color: " + [Link]())
);
// Add components to the frame
add(colorChoice);
add(colorLabel);
setVisible(true);
}
public static void main(String[] args) {
new SimpleChoiceExample();
}
}

Explanation

1. Choice Component: A dropdown menu is created using Choice colorChoice


= new Choice();.
2. Adding Items: The program adds three colors ("Red," "Green," and "Blue") to the
dropdown.
3. ItemListener: An ItemListener is attached to the Choice to print the selected
color to the console whenever the user makes a selection.
4. Visibility: The choice is added to the frame and the frame is made visible.

Module IV Page 30
CGB1201-JAVA PROGRAMMING

List
In Java AWT, the List class is used to create a list of items that users can select
from. Unlike a Choice component, which displays a single item at a time in a dropdown
format, a List can show multiple items at once and allows for single or multiple selections,
depending on its configuration.

Key Constructors of List

Constructor Description Example Usage


Creates an empty list with
List() List list = new List();
default size.
Creates a list that displays
List(int rows) the specified number of List list = new List(5);
rows.
Creates a list that can
List(int rows, boolean display multiple items and
List list = new List(5, true);
multipleMode) allows multiple selections if
multipleMode is true.

Key Methods of List

Method Description Example Usage


void add(String item) Adds an item to the list. [Link]("Apple");
Returns an array of
String[] selected =
String[] getSelectedItems() currently selected items (for
[Link]();
multiple selection mode).
Removes the item at the
void remove(int index) [Link](0);
specified index from the list.

Program

import [Link].*;
import [Link].*;
public class SimpleListExample1 extends Frame {

Module IV Page 31
CGB1201-JAVA PROGRAMMING

private Label selectedFruitLabel; // Label to display the selected fruit


public SimpleListExample1() {
setTitle("List Example");
setSize(250, 200); // Adjusted size for better visibility
setLayout(new FlowLayout());
// Create a List component
List fruitList = new List(4); // 4 visible rows
// Add items to the List
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
// Create a Label to display the selected fruit
selectedFruitLabel = new Label("Selected Fruit: None");
// Add ItemListener to handle selection and update label
[Link](e ->
[Link]("Selected Fruit: " + [Link]())
);
// Add List and Label to the frame
add(fruitList);
add(selectedFruitLabel);
setVisible(true);
}
public static void main(String[] args) {
new SimpleListExample1();
}
}

Output :

Module IV Page 32
CGB1201-JAVA PROGRAMMING

Explanation

1. Creating the List Component:


○ The list is created with List fruitList = new List(4);, which
shows four items at a time.
○ Fruits are added using [Link]("Apple");,
[Link]("Banana");, and [Link]("Cherry");.
2. ItemListener:
○ An ItemListener is added to print the selected fruit to the console when
the user selects an item from the list.
3. Adding to Frame:
○ The list is added to the frame, making it visible.

Case Study :
b) Develop a simple calculator application using Java AWT components such as Text
Field, Button, and Label. Implement event handlers to perform arithmetic operations
(addition, subtraction, multiplication, division) when the user clicks on the buttons.

Program

import [Link].*;
import [Link].*;

Module IV Page 33
CGB1201-JAVA PROGRAMMING

public class SimpleCalculator extends Frame implements ActionListener


{
TextField number1, number2;
Button add, subtract, multiply, divide, modulo;
Label result;
public SimpleCalculator() {
// Set up the frame
setTitle("Simple Calculator");
setSize(300, 200);
setLayout(new FlowLayout());
// Create components
number1 = new TextField(10);
number2 = new TextField(10);
add = new Button("Add");
subtract = new Button("Subtract");
multiply = new Button("Multiply");
divide = new Button("Divide");
modulo = new Button("Modulo");
result = new Label("Result: ");
// Add components to the frame
add(number1);
add(number2);
add(add);
add(subtract);
add(multiply);
add(divide);
add(modulo);
add(result);
// Add action listeners to buttons
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {

Module IV Page 34
CGB1201-JAVA PROGRAMMING

double num1 = [Link]([Link]());


double num2 = [Link]([Link]());
double output = 0;
// Determine which button was pressed
if ([Link]() == add) {
output = num1 + num2;
} else if ([Link]() == subtract) {
output = num1 - num2;
} else if ([Link]() == multiply) {
output = num1 * num2;
} else if ([Link]() == divide) {
if (num2 != 0) {
output = num1 / num2;
} else {
[Link]("Error: Division by zero");
return;
}
} else if ([Link]() == modulo) {
if (num2 != 0) {
output = num1 % num2;
} else {
[Link]("Error: Division by zero");
return;
}
}
// Display the result
[Link]("Result: " + output);
}
public static void main(String[] args) {
new SimpleCalculator();
}
}

Output:

Module IV Page 35
CGB1201-JAVA PROGRAMMING

Program
import [Link].*;
import [Link].*;
public class SimpleGUIExample {
public static void main(String[] args) {
// Create a frame (Window)
Frame f = new Frame("Simple GUI Example");
// Create components with abbreviated names
Label l = new Label("Select your choice:");
Checkbox cb = new Checkbox("Accept Terms");
Choice c = new Choice();
List li = new List();
Button b = new Button("Submit");
// Add items to the Choice and List
[Link]("Option 1");
[Link]("Option 2");
[Link]("Option 3");
[Link]("Apple");
[Link]("Mango");
[Link]("Banana");
// Set the layout for the frame
[Link](new FlowLayout());
// Add components to the frame
[Link](l);
[Link](cb);

Module IV Page 36
CGB1201-JAVA PROGRAMMING

[Link](c);
[Link](li);
[Link](b);
// Button click event handling
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selectedChoice = [Link]();
String selectedListItem = [Link]();
boolean isChecked = [Link]();

// Display the selected values in the console


[Link]("Selected Choice: " + selectedChoice);
[Link]("Selected List Item: " + selectedListItem);
[Link]("Accepted Terms: " + (isChecked ? "Yes" : "No"));
}
});
// Set the size and make the frame visible
[Link](300, 200);
[Link](true);
// Close the frame when clicking the close button
[Link](new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
}
});
}
}

Output :

Module IV Page 37
CGB1201-JAVA PROGRAMMING

Event handling :
Event handling in Java is a mechanism that allows programs to respond to user
interactions, such as button clicks, mouse movements, and key presses. Java's
event-handling system is part of the AWT (Abstract Window Toolkit) and Swing libraries
and follows a delegation event model. In this model, events are dispatched to designated
objects (known as listeners) that are responsible for handling specific events.

Key Components of Java's Event Handling Mechanism

1. Event Sources: These are the objects that generate events. Examples include GUI
components like buttons, text fields, checkboxes, etc. Each source can trigger
multiple types of events (e.g., mouse events, action events).
2. Events: Events are objects that represent specific user interactions. Java provides a
variety of event classes (e.g., ActionEvent, MouseEvent, KeyEvent) to
represent different interactions.
3. Event Listeners: Event listeners are interfaces that define the methods required to
handle specific types of events. Listeners must implement these methods and be
registered with an event source to receive events.
4. Event Handlers: The actual methods that perform the actions when an event
occurs. These methods are defined in the listener interfaces and are called
automatically when an event occur

Steps to Implement Event Handling

1. Identify the Event Source: Determine which component will generate the event,
such as a button.
2. Implement the Listener Interface: Create a class that implements the listener
interface(s) relevant to the type of event. For example, ActionListener for

Module IV Page 38
CGB1201-JAVA PROGRAMMING

button clicks, MouseListener for mouse events, or KeyListener for keyboard


events.
3. Register the Listener: Register the listener with the event source using a method
such as addActionListener(), addMouseListener(), or
addKeyListener().
4. Define the Event Handler: Implement the specific method(s) defined in the listener
interface to handle the event.

1. MouseEvent

MouseEvent represents mouse actions (clicks, movements, etc.) in a graphical user


interface. It provides information about the mouse state and the location of the mouse
cursor.

Key Methods of MouseEvent

Method Description

int getX() Returns the x-coordinate of the mouse cursor.

int getY() Returns the y-coordinate of the mouse cursor.

Returns the mouse button that was pressed (left,


int getButton()
middle, right).

Program

import [Link].*;
import [Link].*;
import [Link].*;
public class MouseEventExample extends JFrame {
public MouseEventExample() {
setTitle("Mouse Event Example");
setSize(300, 200);

Module IV Page 39
CGB1201-JAVA PROGRAMMING

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// JLabel to show event details
JLabel label = new JLabel("Mouse hasn't interacted yet.");
// MouseListener to detect mouse events
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse clicked at: " + [Link]());
}
@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse pressed at: " + [Link]());
}
@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse released at: " + [Link]());
}
@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse entered the window!");
}
@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse exited the window.");
}
});
// Add label to the frame
add(label);
setVisible(true);
}
public static void main(String[] args) {
new MouseEventExample();
}
}

Output:

Module IV Page 40
CGB1201-JAVA PROGRAMMING

2. KeyEvent

KeyEvent represents keyboard actions (key presses, releases, etc.) in a graphical


user interface. It provides information about which key was pressed and the state of
modifier keys (like Shift, Control, etc.).

Method Description
Returns the integer code for the key that was
int getKeyCode()
pressed.
Returns the character generated by the key
char getKeyChar()
pressed.
Returns true if the Shift key was pressed
boolean isShiftDown()
when the event occurred.
Returns true if the Control key was pressed
boolean isControlDown()
when the event occurred.
Returns true if the Alt key was pressed when
boolean isAltDown()
the event occurred.

Program

import [Link].*;
import [Link].*;

Module IV Page 41
CGB1201-JAVA PROGRAMMING

public class KeyEventExample extends Frame implements KeyListener {


public KeyEventExample() {
setTitle("KeyEvent Example");
setSize(300, 200);
setLayout(new FlowLayout());

// Add KeyListener to the frame


addKeyListener(this);

setVisible(true);
}

@Override
public void keyPressed(KeyEvent e) {
[Link]("Key Pressed: " + [Link]());
}

@Override
public void keyReleased(KeyEvent e) {}

@Override
public void keyTyped(KeyEvent e) {}

public static void main(String[] args) {


new KeyEventExample();
}
}

Output

Console
Key Pressed: h
Key Pressed: g

Module IV Page 42
CGB1201-JAVA PROGRAMMING

Java Swing

Java Swing is a part of the Java Foundation Classes (JFC) used for creating graphical
user interfaces (GUIs) in Java applications. It provides a rich set of components and a highly
customizable framework that supports a wide range of graphical elements, from basic
components like buttons and labels to more complex components like tables and trees.

Hierarchy of Java Swing classes

JComponent

Module IV Page 43
CGB1201-JAVA PROGRAMMING

JComponent is a key class in the Swing library in Java, providing the foundation for
creating graphical components in a GUI application. It’s the superclass for all Swing
components, including JButton, JLabel, JPanel, and others. JComponent inherits from
Container, meaning it can hold other components and is part of the component hierarchy in
a Java Swing application.

Key Features of JComponent

● Custom Painting: JComponent provides the paintComponent(Graphics g) method,


allowing custom rendering.
● Borders: You can set borders using setBorder(Border border).
● Tooltips: Set a tooltip for any component using setToolTipText(String text).
● Opacity: Control transparency with setOpaque(boolean opaque).
● Event Handling: Supports event listeners for interaction.

[Link]

JButton is a component in Java Swing used to create buttons in a graphical user


interface (GUI). Buttons allow users to perform actions by clicking on them, triggering
events that can be handled programmatically. JButton is part of the [Link]
package and provides a flexible, customizable way to add interactive buttons to a Java
Swing application.

Constructors

Constructor Description
JButton() Creates a button with no text or icon.
JButton(String text) Creates a button with specified text.
JButton(Icon icon) Creates a button with an icon but no text.
JButton(String text, Icon icon) Creates a button with both text and an icon.

Module IV Page 44
CGB1201-JAVA PROGRAMMING

Methods

Method Description
void setText(String text) Sets the text displayed on the button.
Returns the text currently displayed on the
String getText()
button.
void setIcon(Icon icon) Sets an icon for the button.
Icon getIcon() Returns the icon used by the button.
void Adds an ActionListener to handle button click
addActionListener(ActionListener l) events.

[Link]

JLabel is a simple yet essential component in Java Swing used to display a short
string or an image. Unlike interactive components like JButton, JLabel is primarily for
displaying information and is non-interactive, meaning users can't click or type into it.
JLabel is found in the [Link] package and is a fundamental part of most GUI
applications, often used for labeling other components or showing static information.

Constructor

Constructor Description
JLabel() Creates an empty label.
JLabel(String text) Creates a label with the specified text.
JLabel(Icon icon) Creates a label with the specified icon.
JLabel(String text, Icon icon, int Creates a label with text, an icon, and
alignment) specified alignment.

Methods

Method Description
void setText(String text) Sets the text displayed by the label.

Module IV Page 45
CGB1201-JAVA PROGRAMMING

Returns the current text displayed by the


String getText() label.
void setIcon(Icon icon) Sets an icon to be displayed in the label.
Icon getIcon() Returns the icon used by the label.
void setHorizontalAlignment(int Sets the horizontal alignment of the label (e.g.,
alignment) [Link]).
void setVerticalAlignment(int Sets the vertical alignment of the label
alignment) content.
void setForeground(Color color) Sets the color of the label’s text.
void setFont(Font font) Sets the font of the label’s text.

[Link]

JList is a component in Java Swing that provides a way to display a list of items
from which users can select one or multiple entries. It’s a versatile and commonly used
component in Swing for presenting options or items in a scrollable, selectable format.
JList is part of the [Link] package and is ideal for cases where users need to
choose from a predefined list of options.

Constructors

Constructor Description
JList() Creates an empty list.
JList(E[] listData) Creates a list from an array of items.
Creates a list using a specified data model,
JList(ListModel<E> dataModel) providing more control.

Methods

Method Description
void setListData(E[] listData) Sets the items in the list from an array.

Module IV Page 46
CGB1201-JAVA PROGRAMMING

Returns the index of the currently selected


int getSelectedIndex() item (single selection mode).
Returns the selected item itself (single
Object getSelectedValue() selection mode).

JComboBox

JComboBox is a Swing component that provides a dropdown list for selecting an


item from multiple options. It's ideal for situations where you want users to pick from a list
of options while conserving screen space. It allows users to either click to expand a list of
choices or type directly if editable, giving it flexibility and ease of use.

Constructors

Constructor Description
JComboBox() Creates an empty combo box.
Creates a combo box containing the elements
JComboBox(E[] items) in the specified array.
Creates a combo box containing the elements
JComboBox(Vector<E> items) in the specified vector.

Methods

Method Description
void addItem(E item) Adds an item to the combo box.
E getSelectedItem() Returns the currently selected item.
void setSelectedItem(Object item) Sets the selected item.
void removeItem(Object item) Removes an item from the combo box.
Sets whether the combo box is editable
void setEditable(boolean editable) (allowing users to type into it).
void Registers an action listener to be notified
addActionListener(ActionListener l) when an item is selected.
Module IV Page 47
CGB1201-JAVA PROGRAMMING

Program

import [Link].*;
import [Link].*;

public class SwingComponentExample extends JFrame {


public SwingComponentExample() {
setTitle("Swing Component Hierarchy Example");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

// JLabel
JLabel l = new JLabel("Choose an option:");

// JList with updated items


String[] items = {"Apple", "Mango", "Cherry"};
JList<String> itemList = new JList<>(items);

// JComboBox renamed to cb
JComboBox<String> cb = new JComboBox<>(items);

// JButton
JButton b = new JButton("Submit");

// Add components to the frame


add(l);
add(new JScrollPane(itemList));
add(cb);
add(b);

setVisible(true);
}

public static void main(String[] args) {


new SwingComponentExample();
}
}

Output

Module IV Page 48
CGB1201-JAVA PROGRAMMING

Difference between java AWT and Swing

Feature AWT Swing


Type Heavyweight components Lightweight components
Components Basic and limited Extensive and customizable
Look and Feel Native appearance Pluggable look-and-feel
Event Handling Traditional model Enhanced model
Performance Faster for simple apps Better for complex apps
Single-threaded with better
Threading Single-threaded utilities

Important Questions
1. Illustrate with a neat diagram and discuss the life cycle of thread and its priority.
2. Develop a java program for creating four threads to perform the following
operations.
i) Getting N numbers as input
ii) Printing the even numbers
iii) Printing the odd numbers
iv) Computing the average

Module IV Page 49
CGB1201-JAVA PROGRAMMING

3. Show how multi threads are created in java with example program and state the
significance of sleep(), run() and join() methods.
4. Develop a java program that illustrates the uses of wait(), notify(), notifyAll()
methods.
5. Discuss in detail about inter thread communication in java.
6. Develop a java program that implements a multi-threaded application that has three
threads. First thread generates a random integer every 1 second and if the value is
even, the second thread computes the square of the number and prints. If the value
is odd, the third thread will print the value of the cube of the number.
7. Classify the swing components in Java and explain any three of them with example
program.
8. Analyse on how events are handled in java. Discuss in detail about it.
9. Classify Java AWT components and explain any three of them with example program.
10. Develop a java program that illustrates event handing such as MouseEvent and
KeyEvent.
11. Develop a calculator application using Java AWT components such as Text Field,
Button, and Label. Implement event handlers to perform arithmetic operations
(addition, subtraction, multiplication, division) when the user clicks on the buttons.
12. Develop a calculator application using Java Swing components such as Text Field,
Button, and Label. Implement event handlers to perform arithmetic operations
(addition, subtraction, multiplication, division) when the user clicks on the buttons.

Module IV Page 50

You might also like