Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Unit 2 - Java Programming

The document discusses multithreaded programming, highlighting the concept of multitasking and the differences between process-based and thread-based multitasking. It explains the benefits of multithreading, the life cycle of a thread, and how to create threads in Java using the Thread class and Runnable interface. Additionally, it covers synchronization in Java, the importance of managing shared resources, and provides examples such as the producer-consumer problem.

Uploaded by

ishq.edits
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit 2 - Java Programming

The document discusses multithreaded programming, highlighting the concept of multitasking and the differences between process-based and thread-based multitasking. It explains the benefits of multithreading, the life cycle of a thread, and how to create threads in Java using the Thread class and Runnable interface. Additionally, it covers synchronization in Java, the importance of managing shared resources, and provides examples such as the producer-consumer problem.

Uploaded by

ishq.edits
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 109

Unit 2

Multithreaded Programming
Concept of Multitasking
Multitasking : Where users of a computer system can
perform multiple actions simultaneously on the machine.

● It can be achieved in two ways:


● Process-Based Multitasking :
○ In this type of Multitasking, processes are heavyweight
○ Each process is allocated by a separate memory area.
○ Cost of communication between processes is high
○ Long time for switching
● Thread-Based Multitasking ( Multithreading)
:
○ Threads are provided with lightweight nature
○ They all share the same address space for each process.
○ Cost of communication between threads is low.
○ Hence, we use threads and perform Multithreading
Multithreading
● Multithreading allows many parts of a program to run
simultaneously.
● These parts = threads
● Multithreading is a programming technique that allows a
process to execute multiple threads concurrently.
○ A process is a running program
○ Process can also be subdivided into independent units
called threads.
● A thread is the smallest unit of execution in a program.
● By using multiple threads, a program can perform multiple
tasks at the same time, improving efficiency and
responsiveness.
● Real-Time Examples of Multithreading in a Computer
System :
○ Web Browsers
■ Each browser tab runs in a separate thread, allowing
multiple web pages to load simultaneously.
■ Background tasks like downloading files, rendering
web pages, and running JavaScript all happen
concurrently.
○ Operating System
■ You can browse the internet while a software update
is being installed in the background.
Multithreading VS Parallel Programming

On a single-core CPU,
multithreading only provides the
illusion of parallelism due to
context switching, whereas
parallel programming requires a
multi-core processor to achieve
true parallel execution.
What is a Thread ?
● A Thread is a light-weight process within a process.
● It is the smallest part of the process.
● Threads use shared memory but act independently.
● Therefore, if an exception occurs in one thread, other threads
are not affected despite sharing same memory.
● This allows programs to operate more efficiently by running
multiple tasks simultaneously.
● Threads can be used to perform complicated tasks in the
background without interrupting the main program.
In a simple way, a Thread is a:
● Feature through which we can perform multiple activities within a
single process.
● Lightweight process.
● Series of executed statements.
● Nested sequence of method calls.
Benefits of multithreading
● It maximizes CPU utilization : Multithreading is a Java
feature that allows concurrent execution of two or more parts of
a program for maximum utilization of CPU.
○ Multi-processor system : multiple threads execute
simultaneously on different cores.
■ Eg- If there are two threads and two cores , then each
thread would run on individual core.
○ Single-processor system : multiple threads execute on the
single core, one after the other giving an illusion of parallel
processing.
● It saves time by allowing multiple operations to be
performed simultaneously by making fast switches between
threads.
● It doesn't block the user in Client-Server Model : This means
the next client doesn't have to wait until the first client has
States of the Thread

● In Java, a thread always exists in any one of the


following states.
● These states are:
○ New
○ Active
○ Blocked / Waiting
○ Timed Waiting
○ Terminated
Life Cycle of A Thread
1) New: Whenever a new thread is created, it is always in the new
state.
○ Thread has not begun its execution.
2) Active: When a thread invokes the start() method, it moves from
the new state to the active state.
○ The active state contains two states within it: one is runnable,
and the other is running.
● Runnable:
○ A thread, that is ready to run is then moved to the runnable
state.
○ Thread should be ready to run at any given instant of time.
○ It is the duty of the thread scheduler to provide the thread
time to run, i.e., moving the thread the running state.
○ Multithreading acquires a fixed slice of time to each individual
thread.
○ If thread finishes it’s execution before the time slice, it
voluntarily gives up the CPU to the other thread
Running: When the thread gets the CPU, it moves from the runnable to
the running state.

3) Blocked or Waiting: Whenever a thread is inactive for a span of


time then, either the thread is in the blocked state or is in the waiting
state.
○ Consider Thread A wants to print some data from the printer but Thread B is currently
printing.
○ Thus, thread A is in the blocked state.
○ A thread in the blocked state is unable to perform any execution and thus never
consume any cycle of the Central Processing Unit (CPU).

4) Timed Waiting: Waiting can lead to starvation.


○ For example, a thread (its name is A) has entered the critical section of a code(where
there are global variables) and is not willing to leave that critical section.
○ In such a scenario, another thread has to wait forever, which leads to starvation.
○ To avoid such scenario, a timed waiting state is given to thread B. Thus, thread lies in
5) Terminated: A thread reaches the termination state because of the
following reasons:
● Normal Termination : When a thread has finished its job, then it
exits or terminates normally.
● Abnormal termination: It occurs when some unusual events such as
an unhandled exception or segmentation fault.

A terminated thread means the thread is no more in the system. In


other words, the thread is dead.
Java Main Thread

● As we know, we create Main Method in each and every Java


Program, which acts as an entry point for the code to get executed
by JVM,
● Similarly in this Multithreading Concept, Each Program has one Main
Thread which was provided by default by JVM
● Whenever a program is being created in java, JVM provides the Main
Thread for its Execution.
start() Method

● The method is used for starting a thread that we have newly


created.
● It starts a new thread with a new call stack.
● After executing the start() method, the thread changes the state
from New to Runnable.
● It executes the run() method when the thread gets the correct
time to execute it.
Creating a thread
● Threads are implemented as objects that contain a method called run()
● This method makes the entire body of the thread.
● It is the only method in which thread’s behaviour can be implemented.

Syntax :

Public void run()

……………. ( statements for implementing thread)

…………….

● Thread can be implemented in 2 ways :


○ By creating a Thread class : a class that extends Thread class and
overrides the run() method.
○ By converting a class to thread : A class that implements Runnable
interface, which has only 1 method that is the run()
How to Create Threads in Java? → 1. By Extending Thread Class

It can be created by extending the Thread class and overriding its run() method:

When the object is created → the thread is in new state

When you invoke start() → thread moves to runnable state

After this run() is invoked → this puts the thread in runnable state
Java Thread Class
● Thread is a line of execution within a program.
● Each program can have multiple associated threads.
● Each thread has a priority which is used by the thread scheduler to
determine which thread must run first.
● Java provides a thread class that has various method calls to
manage the behavior of threads by providing constructors
and methods to perform operations on threads.
● A Thread is a program that starts with a method frequently used in
this class only known as the start() method.
● This method looks out for the run() method which is also a method of
this class and begins executing the body of the run() method.
How to Create Threads in Java? → 2. Using Runnable Interface
Runnable Interface

● java.lang.Runnable is an interface that is to be implemented by a


class whose instances are intended to be executed by a thread.
● The runnable interface has an undefined method run() with void as
return type, and it takes in no arguments.
● Syntax :
public void run()

//BODY OF THE THREAD

}
Multithreading in Java - By Extending the Thread class

NOTE :
Thread.currentThread() is a static method of the Thread class that returns a reference to the currently executing thread.
The getId() method in Java is used to retrieve the unique identifier (ID) of a thread.
Output :

Thread 15 is running

Thread 14 is running

Thread 16 is running

Thread 12 is running

Thread 11 is running

Thread 13 is running

Thread 18 is running

Thread 17 is running
Multithreading in Java - By Implementing the Runnable Interface
Output :

Thread 13 is running

Thread 11 is running

Thread 12 is running

Thread 15 is running

Thread 14 is running

Thread 18 is running

Thread 17 is running

Thread 16 is running
https://www.programiz.com/online-compiler/68tV1VfM9Db6j
Thread Class vs Runnable Interface

● If we extend the Thread class, our class cannot extend any


other class because Java doesn’t support multiple inheritance. But,
if we implement the Runnable interface, our class can still extend
other base classes.
● We can achieve basic functionality of a thread by extending Thread
class because it provides some inbuilt methods like yield(),
interrupt() etc. that are not available in Runnable interface.
● Using runnable will give you an object that can be shared amongst
multiple threads.
Synchronization in Java
● Thread synchronization in Java is important for managing
shared resources in a multithreaded environment.
● It ensures that only one thread can access a shared resource
at a time, which enhances the overall system performance.
● Real World Example :
○ Imagine multiple computers connected to a single printer:
○ If two computers send print jobs simultaneously, the
printer might mix their outputs and that leads to invalid
results.
○ Similarly, threads accessing the same resource without
coordination can produce inconsistent data.
Why We Require Synchronization?
● Multi-threaded programs may often come to a situation where
multiple threads try to access the same resources and finally
produce erroneous and unforeseen results.
● Synchronization method is required that only one thread can
access the resource at a given point in time.
● Without synchronization, simultaneous access can lead to :
○ Race Conditions: Multiple Threads interchanging shared data
at the same time and it results an unpredictable output.
○ Data Corruption: Incomplete or corrupted data when multiple
threads modify the same resource simultaneously.
Without Race Condition
Race
Condition
Example :

If two threads execute increment()


simultaneously, they might read the current
value of count, increment it, and write it back
concurrently.

This can result in lost updates or incorrect final


values due to race conditions.
Synchronization in JAVA

● Problems as discussed before, as tackled in JAVA by giving


a single thread to have exclusive access to either a
synchronized block of code or a synchronized method
associated with an object in question at a time.
● The keyword ‘synchronized’ is used to tackle the problem.
● There are two primary mechanisms for synchronization in
Java:
○ Synchronized blocks
○ Synchronized methods
Synchronized Blocks
● Synchronized blocks in Java are marked with the
synchronized keyword.
● All synchronized blocks synchronize on the same object and
can only have one thread executed inside them at a time.
● All other threads attempting to enter the synchronized block
are blocked until the thread inside the synchronized block
exits the block.
● This synchronization is implemented in Java with a
concept called monitors or locks.
● Only one thread can own a monitor at a given time.
● When a thread acquires a lock, it is said to have
entered the monitor.
● All other threads attempting to enter the locked
monitor will be suspended until the first thread exits the
monitor.
Thread Synchronization in Java
join() Method
● The join() method in Java is provided by the java.lang.Thread
class that permits one thread to wait until the other thread to
finish its execution.
● It is a method from the Thread class and plays a crucial role in
coordinating multiple threads.
● When the join() method is invoked, the current thread stops its
execution and the thread goes into the wait state.
● The current thread remains in the wait state until the thread on
which the join() method is invoked has achieved its dead state.
● When a thread needs results from another thread before
proceeding, join() ensures the dependent task starts only after
the required task is complete.
Bounded Buffer Problem (Producer–Consumer Problem)

● The problem describes two processes, the producer and the


consumer, which share a common, fixed-size buffer used as a queue.
● The producer’s job is to generate data, put it into the buffer, and
start again.
● At the same time, the consumer is consuming the data (i.e.
removing it from the buffer), one piece at a time.
● Problem : To make sure that the producer won’t try to add data into
the buffer if it’s full and that the consumer won’t try to remove data
from an empty buffer.
Solution :
● If Buffer is FULL - The producer is to either go to
sleep or discard data.
● The next time the consumer removes an item from
the buffer, it notifies the producer, who starts to fill
the buffer again.
● If Buffer is EMPTY - the consumer can go to sleep
● The next time the producer puts data into the buffer,
it wakes up the sleeping consumer.
Producer Function - Solution using Threads
public void produce() throws InterruptedException synchronized (this) : locks the instance,
ensuring only one thread executes the block
{ at a time.
int value = 0; notify() : to notify the consumer to start
while (true) consuming items from the list.

{
synchronized (this)
{ The consume function has a loop to get
while (list.size() == capacity) items from the list. The function checks if
the list is empty, if it is empty then the
wait(); thread gives up the lock and transfers the
System.out.println("Producer produced: control to the producer thread to produce
"+ value); the item and add it to
list.add(value++); the list. If the list is not empty, we remove
notify(); the item from the list. We have the notify
Thread.sleep(1000); method to notify the producer to produce
} the item.
}
}
Infinite Loop: The method runs indefinitely, producing values continuously.
Synchronization (synchronized (this)): Ensures that only one thread can
execute this block at a time.
Wait Condition: (while (list.size() == capacity)
wait() :
● If the shared resource reaches its capacity, the producer thread waits.
● wait(); releases the lock on this, allowing consumer threads to
consume items.
Notify Consumer (notify()); : Wakes up one waiting consumer thread, so it
can consume an item.
Thread Sleep (Thread.sleep(1000); :Introduces a delay before producing
the next item.
sleep() Method :
● Introduces a pause in the execution of the thread.
● Example : Thread.sleep(1000) - delay of 1000 milliseconds
(1 second).
● Why is this required ?
○ Prevents CPU Overload - if not introduced all the threads run
continuously in a tight loop, consuming CPU resources
unnecessarily.
○ Simulates Real-World Processing Time - In real-world scenarios,
producing and consuming data usually takes some time (e.g.,
fetching data from a database, writing to a file, or network delays).
It is used to mimic the delay.
○ Reduces Context Switching Overhead - Continuous context
switching is expensive. A short sleep period allows the CPU to
Is Sleep() mandatory ?

Would the program Work Without Thread.sleep()?


Yes, the program would still function without Thread.sleep(), but:
✅ The CPU would be heavily utilized.
✅ The output would be too fast to read.
✅ It might lead to performance issues on high-load systems.
Notify ()

● the notify() method wakes up one thread that is waiting on an


object.
● If multiple threads are waiting on an object, the thread scheduler
randomly selects one to wake up.
● In this problem, consumer threads wait for objects in a queue, and
producer threads put objects in the queue and notify the waiting
threads.
Consumer Function - Solution using Threads
synchronized (this): locks the instance,
public void consume() throws InterruptedException ensuring only one thread executes the block
{ at a time.
while (true) notify() : is used to notify the producer to
{ produce an item if needed.
synchronized (this)
{
while (list.size() == 0)
wait(); We add a sleep method at the end of
int val = list.removeFirst(); both producer and consumer methods
System.out.println("Consumer so that the output is not shown at once
consumed: "+ val); and we can see what is happening in
the code. We can change the value of
notify();
capacity to change the size of the list.
Thread.sleep(1000);
In our case, the list size is 1. We have
} the main class in which we create
} threads t1 and t2 for producer and
} consumer respectively and then run
both the threads.
Full Code :

The full code can be found at the following link :

https://www.scaler.com/topics/producer-consumer-problem-in-java/
Readers-Writers Problem

● The readers-writer problem is about managing


access to shared data.
● It allows:
○ Multiple readers to read data at the same time
without issues
○ Ensures that only one writer can write at a time,
and no one can read while writing is happening.
● This helps prevent data corruption and ensures
smooth operation in multi-user systems.
● A classic problem used to illustrate this issue is
Readers-Writers.
● The Readers-Writers problem refers specifically to
situations where a number of processes or threads
may possibly have access to some common resource,
like a database or a file.
● It also gives rise to the need for good
synchronization mechanisms so as not to bias the
requirement of readers against that of writers in
access to the resource, considering the integrity of
data.
Readers-Writers Problem
● A database is to be shared among several concurrent
processes.
● Readers - processes who want only to read the database,
● Writers - Processes which want to update (that is, to read
and write) the database.
● Precisely in OS we call this situation as the readers-
writers problem.
● Problem parameters:
○ One set of data is shared among a number of processes.
○ Once a writer is ready, it performs its write. Only one writer may
write at a time.
○ If a process is writing, no other process can read it.
○ If at least one reader is reading, no other process can write.
Solution of the Reader-Writer Problem

There are two fundamental solutions to the Readers-Writers problem:


● Readers Preference: In this solution, readers are given preference
over writers. That means that till readers are reading, writers will
have to wait. The Writers can access the resource only when no
reader is accessing it.

● Writer’s Preference: Preference is given to the writers. It simply


means that, after arrival, the writers can go ahead with their
operations; though perhaps there are readers currently accessing the
resource.
Semaphores
● A semaphore controls access to a shared resource through the use of
a counter.
● If the counter is greater than zero, then access is allowed(gain acccess to
the lock).
● If it is zero, then access is denied ( cannot open the lock).
● WORKING:
○ If the semaphore’s count is greater than zero, then the thread acquires
a permit, which causes the semaphore’s count to be decremented.
○ Otherwise, the thread will be blocked until a permit can be acquired.
○ When the thread no longer needs an access to the shared resource, it
releases the permit, which causes the semaphore’s count to be
incremented.
○ If there is another thread waiting for a permit, then that thread will acquire
a permit at that time.
Full code

https://onecompiler.com/java/3xbkf3pxe
Summary :

Thread class (Inbuilt class) : The Thread class in Java is part of the
java.lang package and is used to create and manage threads in a
multithreading environment.
Methods of Thread Class
Methods Action Performed

start() Causes this thread to begin execution; the Java Virtual Machine calls the run method of
this thread

run() If this thread was constructed using a separate Runnable run object, then that Runnable
object’s run method is called; otherwise, this method does nothing and returns

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

getId() Returns the identifier of this Thread

getState() Returns the state of this thread

isAlive() Tests if this thread is alive

join() Waits for this thread to die

sleep(long millis Causes the currently executing thread to sleep (temporarily cease execution) for the
) specified number of milliseconds
Event Handling
What is Event Handling ?

● Event Handling is the mechanism that controls


the event and decides what should happen if an
event occurs.
● What is an event ?
● An event can be defined as changing the state of
an object or behavior by performing actions.
● Actions can be a button click, cursor movement,
keypress through keyboard or page scrolling, etc.
Events
● Event is an object that describes a state change in a source.
● An event can be generated as a consequence of a person
interacting with the elements in a graphical user interface.
● Some of the activities that cause events to be generated are :
○ pressing a button
○ entering a character via the keyboard
○ selecting an item in a list
○ clicking the mouse.
● Events may also occur that are not directly caused by interactions
with a user interface.
○ Event may be generated when a timer expires,
○ a counter exceeds a value
○ software or hardware failure occurs
○ An operation is completed.
The Delegation Event Model

● The modern approach to handle events is by making use of the


Delegation Event Model.
● Its concept is quite simple: a source generates an event and
sends it to one or more listeners.
● In this scheme, the listener simply waits until it receives an event.
● Once an event is received, the listener processes the event and
then returns.
● Listeners must register with a source in order to receive an event
notification.
○ This provides an important benefit: notifications are sent only to listeners that
want to receive them.
Event Sources

● A source is an object that generates an event.


● This occurs when the internal state of that object changes in
some way.
● Sources may generate more than one type of event.
● A source must register listeners in order for the listeners to
receive notifications about a specific type of event.
● Each type of event has its own registration method.
● Here is the general form:

public void addTypeListener (TypeListener el )


public void addTypeListener (TypeListener el )

● Here, Type is the name of the event, and el is a reference to the


event listener.
● For example:
○ The method that registers a keyboard event listener is called addKeyListener( ).
○ The method that registers a mouse motion listener is called
addMouseMotionListener( ).
● When an event occurs, all registered listeners are notified and
receive a copy of the event object.
● This is known as multicasting the event.
● In all cases, notifications are sent only to listeners that register to
receive them.
Event Listeners
● A listener is an object that is notified when an event occurs.
● It has two major requirements :
○ First, it must have been registered with one or more sources to receive
notifications about specific types of events.
○ Second, it must implement methods to receive and process these
notifications. In other words, the listener must supply the event handlers.
● The methods that receive and process events are defined in a set
of interfaces, such as those found in java.awt.event.
● For example, the MouseMotionListener interface defines two
methods to receive notifications when the mouse is dragged or
moved.
● When your program receives an event, it must process it
● At the root of the Java event class hierarchy is EventObject, which is
in java.util.
● It is the superclass for all events. Its one constructor is shown here:

EventObject(Object src)
● Here, src is the object that generates this event.
● EventObject defines two methods:
○ getSource( ) method : returns the source of the event. Its general
form is shown here: Object getSource( )
○ toString( ) : returns the string equivalent of the event.

● AWT - Abstract Window Toolkit is used to perform Event Handling in


Java
● The class AWTEvent, defined within the java.awt
package, is a subclass of EventObject.
● It is the superclass of all AWT- based events used by the
delegation event model.
● Its getID( ) method can be used to determine the type of
the event. The signature of this method is shown here:
int getID( )
● Typically, you won’t use the features defined by AWTEvent
directly. Rather, you will use its subclasses.
● To summarize:
○ EventObject is a superclass of all events.
○ AWTEvent is a superclass of all AWT events that are handled by
the delegation event model.
Sources of Events
● User interface components that can generate the events which
were explained in the prev slide.
Event Listener Interfaces

● The delegation event model has two parts: sources


and listeners.
● Listeners are created by implementing one or more
of the interfaces defined by the java.awt.event
package.
● When an event occurs, the event source invokes the
appropriate method defined by the listener and
provides an event object as its argument.
1. ActionListener

● actionPerformed(ActionEvent e) → Handles button clicks and other action events.

2. AdjustmentListener

● adjustmentValueChanged(AdjustmentEvent e) → Handles changes in adjustable components like scrollbars.

3. ComponentListener

● componentResized(ComponentEvent e) → Detects when a component is resized.


● componentShown(ComponentEvent e) → Detects when a component becomes visible.
● componentMoved(ComponentEvent e) → Detects when a component is moved.
● componentHidden(ComponentEvent e) → Detects when a component is hidden.

4. ContainerListener

● componentAdded(ContainerEvent e) → Detects when a component is added to a container.


● componentRemoved(ContainerEvent e) → Detects when a component is removed from a container.

5. FocusListener

● focusGained(FocusEvent e) → Detects when a component gains focus.


● focusLost(FocusEvent e) → Detects when a component loses focus.
6. ItemListener
● itemStateChanged(ItemEvent e) → Handles changes in items like checkboxes and combo boxes.

7. KeyListener
● keyTyped(KeyEvent e) → Detects when a key is typed.
● keyPressed(KeyEvent e) → Detects when a key is pressed.
● keyReleased(KeyEvent e) → Detects when a key is released.

8. MouseListener
● mousePressed(MouseEvent e) → Detects when a mouse button is pressed.
● mouseClicked(MouseEvent e) → Detects when a mouse button is clicked.
● mouseEntered(MouseEvent e) → Detects when the mouse enters a component.
● mouseExited(MouseEvent e) → Detects when the mouse exits a component.
● mouseReleased(MouseEvent e) → Detects when a mouse button is released.

9. MouseMotionListener
● mouseMoved(MouseEvent e) → Detects when the mouse moves.
● mouseDragged(MouseEvent e) → Detects when the mouse is dragged.
10. MouseWheelListener
● mouseWheelMoved(MouseWheelEvent e) → Detects mouse wheel movement.

11. TextListener
● textChanged(TextEvent e) → Detects changes in text components like text fields and text
areas.

12. WindowListener
● windowActivated(WindowEvent e) → Detects when a window is activated.
● windowDeactivated(WindowEvent e) → Detects when a window is deactivated.
● windowOpened(WindowEvent e) → Detects when a window is opened.
● windowClosed(WindowEvent e) → Detects when a window is closed.
● windowClosing(WindowEvent e) → Detects when a window is about to close.
● windowIconified(WindowEvent e) → Detects when a window is minimized.
● windowDeiconified(WindowEvent e) → Detects when a window is restored from a
minimized state
Example : in the text file
Revision - Interface in JAVA

● An Interface in Java programming language is defined as an


abstract type used to specify the behavior of a class.
● A Java interface contains static constants and abstract methods.
● The interface in Java is a mechanism to achieve abstraction.
● By default, variables in an interface are public, static, and final.
● It is used to achieve abstraction and multiple inheritances in Java.
● A class that implements an interface must implement all the
methods declared in the interface.
● To implement the interface, use the implements keyword.
Adapter Classes
● It simplifies the creation of event handlers in certain situations.
● An adapter class provides an empty implementation of all methods in an
event listener interface.
● Adapter classes are useful when you want to receive and
process only some of the events that are handled by a
particular event listener interface.
● You can define a new class to act as an event listener by extending one
of the adapter classes and implementing only those events in which you
are interested.
● For example, the MouseMotionAdapter class has two methods,
mouseDragged( ) and mouseMoved( ), which are the methods
defined by the MouseMotionListener interface. If you were
interested in only mouse drag events, then you could simply extend
MouseMotionAdapter and override mouseDragged( ).
Example : in the text file
Origins of Swing
● The AWT support limited graphical interface.
● One reason for the limited nature of the AWT is that the look and
feel of a component is defined by the platform, not by Java.
● Because the AWT components use native code (directly run by
processor no Virtual machine to translate the code)resources ,
they are referred to as heavyweight. This leads to several
problems :
○ Because of variations between operating systems, a component
might look, or even act, differently on different platforms.
○ Second, the look and feel of each component was fixed (because
it is defined by the platform) and could not be (easily) changed.
○ Third, the use of heavyweight components caused some
frustrating restrictions.
Swing Is Built on the AWT
● Swing does not replace AWT.
● Instead, Swing is built on the foundation of the AWT.
This is why the AWT is still a crucial part of Java.
● Swing also uses the same event handling mechanism as
the AWT.
● Swing is a Java Foundation Classes [JFC] library and an
extension of the Abstract Window Toolkit [AWT].
● Java Swing offers much-improved functionality over AWT,
new components, expanded components features, and
excellent event handling with drag-and-drop support.
● Swing has about four times the number of User Interface [UI]
components as AWT
Two Key Swing Features

● Swing was created to address the limitations present in the AWT


● It does this through two key features:
○ lightweight components
○ pluggable look and feel.
Swing Components Are Lightweight
● Swing components are lightweight.
● They are written entirely in Java and do not map directly
to platform-specific peers.
● Thus, lightweight components are more efficient and
more flexible.
● Because lightweight components do not translate into
native peers, the look and feel of each component is
determined by Swing, not by the underlying operating
system.
● As a result, each component will work in a consistent
Swing Supports a Pluggable Look and Feel (PLAF)
● Since the look and feel of a component is under the control of
Swing, this means that it is possible to separate the look and
feel of a component from the logic of the component.
● Separating out the look and feel provides a significant advantage: it
becomes possible to change the way that a component is
rendered without affecting any of its other aspects.
● In other words, it is possible to “plug in” a new look and feel for any
given component without creating any side effects in the code that
uses that component.
● To use a specific style, its look and feel is simply “plugged in.”
● Once this is done, all components are automatically rendered using
that style.
PLAF Examples

1. In Windows, you can switch between Light Mode and Dark


Mode without changing the core functionality.
2. Web Browsers (Chrome, Firefox, Edge) : Users can
switch between light and dark modes, or install custom
themes.
3. WhatsApp, Instagram, YouTube : You can toggle
between Light Mode and Dark Mode in settings.
4. Android and iOS Themes : Users can install different
themes that change fonts, colors, and icons without
affecting functionality.
Advantages of PLAF

● It is possible to define a look and feel that is consistent


across all platforms.
● Conversely, it is possible to create a look and feel that
acts like a specific platform.
● For example, if you know that an application will be running
only in a Windows environment, it is possible to specify the
Windows look and feel.
● It is also possible to design a custom look and feel.
● Finally, the look and feel can be changed dynamically at
run time.
Components and Containers
● A component is an independent visual control - a push button or
slider.
● A container holds a group of components.
● Thus, a container is a special type of component that is designed to
hold other components.
● Furthermore, in order for a component to be displayed, it must be
held within a container.
● Thus, all Swing GUIs will have at least one container.
● Because containers are components, a container can also hold other
containers. This enables Swing to define what is called a
containment hierarchy, at the top of which must be a top-level
container
Components

● Swing components are derived from the JComponent class.


● JComponent inherits the AWT classes Container and Component.
● All of Swing’s components are represented by classes defined within
the package javax.swing.
Class names for Swing Components
Containers - top-level containers
● The first are top-level containers: JFrame, JApplet, JWindow,
and JDialog.
● These containers do not inherit JComponent.
● Unlike Swing’s other components the top-level containers are
heavyweight.
● This makes the top-level containers a special case in the Swing
component library.
● As the name implies, a top-level container must be at the top of
a containment hierarchy.
● A top-level container is not contained within any other
container.
● Furthermore, every containment hierarchy must begin with a top-
level container.
Containers - lightweight containers
● The second type of containers supported by Swing are
lightweight containers.
● Lightweight containers do inherit JComponent.
● An example of a lightweight container is JPanel, which is a
general-purpose container.
● Lightweight containers are often used to organize and manage
groups of related components because a lightweight
container can be contained within another container.
● Thus, you can use lightweight containers such as JPanel to
create subgroups of related controls that are contained within an
outer container.
The Swing Packages
● Swing is a very large subsystem and makes use of many packages.
● The main package is javax.swing.
● This package must be imported into any program that uses Swing.
● It contains the classes that implement the basic Swing components,
such as push buttons, labels, and check boxes.
Explanation :
● In the process, it demonstrates several key features of Swing.
● It uses two Swing components: JFrame and JLabel.
● JFrame is the top-level container that is commonly used for Swing
applications.
● JLabel is the Swing component that creates a label, which is a
component that displays information.
● The label is Swing’s simplest component because it is passive.
● That is, a label does not respond to user input. It just displays output.
● The program uses a JFrame container to hold an instance of a JLabel.
● The label displays a short text message
Fig 1 : Initial Frame which is Fig 2 : After Writing in the text field
displayed and pressing the button ( Event

You might also like