0% found this document useful (0 votes)
14 views154 pages

Lecture Slide - Week 8 (4)

The document provides an overview of multithreading in Java, explaining its definition, benefits, and applications. It covers the thread lifecycle, types of threads, and methods for creating and managing threads, including synchronization and preventing deadlocks. Additionally, it discusses the differences between processes and threads, emphasizing the advantages of using threads for better resource utilization and performance.

Uploaded by

xylem3009
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)
14 views154 pages

Lecture Slide - Week 8 (4)

The document provides an overview of multithreading in Java, explaining its definition, benefits, and applications. It covers the thread lifecycle, types of threads, and methods for creating and managing threads, including synchronization and preventing deadlocks. Additionally, it discusses the differences between processes and threads, emphasizing the advantages of using threads for better resource utilization and performance.

Uploaded by

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

OBJECT ORIENTED

PROGRAMMING
USING JAVA
 Multithreading in java
 Thread

OUTLINE  Scheduler
 Thread lifecycle
 Java Swing and AWT
WHAT IS MULTITHREADING??

• Multithreading is a Java feature that allows concurrent execution of two or more parts
of a program for maximum utilization of CPU.
• Each part of such program is called a thread. So, threads are light-weight processes
within a process.
• Each of the threads can run in parallel.
APPLICATION OF MULTITHREADING?

 Mobile application usage and updation.


 Browsing displaying images in webpages.
 Websites displaying ads.
 Webcrawlers.
MOTIVATION OF MULTITHREADING?
 We know sequential programming
 Certain task block. E.g. read() in I/O
 Blocking halts CPU time thus wasting CPU time.

Solution: Concurrent programming


Why???
Helps in better recourse utilization and throughput.

“But Concurrent programming is complex”


EXAMPLE:
THREADS

 Post-os era- computers ran a single program.


 OS- multiple processes to run on concurrent
 Multitasking : switching CPU from processes to another(illusion of parallelism:
does not imply parallelism-)
“Better resource utilization”

“ Better resource utilization leads to the development of threads”


THREADS
 Single sequential flow of control within a process.
 Light weight processes.
 A process can have multiple threads.
 Threads share processes wide recourses e.g. Memory.
 Threads has its own PC, Stack and local variable.
BENEFITS OF THREADS

 Exploiting multiple processors (thus achieving parallelism);


 Always loosely coupled designs.
 Better throughput even in single CPU machines.
THREADS TYPES

 Daemon threads
 Background threads which are useful for tasks such as garbage collection
 Non-Daemon
 Created within application
 Main thread: created by JVM to run main()
 JVM will not terminate if at least one non-daemon thread is running
LAUNCHING A THREAD

 Case 1: By extending thread class


 Case 2: By implementing runnable interface
 Create Task
 Runnable task=new MyRunnable();
 Runnable has exactly one method run()
 Creating a thread with task
 Thread thread=new Thread(task); // NEW
 Start Thread
 Thread.start(); //Runnable
 New call stack with run() is created for thread
CASE 1: BY EXTENDING THREAD CLASS

Job of a Defining a thread


thread
THREAD SCHEDULER

 It is the part of jvm.


 It is responsible to schedule threads.
 If multiple threads are waiting to get a chance of execution , in which order threads
are executed is done by thread scheduler.
 We cant expect exact algorithm followed by thread scheduler it is varied from jvm to
jvm, hence we cant expect thread execution order and exact order.
 Hence whenever there is no guarantee of exact output, but we can provide all possible
outputs.
DIFFERENCE BETWEEN t.start() vs t.run()
DIFFERENCE BETWEEN t.start() vs t.run()

Number of thread:1
Number of thread:2
• Here a new thread is created which is • Here a new thread is not created and is executed in a
responsible for the execution of run method normal method call.
• Overloading not possible. • Overloading possible.
• It is mandatory to override run() method.
Otherwise don’t use thread.
THREAD LIFECYCLE

If run()
methods
conpletes
New t.start() Ready Running Dead
state state state state
If thread
scheduler
Mythread t=new mythread();
allocates
processor

Note:after starting a thread if we again start a thread we will get a RE:


illegalthreadstateelements
THREAD SCHEDULER
THREAD LIFECYCLE
EXAMPLE
DEFINE A THREAD BY RUNNABLE INTERFACE

Runnable
interface

Thread
class

Mythread
subclass Myrunnable
DEFINE A THREAD BY RUNNABLE INTERFACE
WHICH APPROACH WE SHOULD WE PREFER/RECOMMEND??
 Case 1: By extending thread class
 Case 2: By implementing runnable interface
THREAD CLASS CONSTRUCTOR

1. Thread t=new Thread()


2. Thread t=new Thread(Runnable r)
3. Thread t=new Thread(String name)
4. Thread t=new Thread(Runnable target, String name)
5. Thread t=new Thread(ThreadGroup group, String name)
6. Thread t=new Thread(ThreadGroup group, Runnable target)
7. Thread t=new Thread(ThreadGroup group, Runnable target, String name)
8. Thread t=new Thread(ThreadGroup group, Runnable target, String name, long stackSize)
THREAD CLASS METHODS
Sr.No. Method & Description

1 public void start()


Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
2 public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that
Runnable object.
3 public final void setName(String name)
Changes the name of the Thread object.There is also a getName() method for retrieving the name.
4 public final void setPriority(int priority)
Sets the priority of this Thread object.The possible values are between 1 and 10.
5 public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
6 public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the
second thread terminates or the specified number of milliseconds passes.
7 public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8 public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to
completion.
THREAD CLASS METHODS
Sr.No. Method & Description

1 public static void yield()


Causes the currently running thread to yield to any other threads of the same priority that
are waiting to be scheduled.
2 public static void sleep(long millisec)
Causes the currently running thread to block for at least the specified number of
milliseconds.
3 public static boolean holdsLock(Object x)
Returns true if the current thread holds the lock on the given Object.
4 public static Thread currentThread()
Returns a reference to the currently running thread, which is the thread that invokes this
method.
5 public static void dumpStack()
Prints the stack trace for the currently running thread, which is useful when debugging a
multithreaded application.
GETNAME AND SETNAME METHOD
THREAD PRIORITY
 It may be default priority set by jvm
 It may be customized priority set by programmer

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
THREAD PRIORITY: EXAMPLE
METHODS THROUGH WHICH WE CAN PREVENT THREAD
EXECUTION

1 2 3
yield() join() sleep()
YIELD():
• A yield() method is a static method of Thread class and it can stop the currently executing thread and will give
a chance to other waiting threads of the same priority.
• If in case there are no waiting threads or if all the waiting threads have low priority then the same thread will
continue its execution.
• The advantage of yield() method is to get a chance to execute other waiting threads so if our current thread
takes more time to execute and allocate processor to other threads.
• We can use the yield() method to temporarily release time for other threads. For example,
public void run() {
for (int i = 1; i <= lastNum; i++) {
System.out.print(" " + i);
Thread.yield();
}
}
• Every time a number is printed, the current thread is yielded. So, the numbers are printed after the characters.
YIELD(): EXAMPLE
YIELD(): EXAMPLE
JOIN():
• The join() method waits for a thread to die.
• In other words, it causes the currently running threads to stop executing until the thread it joins with completes its
task.
• If a thread want to wait until completing some other thread then we should go for join method.
• For example if a thread t1 wants to wait until completing t2 then t1 has to call t2.join().
• If t1 executes t2.join then immediately t1 will be entered into waiting state until t2 completes.
• Once t2 completes then t1 can continue its execution.

public void run() { Thread Thread


Thread thread4 = new Thread( print100 printA
new PrintChar('c', 40));
thread4.start();
try {
for (int i = 1; i <= lastNum; i++) { printA.join()
System.out.print(" " + i);
if (i == 50) thread4.join(); Wait for printA
} to finish
}
catch (InterruptedException ex) { printA finished
}
JOIN():EXAMPLE
JOIN():EXAMPLE
SLEEP():
• The sleep() method of Thread class is used to sleep a thread for the specified amount of
time.
• The java.lang.Thread.sleep(long millis) method causes the currently executing thread to sleep
for the specified number of milliseconds, subject to the precision and accuracy of system
timers and schedulers.
• Method Whenever Thread.sleep() functions to execute, it always pauses the current thread
execution.
• If any other thread interrupts when the thread is sleeping, then InterruptedException will be
thrown.
• If the system is busy, then the actual time the thread will sleep will be more as compared to
that passed while calling the sleep method and if the system has less load, then the actual
sleep time of the thread will be close to that passed while calling sleep() method.
SLEEP():EXAMPLE
THREADS STATES

yield(), or Running
time out run() returns
Thread created start()
New Ready run() join() Finished

sleep()
interrupt()
Target wait()
finished

Wait for target Wait for time Wait to be


to finish out notified
Time out notify() or
notifyAll()
Blocked
Interrupted()
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.
• So it needs to be made sure by some synchronization method that only one thread can
access the resource at a given point of time.
• Cause race condition
•Why do we require Synchronization? Ans: To achieve
Consistency.

Step balance thread[i] thread[j]

1 0 newBalance = bank.getBalance() + 1;
2 0 newBalance = bank.getBalance() + 1;
3 1 bank.setBalance(newBalance);
4 1 bank.setBalance(newBalance);
THE SYNCHRONIZED KEYWORD
• The synchronized keyword can be used to mark four different types of blocks:
• Instance methods
• Static methods
• Code blocks inside instance methods
• Code blocks inside static methods
• To avoid race conditions, threads must be prevented from simultaneously entering
certain part of the program, known as critical region.
• The critical is the entire deposit method. You can use the synchronized keyword to
synchronize the method so that only one thread can access the method at a time.

public synchronized void deposit(double amount) {


int newBalance= balance + amount;
Balance = newBalance;
}
SYNCHRONIZING INSTANCE METHODS AND STATIC METHODS

• With the deposit method synchronized, the preceding scenario cannot happen. If Task
2 starts to enter the method, and Task 1 is already in the method, Task 2 is blocked
until Task 1 finishes the method.
THE SYNCHRONIZED KEYWORD
• The synchronized keyword can be used to mark four different types of blocks:
• Instance methods
• Static methods
• Code blocks inside instance methods
• Code blocks inside static methods
EXAMPLE:
EXAMPLE:
SYNCHRONIZED BLOCK IN JAVA
• Synchronized block can be used to perform synchronization on any specific resource of
the method.
• Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
• If you put all the codes of the method in the synchronized block, it will work same as
the synchronized method

Syntax to use synchronized block:

synchronized (object reference expression) {


//code block
}
EXAMPLE:
DEADLOCK
• Sometimes two or more threads need to acquire the locks on several shared objects.
This could cause deadlock, in which each thread has the lock on one of the objects and
is waiting for the lock on the other object. Consider the scenario with two threads and
two objects, as shown. Thread 1 acquired a lock on object1 and Thread 2 acquired a
lock on object2. Now Thread 1 is waiting for the lock on object2 and Thread 2 for the
lock on object1. The two threads wait for each other to release the in order to get the
lock, and neither can continue to run.
Step Thread 1 Thread 2

1 synchronized (object1) {
2 synchronized (object2) {
3 // do something here
4 // do something here
5 synchronized (object2) {
6 synchronized (object1) {
// do something here // do something here
} }
} }

Wait for Thread 2 to Wait for Thread 1 to


release the lock on object2 release the lock on object1
PREVENTING DEADLOCK
• Deadlock can be easily avoided by using a simple technique known as resource
ordering. With this technique, you assign an order on all the objects whose locks must
be acquired and ensure that each thread acquires the locks in that order. For the
example, suppose the objects are ordered as object1 and object2. Using the resource
ordering technique, Thread 2 must acquire a lock on object1 first, then on object2.
Once Thread 1 acquired a lock on object1, Thread 2 has to wait for a lock on object1.
So Thread 1 will be able to acquire a lock on object2 and no deadlock would occur.
Outline
▪ Process versus Thread

▪ Synchronization

▪ Multithreading with Java

Multithreading 55
Process versus Thread.
Synchronization

Multithreading 56
Process Model
▪ A process is a sequential program in execution.
▪ A process is a unit of computation.
▪ Process components:
▪ The program (code) to be executed.
▪ The data on which the program will execute.
▪ Resources required by the program.
▪ The status of the process execution.
▪ A process runs in an abstract machine environment (could be OS) that
manages the sharing and isolation of resources among the community of
processes.
Code Data
Process Status
Resource

Abstract Machine Environment

Multithreading 57
Program and Process

Program and process – distinction?


▪ A program is a static entity made up of program statements. The
latter define the run-time behavior.

▪ A process is a dynamic entity that executes a program on a


particular set of data.

▪ Two or more processes could execute the same program, each


using their own data and resources.

Multithreading 58
Thread Model
▪ A thread is an alternative form (to the process) of schedulable unit of
computation.
▪ In the thread model:
▪ Each thread is associated with a process.
▪ A thread is an entity that executes by relying on the code and resources,
holding by the associated process.
▪ Several threads could be associated with a single process. Those threads
share the code and resources of the process.
▪ A thread allocates part of the process’s resources for its needs.
▪ A thread has its own data and status.

Resource

Process Thread

Data Code Data


Process Status Thread Status

Multithreading 59
Thread Model
▪ Control in a normal program usually follows a single thread of
execution.

▪ What differentiates threads from normal processes is the shared


memory (objects), which is visible to all threads in a multi-
threaded program.

▪ A thread has much less overhead than a process so is sometimes


called as light-weight process.

▪ Multithreading allows an application to have multiple threads


of execution running concurrently.

Multithreading 60
Concurrency and Parallelism
▪ Concurrent multithreading systems give the appearance of
several tasks executing at once, but these tasks are actually
split up into chunks that share the processor with chunks from
other tasks.
▪ In parallel systems, two tasks are actually performed
simultaneously. Parallelism requires a multi-CPU system.

Multithreading 61
Multitasking
Multitasking operating systems run multiple programs simultaneously.
Each of these programs has at least one thread within it - single-threaded
process:
▪ The process begins execution at a well-known point. In Java, C# or C++, the
process begins execution at the first statement of the function called main().
▪ Execution of the statements follows in a completely ordered, predefined
sequence for a given set of inputs.
▪ While executing, the process has access to certain data – local, global, static
etc.

Multithreading 62
Multithreading
▪ A program with multiple threads running within a single instance could be
considered as a multitasking system within an OS.
▪ In a multithreading program, threads have the following properties:
▪ A thread begin execution at a predefined, well-known location. For one of
the threads in the program, that location is the main() method; for the rest of
the threads, it is a particular location the programmer decides on when the
code is written.
▪ A thread executes code in an ordered, predefined sequence.
▪ A thread executes its code independently of the other threads.
▪ The threads appear to have a certain degree of simultaneous execution.

Multithreading 63
Threading Models

There are typically two threading models supported by OS:


▪ Cooperative Threading Model;
▪ Preemptive Threading Model.

Cooperative Threading Model


▪ In a cooperative system, a thread retains control of the
processor until it decides to give it up (which might be never).
▪ Supporting OS – Windows 3.x, Solaris, Mac OS.
▪ The various threads have to cooperate with each other. If not,
some of them will be starving (never given a chance to run).
▪ Scheduling in most cooperative systems is done strictly by
priority level - when the current thread gives up control, the
highest-priority waiting thread gets control.
Multithreading 64
Threading Models

Preemptive Threading Model


▪ In a preemptive system, some sort of timer is used by the
operating system itself to cause a context swap.
▪ Supporting OS – Windows 9x, XP, NT (2000), Solaris, Linux.
▪ When the timer "ticks" the OS can abruptly take control away
from the running thread and give control to another thread.
▪ The interval between timer ticks is called a time slice.
▪ To get to concurrency, the OS must do the thread scheduling.
▪ Preemptive systems are less efficient than cooperative ones
because the thread management must be done by the OS’
kernel, but they are easier to program (except their
synchronization).

Multithreading 65
Synchronization
Background
▪ Concurrent access to shared data may result in data
inconsistency.
▪ Maintaining data consistency requires mechanisms to ensure the
orderly execution of cooperating processes (or threads).

When do we need synchronization?


When two or more processes (or threads) work on the same
data simultaneously.

Multithreading 66
Synchronization
Example:
Two threads are trying to update the same shared variable
simultaneously:
▪ The result is unpredictable.

▪ The result depends on which of the two threads was the last
one to change the value.
▪ The competition of the threads for the variable is called race
condition.
▪ The first thread is the one who wins the race to update the
variable.

Multithreading 67
Classical Synchronization Problems
Mutual exclusion
▪ Only one process executes a piece of code (critical section) at
any time.
▪ OS examples: access to shared resources, e.g., a printer.

Sequencing
▪ A process waits for another process to finish executing some
code.
▪ OS examples: waiting for an event, e.g., ls (dir) command
suspends until there is some data to read from the file system.

Multithreading 68
Classical Synchronization Problems
Bounded-buffer
(also referred to as the Producer-Consumer problem)

▪ A pool of n buffers.
▪ Producer processes put items into the pool.
▪ Consumer processes take items out of the pool.
▪ Issues: mutual exclusion, empty pool, and full pool.
▪ OS examples: buffering for pipes, file caches, etc.

Multithreading 69
Classical Synchronization Problems
Readers-Writers
▪ Multiple processes access a shared data object X.
▪ Any number of readers can access X at the same time.
▪ No writer can access it at the same time as a reader or another
writer.
▪ Mutual exclusion is too constraining. Why?
▪ Variations:
▪ reader-priority: a reader must not wait for a writer;

▪ writer-priority: a writer must not wait for a reader,

▪ OS examples: file locks.

Multithreading 70
Classical Synchronization Problems
Dining Philosophers
▪ 5 philosophers with 5 chopsticks placed between them.
▪ To eat requires two chopsticks.
▪ Philosophers alternate between thinking and eating.
▪ OS examples: simultaneous use of multiple resources.

Many examples, along with Java code


▪ http://www.doc.ic.ac.uk/~jnm/book/book_applets/concurrency.ht
ml

Multithreading 71
The Critical Section Problem
Definition:
A critical section is a piece of code that accesses a shared
resource (data structure or device) that must not be concurrently
accessed by more than one thread of execution.

Conditions:
▪ n processes (or threads) all competing to use some shared data.
▪ Each process has a code segment, called critical section, in
which the shared data is accessed.

Problem:
How to ensure that when one process is executing in its
critical section, no other process is allowed to execute in its
critical section?
Multithreading 72
The Critical Section Problem - Example
Suppose that two processes are trying to increment the same
variable. They both execute the statement
x := x + 1;

To execute this statement each process reads the variable x, then


adds one to the value, then write it back.
Suppose the value of x is 3.
▪ If both processes read x at the same time then they would get
the same value 3.
▪ If they then both added 1 to it then they would both have the
value 4.
▪ They would then both write 4 back to x.
▪ The result is that both processes incremented x, but its value is
only 4, instead of 5.
Multithreading 73
The Critical Section Problem
Solution – three requirements:
▪ Only one process is allowed to be in its critical section at a time.
Hence, the execution of critical sections is mutually exclusive.

▪ If
there is no process in its critical section, but some processes are
waiting to enter their critical sections, only the waiting processes
may compete for getting in. Ultimately, there must be progress in
the resolution and one process must be allowed to enter.

▪ Processes
waiting to enter their critical sections must be allowed
to do so in a bounded timeframe. Hence, processes have
bounded waiting.

Multithreading 74
The Critical Section Problem
Critical sections are General Framework for process (thread)
synchronization:

ENTRY SECTION
CRITICAL SECTION CODE
EXIT SECTION

▪ The ENTRY SECTION controls access to make sure no


more than one process Pi gets to access the critical section at
any given time. It acts as a guard.
▪ The EXIT SECTION does bookkeeping to make sure that
other processes that are waiting know that Pi has exited.

Multithreading 75
Semaphores
▪ The Semaphores are a solution to the Critical Section Problem.
▪ Help in making the Critical Section atomic.

A semaphores is:
▪ a single integer variable S;
Mutual Exclusion Semaphore
▪ accessed via two atomic operations:
▪ WAIT (sometimes denoted by P) //**** initially S = 1
while S <= 0 do wait();
P( S ) //**** WAIT
S := S-1;
CRITICAL SECTION
▪ SIGNAL (sometimes denoted by V) V( S ) //**** SIGNAL
S := S+1;
▪ wake up a waiting process (if any);

▪ WAITing processes cannot “lock out” a SIGNALing process.

Binary semaphores - S is restricted to take on only the values 0 and 1.

Multithreading 76
Topic

Multithreading with Java

Multithreading 77
Threads in Java
▪ There are two ways to create a java thread:
▪ By extending the java.lang.Thread class.
▪ By implementing the java.lang.Runnable interface.
▪ The run() method is where the action of a thread takes place.
▪ The execution of a thread starts by calling its start() method.
class PrimeThread extends Thread {
long minPrime;
PrimeThread(long minPrime) {
this.minPrime = minPrime; }
public void run() {
// compute primes larger than minPrime . . .
}
}
▪ The following code would then create a thread and start it running:
PrimeThread p = new PrimeThread(143);
p.start();
Multithreading 78
Implementing the Runnable Interface
▪ In order to create a new thread we may also provide a class that implements
the java.lang.Runnable interface.
▪ Preferred way in case our class has to subclass some other class.
▪ A Runnable object can be wrapped up into a Thread object:
▪ Thread(Runnable target)
▪ Thread(Runnable target, String name)
▪ The thread’s logic is included inside the run() method of the runnable object.

class ExClass class A {


extends ExSupClass …
implements Runnable { main(String[] args) {
… …
public ExClass (String name) { Thread mt1 = new Thread(new ExClass("thread1”));
} Thread mt2 = new Thread(new ExClass("thread2”));
public void run() { mt1.start();
… mt2.start();
} }
} }

Multithreading 79
Implementing the Runnable Interface
▪ Constructs a new thread object associated with the given Runnable object.
▪ The new Thread object's start() method is called to begin execution of the
new thread of control.
▪ The reason we need to pass the runnable object to the thread object's
constructor is that the thread must have some way to get to the run() method
we want the thread to execute. Since we are no longer overriding the run()
method of the Thread class, the default run() method of the Thread class is
executed:
public void run() {
if (target != null) {
target.run();
}
}
▪ Here, target is the runnable object we passed to the thread's constructor. So
the thread begins execution with the run() method of the Thread class, which
immediately calls the run() method of our runnable object.

Multithreading 80
Sleep, Yield, Notify & Wait Thread’s Functions
▪ sleep(long millis) - causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of
milliseconds.
▪ yield() - causes the currently executing thread object to
temporarily pause and allow other threads to execute.
▪ wait() - causes current thread to wait for a condition to occur
(another thread invokes the notify() method or the notifyAll()
method for this object). This is a method of the Object class and
must be called from within a synchronized method or block.
▪ notify() - notifies a thread that is waiting for a condition that the
condition has occurred. This is a method of the Object class and
must be called from within a synchronized method or block.
▪ notifyAll() – like the notify() method, but notifies all the threads
that are waiting for a condition that the condition has occurred.
Multithreading 81
The Lifecycle of a Thread
▪ The start() method creates the system resources necessary to run the thread,
schedules the thread to run, and calls the thread's run() method.
▪ A thread becomes Not Runnable when one of these events occurs:
▪ Its sleep() method is invoked.
▪ The thread calls the wait() method.
▪ The thread is blocked on I/O operations.
▪ A thread dies naturally when the run() method exits.

Multithreading 82
Thread Priority
▪ On a single CPU, threads actually run one at a time in such a way
as to provide an illusion of concurrency.

▪ Execution of multiple threads on a single CPU, in some order, is


called scheduling.

▪ The Java runtime supports a very simple scheduling algorithm


(fixed priority scheduling). This algorithm schedules threads
based on their priority relative to other runnable threads.

▪ The runtime system chooses the runnable thread with the highest
priority for execution.

Multithreading 83
Thread Priority
▪ If two threads of the same priority are waiting for the CPU, the
scheduler chooses one of them to run in a round-robin fashion -
each process is guaranteed to get its turn at the CPU at every
system-specified time interval.

▪ The chosen thread will run until:


▪ A higher priority thread becomes runnable.
▪ It yields (calls its yield() method), or its run() method exits.
▪ On systems that support time-slicing, its time allotment has
elapsed.

▪ You can modify a thread's priority at any time after its creation
by using the setPriority() method.

Multithreading 84
Synchronization of Java Threads
▪ In many cases concurrently running threads share data and must consider the
state and activities of other threads.
▪ If two threads can both execute a method that modifies the state of an object
then the method should be declared to be synchronized, those allowing only
one thread to execute the method at a time.
▪ If a class has at least one synchronized method, each instance of it has a
monitor. A monitor is an object that can block threads and notify them when
the method is available.

Example:
public synchronized void updateRecord() {
//**** critical code goes here …
}
▪ Only one thread may be inside the body of this function. A second call will be
blocked until the first call returns or wait() is called inside the synchronized
method.

Multithreading 85
Synchronization of Java Threads
▪ If you don’t need to protect an entire method, you can synchronize
on an object:
public void foo() {
synchronized (this) {
//critical code goes here …
}

}

▪ There are two syntactic forms based on the synchronized


keyword - blocks and methods.
▪ Block synchronization takes an argument of which object to
lock. This allows any method to lock any object.
▪ The most common argument to synchronized blocks is this.
▪ Block synchronization is considered more fundamental than
method synchronization.
Multithreading 86
Applying Synchronization (Example)
Consider the following class:
class Even {
private int n = 0;
Declaring the next method as
public synchronized int next(){
synchronized would resolve such
++n; conflicting problems.
++n;
return n; //**** next is always even
}
}
Without synchronizing, the desired postcondition may fail due to a storage conflict when
two or more threads execute the next method of the same Even object.
Here is one possible execution trace:

Multithreading 87
Synchronization of Java Threads
▪ To program the synchronization behavior we use the Object class’
methods wait(), notify() and notifyAll().

▪ With these methods we allow objects to wait until another object


notifies them:
synchronized( waitForThis ) {
try { waitForThis.wait();}
catch (InterruptedException ie) {}
}
▪ To wait on an object, you must first synchronize on it.
▪ InterruptedException is thrown when a thread is waiting,
sleeping, or otherwise paused for a long time and another thread
interrupts it using the interrupt method in class Thread.

Multithreading 88
Synchronization of Java Threads
▪ A thread may call wait() inside a synchronized method. A timeout
may be provided. If missing or zero then the thread waits until
either notify() or notifyAll() is called, otherwise until the timeout
period expires.

▪ wait() is called by the thread owning the lock associated with a


particular object.

▪ notify() or notifyAll() are only called from a synchronized


method. One or all waiting threads are notified, respectively. It’s
probably better (safer) to use notifyAll(). These methods don't
release the lock. The threads awakened will not return from their
wait() call immediately, but only when the thread that called
notify() or notifyAll() finally relinquishes ownership of the lock.
Multithreading 89
Synchronization of Java Threads

▪ The wait() method releases the lock prior to waiting, and


reacquires the lock prior to returning from the wait() method.

▪ It is possible a synchronized method to make a self-call to


another synchronized method on the same object without
freezing up.

▪ Methods that are not synchronized may still execute at any


time, even if a synchronized method is in progress. In other
words, synchronized is not equivalent to atomic, but
synchronization can be used to achieve atomicity.

Multithreading 90
Java Semaphore - Example

Multithreading 91
Protecting Static Fields
▪ Locking an object does not automatically protect access to the
static fields of that object's class or any of its superclasses.
▪ Access to static fields is instead protected via static synchronized
methods and blocks.

Consider the following class:


Will prevent outer access on n,
class Even { until the end of the next() method.
public static int n = 0;
public static synchronized int next(){ //**** will lock n as well and
++n;
++n;
return n; //**** next is always even
}
}

Multithreading 92
Java Threading API
:: Stopping Threads
▪ The Thread class does contain a stop() method that allows you to stop a thread
immediately: no matter what the thread is doing, it will be terminated.
▪ However, the stop() method is very dangerous. In Java 2, the stop() method is
deprecated.

Why?
▪ If a thread holds a lock at the time it is stopped, the lock will be released when
the thread stops.
▪ But if the thread that is being stopped is in the middle of updating a linked list,
for example, the links in the list will be left in an inconsistent state.
▪ Hence, if we were able to interrupt a thread in the middle of this operation, we
would lose the benefit of its obtaining the lock.
▪ The reason we needed to obtain a lock on the list in the first place was to
ensure that the list would not be found by another thread in an inconsistent
state.

Multithreading 93
Java Threading API
:: The suspend() and resume() Methods
▪ The suspend() and resume() methods are very dangerous and
they became deprecated.
▪ The problem with using the suspend() method is that it can
conceivably lead to cases of lock starvation - including cases
where the starvation shuts down the entire virtual machine.
▪ If a thread is suspended while it is holding a lock, that lock
remains held by the suspended thread. As long as that thread is
suspended, no other thread can obtain the lock.
▪ There is no danger in the resume() method itself, but since the
resume() method is useful only with the suspend() method, it too
has been deprecated.
▪ Java Thread primitives deprecation:
http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDe
precation.html
Multithreading 94
Java Threading API
:: Thread Naming
▪It is possible to assign a String name to the Thread object itself:
void setName(String name) //assigns a name to the Thread instance
String getName() //gets the name of the Thread instance

▪ The system does not use this string for any specific purpose.
▪ We can use it for debugging. With an assigned name, the debugger and the
toString() method display thread information in terms of a “logical" name
instead of a number.
▪ The naming support is also available as a constructor of the Thread class:
▪ Thread(String name) constructs a thread object with a name that is already
assigned. This constructor is used when threading by inheritance.
▪ Thread(Runnable target, String name) constructs a thread object that is
associated with the given Runnable object and is created with a name that is
already assigned. This constructor is used when threading by interfaces.

Multithreading 95
Java Threading API
:: Thread Access – The currentThread() Method
▪ static Thread currentThread() gets the Thread object that represents the
current thread of execution. The method is static and may be called through the
Thread class name.
Why is this method important?
▪ The Thread object for the current thread may not be saved anywhere, and even
if it is, it may not be accessible to the called method.
▪ In this code we are assuming that reader threads are threads whose names start
with "Reader." This name could have been assigned by the setName() method
earlier or when the threads were constructed.
▪ To obtain a name, we need simply
to call the getName() method.
However, since we do not have the
Thread object reference of the
caller, we must call the
currentThread() method to obtain
the reference.

Multithreading 96
Java Threading API
:: Thread Access – Enumerating Threads in JVM
The Thread class provides methods that allow you to obtain a list of all the
threads in the program:
▪ static int enumerate(Thread threadArray[]) gets all the thread objects of the
program and stores the result into the thread array. The value returned is the
number of thread objects stored into the array. The method is static and may be
called through the Thread class name.
▪ static int activeCount() returns the number of threads in the program. The
method is static and may be called through the Thread class name.

Multithreading 97
Objectives
 To distinguish simple GUI components.
 To describe the Java GUI API hierarchy.
 To create user interfaces using frames, panels, and simple UI
components.
 To understand the role of layout managers.
 To use the FlowLayout, GridLayout, and BorderLayout managers
to layout components in a container.
 To specify colors and fonts using the Color and Font classes.
 To use JPanel as subcontainers.

98
Creating GUI Objects
// Create a button with text OK
JButton jbtOK = new JButton("OK");

// Create a label with text "Enter your name: "


JLabel jlblName = new JLabel("Enter your name:"); Text Check Radio
field Box Butto
Label
n

Button

Combo
// Create a text field with text "Type Name Here"
JTextField jtfName = new JTextField("Type Name Here"); Box

// Create a check box with text bold


JCheckBox jchkBold = new JCheckBox("Bold");

// Create a radio button with text red


JRadioButton jrbRed = new JRadioButton("Red");

// Create a combo box with choices red, green, and blue


JComboBox jcboColor = new JComboBox(new String[]{"Red“,"Green“,"Blue"});
99
Swing vs. AWT
So why do the GUI component classes have a prefix J? Instead of JButton, why not name it
simply Button? In fact, there is a class already named Button in the java.awt package.

When Java was introduced, the GUI classes were bundled in a library known as the Abstract
Windows Toolkit (AWT).
AWT is fine for developing simple graphical user interfaces, but not for developing
comprehensive GUI projects.
Besides, AWT is prone/suffered/ to platform-specific bugs because its peer-based approach
relies heavily on the underlying platform.
With the release of Java 2, the AWT user-interface components were replaced by a more
robust, versatile, and flexible library known as Swing components.
Swing components are painted directly on canvases using Java code, except for components
that are subclasses of java.awt.Window or java.awt.Panel, which must be drawn using native
GUI on a specific platform.
Swing components are less dependent on the target platform and use less of the native GUI
resource.
For this reason, Swing components that don’t rely on native GUI are referred to as
lightweight components, and AWT components are referred to as heavyweight components.

100
Swing vs. AWT
Java AWT Java Swing
Java swing components are platform-
AWT components are platform-dependent.
independent.
AWT components are heavyweight. Swing components are lightweight.
AWT doesn't support pluggable look and Swing supports pluggable look and
feel. feel.
Swing provides more powerful
AWT provides less components than Swing. components such as tables, lists,
scrollpanes, colorchooser, tabbedpane etc.
AWT doesn't follows MVC(Model View
Controller) where model represents data, view
Swing follows MVC.
represents presentation and controller acts as an
interface between model and view.
101
GUI Class Hierarchy (Swing and AWT)

102
The Java GUI API
 The GUI API contains classes that can be classified into three groups:
Component classes, Container classes, and Helper classes.
 Component Classes: Component classes are elementary GUI
entities, such as JButton, JLabel, JTextField etc.
 Container Classes: The classes, such as JFrame, JPanel, and
JApplet, JDialog are called container classes used to contain other
components.
 Helper Classes: The classes, such as Graphics, Color, Font,
FontMetrics, and Dimension and LayoutManager, are called
helper classes used to support GUI components.
 Component is the root class of all the user-interface classes
including container classes, and JComponent is the root class of all
the lightweight Swing components.
103  Both Component and JComponent are abstract classes.
Container Classes

Container classes can contain


other GUI components.

104
GUI Helper Classes

Dimension Classes in the java.awt


LayoutManager package
Heavyweight
Font 1

FontMetrics

Object Color Panel Applet JApplet

Graphics

Component Container Window Frame JFrame


*
Dialog JDialog

JComponent JPanel Swing Components


The helper classes are not subclasses of in the javax.swing package
Component. They are used to describe
the properties of GUI components such
as graphics context, colors, fonts, and
Lightweight
105 dimension.
Swing GUI Components
JCheckBoxMenuItem

JMenuItem JMenu

AbstractButton JButton JRadioButtonMenuItem

JToggleButton JCheckBox

JRadioButton
JComponent JEditorPane

JTextComponent JTextField JPasswordField

JTextArea

JLabel JList JComboBox JPanel JOptionPane JScrollBar JSlider

JTabbedPane JSplitPane JLayeredPane JSeparator JScrollPane JRootPane

JToolBar JMenuBar JPopupMenu JFileChooser JColorChooser JToolTip

JTree JTable JTableHeader JInternalFrame JProgressBar JSpinner


106
AWT (Optional)
AWTEvent Container Panel Applet

Font Button Window Frame

FontMetrics Label Dialog FileDialog


TextField
Object Color TextComponent

TextArea
Graphics List

Component Choice

CheckBox

LayoutManager CheckBoxGroup

Canvas

MenuComponent MenuItem Menu

MenuBar
Scrollbar
107
Swing - Basic Components
 A Strategy for Designing GUI
 Identify needed components
 Choose layout managers
 FlowLayout
 GridLayout
 BorderLayout
 Sketch the GUI

108
Swing - Basic Components
 Category of components
1.Container components
2.Ordinary components
3.Menu components

109
Swing - Basic Components
1. Container Components
 JFrame
 Jpanel
 Japplet
 JDialog

110
JFrame
 Is an independent window that can be moved around on the
screen independently of any other GUI windows.
 Frame is a window that is not contained inside another window.
 Frame is the basis to contain other user interface components in
Java GUI applications.
 The JFrame class can be used to create windows.
 For Swing GUI programs, use JFrame class to create widows.

111
Creating JFrame…
import javax.swing.JFrame;
public class Simple extends JFrame {
public Simple() {
setSize(300, 200);
setTitle("First JFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
Simple simple = new Simple();
simple.setVisible(true);
}
}

112
JFrame
JFrame Class
Class

113
JPanel
 A container can be placed inside another container.
 Panels can be used as sub-containers to group GUI components
to achieve the desired layout.
 Panel is a blank rectangular component that can contain other
components.
 Each panel uses a layout manager to determine the position and
size of its child components.
 It is recommended that you place the user interface components
in panels and place the panels in a frame.
 You can also place panels in a panel.

114
JPanel
 To add a component to JFrame, you actually add it to the content
pane of JFrame.
 To add a component to a panel, you add it directly to the panel
using the add method.
• You can use new JPanel() to create a panel with a default
FlowLayout manager or new JPanel(LayoutManager) to create a
panel with the specified layout manager.
• Use the add(Component) method to add a component to the
panel.
• For example, JPanel p = new JPanel();
p.add(new JButton("OK"));
115
Creating a JPanel Interface - Example

frame
A textfield
p2
A button 12
buttons p1

116
Layout Managers
 Each container contains a layout manager, which is an object
responsible for laying out the GUI components in the container

 Java’s layout managers provide a level of abstraction to


automatically map your user interface on all window systems.

 The UI components are placed in containers. Each container has


a layout manager to arrange the UI components within the
container.

 Layout managers are set in containers using the


setLayout(LayoutManager) method in a container.
117
Types of Layout Managers
 There are three basic layout managers in Java.

1. FlowLayout

2. GridLayout

3. BorderLayout

118
The FlowLayout Manager
 FlowLayout is the simplest layout manager.
 The components are arranged in the container from left to right in the
order in which they were added.
 When one row is filled, a new row is started.
 You can specify the way the components are aligned by using one of
three constants:
 FlowLayout.RIGHT,
 FlowLayout.CENTER, or
 FlowLayout.LEFT.

119
FlowLayout - Example
Write a program that adds three labels and text fields into the
content pane of a frame with a FlowLayout manager.

120
FlowLayout - Example
 import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.FlowLayout;
public class ShowFlowLayout extends JFrame{
public ShowFlowLayout() {
setLayout(new FlowLayout(FlowLayout.LEFT, 10,20) );
add(new JLabel("First Name")); add(new JTextField(8));
add(new JLabel("MI")); add(new JTextField(1));
add(new JLabel("Last Name")); add(new JTextField(8));
}
public static void main(String[] args) {
ShowFlowLayout frame = new ShowFlowLayout();
frame.setTitle("ShowFlowLayout");
frame.setSize(200, 200);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
121 }
FlowLayout Class Diagram

The get and set methods for these data fields are provided in
java.awt.FlowLayout the class, but omitted in the UML diagram for brevity.

-alignment: int The alignment of this layout manager (default: CENTER).


-hgap: int The horizontal gap of this layout manager (default: 5 pixels).
-vgap: int The vertical gap of this layout manager (default: 5 pixels).

+FlowLayout() Creates a default FlowLayout manager.


+FlowLayout(alignment: int) Creates a FlowLayout manager with a specified alignment.
+FlowLayout(alignment: int, hgap: Creates a FlowLayout manager with a specified alignment,
int, vgap: int) horizontal gap, and vertical gap.

122
The GridLayout Manager
• The GridLayout manager arranges components in a grid
(matrix) formation.
• The components are placed in the grid from left to right, starting
with the first row, then the second, and so on, in the order in
which they are added.

Example: Rewrite the program in the preceding example using a


GridLayout manager instead of a FlowLayout manager to display
the labels and text fields.

123
GridLayout - Example
 import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JFrame;
import java.awt.GridLayout;
public class ShowGridLayout extends JFrame {
public ShowGridLayout() {
setLayout(new GridLayout(3, 2, 5, 5));
add(new JLabel("First Name")); add(new JTextField(8));
add(new JLabel("MI")); add(new JTextField(1));
add(new JLabel("Last Name")); add(new JTextField(8));
}
public static void main(String[] args) {
ShowGridLayout frame = new ShowGridLayout();
frame.setTitle("ShowGridLayout");
frame.setSize(200, 125);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
124
}
GridLayout Class Diagram

The get and set methods for these data fields are provided in
java.awt.GridLayout the class, but omitted in the UML diagram for brevity.

-rows: int The number of rows in this layout manager (default: 1).
-columns: int The number of columns in this layout manager (default: 1).
-hgap: int The horizontal gap of this layout manager (default: 0).
-vgap: int The vertical gap of this layout manager (default: 0).

+GridLayout() Creates a default GridLayout manager.


+GridLayout(rows: int, columns: int) Creates a GridLayout with a specified number of rows and columns.
+GridLayout(rows: int, columns: int, Creates a GridLayout manager with a specified number of rows and
hgap: int, vgap: int) columns, horizontal gap, and vertical gap.

125
The BorderLayout Manager

• The BorderLayout manager divides the container into five


areas: East, South, West, North, and Center.
• Components are added to a BorderLayout by using the add
method.
• add(Component, index), where index is a constant
BorderLayout.EAST, BorderLayout.SOUTH,
BorderLayout.WEST, BorderLayout.NORTH, or
BorderLayout.CENTER.

126
BorderLayout - Example

Writer program adds five buttons labeled East, South, West,


North, and Center to the frame with a BorderLayout manager

127
BorderLayout - Example
 import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.BorderLayout;
public class ShowBorderLayout extends JFrame {
public ShowBorderLayout() {
setLayout(new BorderLayout(5, 10));
add(new JButton("East"), BorderLayout.EAST);
add(new JButton("South"), BorderLayout.SOUTH);
add(new JButton("West"), BorderLayout.WEST);
add(new JButton("North"), BorderLayout.NORTH);
add(new JButton("Center"), BorderLayout.CENTER);
}
public static void main(String[] args) {
ShowBorderLayout frame = new ShowBorderLayout();
frame.setTitle("ShowBorderLayout");
frame.setSize(300, 200);
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
128 }
}
BorderLayout Class Diagram

The get and set methods for these data fields are provided in
java.awt.BorderLayout the class, but omitted in the UML diagram for brevity.

-hgap: int The horizontal gap of this layout manager (default: 0).
-vgap: int The vertical gap of this layout manager (default: 0).

+BorderLayout() Creates a default BorderLayout manager.


+BorderLayout(hgap: int, vgap: int) Creates a BorderLayout manager with a specified number of
horizontal gap, and vertical gap.

129
The Color Class
• Each GUI component has background and foreground colors.
• Colors are objects created from the Color class.
• You can set colors for GUI components by using the
java.awt.Color class.
• Colors are made of red, green, and blue components, each
represented by an int value that describes its intensity,
ranging from 0 (darkest shade) to 255 (lightest shade).
• This is known as the RGB model.
Color c = new Color(r, g, b); r, g, and b
specify a color by its red, green, and blue components.
Example:
130
Color c = new Color(228, 100, 255);
Standard Colors
• Thirteen standard colors (black, blue, cyan, darkGray, gray,
green, lightGray, magenta, orange, pink, red, white, yellow)
are defined as constants in java.awt.Color.
• You can use the following methods to set the component’s
background and foreground colors:
setBackground(Color c)
setForeground(Color c)

Example: JButton jbt = new JButton("OK");


jbt.setBackground(Color.yellow);
jbt.setForeground(Color.red);

131
The Font Class
 Each GUI component has the font property.
 Fonts are objects created from the Font class.
 You can create a font using the java.awt.Font class and set fonts for the
components using the setFont method in the Component class.
Font Names Font Style
Standard font names that are Font.PLAIN (0), Font.BOLD
supported in all platforms are: (1), Font.ITALIC (2), and
SansSerif, Serif, Monospaced, Font.BOLD + Font.ITALIC (3)
Dialog, or DialogInput.

Font myFont = new Font(name, style, size);


Example:
Font myFont = new Font("SansSerif ", Font.BOLD, 16);
Font myFont = new Font("Serif", Font.BOLD+Font.ITALIC, 12);

132 JButton jbtOK = new JButton("OK");


jbtOK.setFont(myFont);
Finding All Available Font Names
• To find the fonts available on your system, you need to obtain an
instance of java.awt.GraphicsEnvironment using its static
method getLocalGraphicsEnvironment().
• GraphicsEnvironment is an abstract class that describes the
graphics environment on a particular system.
• You can use its getAllFonts() method to obtain all the available
fonts on the system and its getAvailableFontFamilyNames()
method to obtain the names of all the available fonts.
• Example:

GraphicsEnvironment e =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = e.getAvailableFontFamilyNames();
for (int i = 0; i < fontnames.length; i++)
133 System.out.println(fontnames[i]);
Common Features of Swing Components
The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
java.awt.Component
-font: java.awt.Font The font of this component.
-background: java.awt.Color The background color of this component.
-foreground: java.awt.Color The foreground color of this component.
-preferredSize: Dimension The preferred size of this component.
-visible: boolean Indicates whether this component is visible.
+getWidth(): int Returns the width of this component.
+getHeight(): int Returns the height of this component.
+getX(): int getX() and getY() return the coordinate of the component’s
+getY(): int upper-left corner within its parent component.

java.awt.Container
+add(comp: Component): Component Adds a component to the container.
+add(comp: Component, index: int): Component Adds a component to the container with the specified index.
+remove(comp: Component): void Removes the component from the container.
+getLayout(): LayoutManager Returns the layout manager for this container.
+setLayout(l: LayoutManager): void Sets the layout manager for this container.
+paintComponents(g: Graphics): void Paints each of the components in this container.

The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
javax.swing.JComponent
-toolTipText: String The tool tip text for this component. Tool tip text is displayed when
the mouse points on the component without clicking.
134 -border: javax.swing.border.Border The border for this component.
ImageIcon Class
• Image icons are objects created using the ImageIcon class.
Java uses the javax.swing.ImageIcon class to represent an icon.
• An icon is a fixed-size picture; typically it is small and used to
decorate components.
• Images are normally stored in image files.
• You can use new ImageIcon(filename) to construct an image
icon.
• For example, the following statement creates an icon from an
image file us.gif in the image directory under the current class
path:
ImageIcon icon = new ImageIcon("image/us.gif");
p.add(new JLable(icon));
135
2. Ordinary Components
 Here is Some of the basic JComponents in which the user directly inputs data

 JLabel  JSlider
 JButton  JTabbedPane
 JCheckBox  Jmenu
 JRadioButton  Jspinner
 JScrollBar  JColorChooser
 JTextField  JEditorPane
 JPasswordField  JTextPane
 JTextArea  JFileChooser
 JComboBox  JProgressBar
 JTable  JDialog
 JTree
136
JLabel
 A label is a display area for a short text, an image, or both.
 With the JLabel class, you can display un-selectable text and
images.
 JFrame frame = new JFrame();
 JLabel label = new JLable(“Name”)
 frame.add(label);

137
JButton
 A button is a component that triggers an action when clicked.
 There are a few steps in using a button: declaring it, creating
it, adding it to a container (the content pane or a JPanel),
and adding a listener that has code to execute when the user
clicks on the button.

JButton btn = new JButton(text);


JButton btn = new JButton(text, image);
JButton btn = new JButton(image);
138
JButton

JButton mybtn = new JButton("Do Something");

mybtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
doMyAction(); // code to execute when button is pressed
}
}

. . .
JPanel content = new JPanel();
content.add(mybtn); // add the button to a JPanel (eg,content).

139
JCheckBox
 JCheckBox is a widget that has two states. On and Off.
 It is a box with a label.
 If the checkbox is checked, it is represented by a tick in a box.
 JCheckBox box = new JCheckBox()

140
JCheckBox…
Constructors
cb = new JCheckBox(text); Creates check box, initially unchecked.

cb = new JCheckBox(text, state); Creates check box, checked or not depending


on state.

Methods
state = cb.isSelected(); Returns true if the check box is checked.

cb.setSelected(state); Checks (true) or unchecks check box.

cb.addActionListener(action-listener); Adds an action listener to the radio button.


The action listener will be called if button is
selected.

cb.addItemListener(item-listener); Add an item listener to a radio button. The


item listener will be called if the button is
selected or deselected.

141
JRadioButton
 Radio buttons are groups of buttons in which only one
button at a time can be selected.

142
JRadioButton
JRadioButton bird = new JRadioButton("Bird");
JRadioButton cat = new JRadioButton("Cat");
JRadioButton dog = new JRadioButton("Dog");
ButtonGroup bg = new ButtonGroup();
bg.add(bird);
bg.add(cat);
bg.add(dog);

143
JTextField
 A text field can be used to enter or display a string.

JTextField firstName = new JTextField(20);


JTextField surName = new JTextField(20);
JTextField address = new JTextField(60);
JPanel p=new JPanel();
p.add(firstName);
p.add(surName);
p.add(address);

144
JPasswordField
Password field

JPasswordField userName = new JPasswordField(20);


JFrame f=new JFrame(“Example 01”); //you may use another container
f.add(userName);//adds the password field to a container

145
JTextArea
 A JTextArea enables the user to enter multiple lines of text
Text Area

Effect of Scroll Pane

JTextArea textArea = new JTextArea(5, 20);


JScrollPane scrollPane = new JScrollPane(textArea);
textArea.setEditable(true);
JPanel p=new JPanel();
p.add(scrollPane);

146
JTextArea

147
JComboBox
 A combo box, also known as a choice list or drop-down list, contains a list
of items from which the user can choose

148
JComboBox
String[] pet = {"Bird", "Cat", "Dog", "Rabbit", "Pig"};
//Create the combo box, select item at index 4.

//Indices start at 0, so 4 specifies the pig.


JComboBox petList = new JComboBox(pet);
petList.setSelectedIndex(4);

149
JList
 A list is a component that basically performs the same function as a combo box, but it
enables the user to choose a single value or multiple values.

String[] str = {"Math", "Computer", "Physics", "Chemistry"};


JList list=new JList(str);
JPanel p=new JPanel();
p.add(list);

150
JList
 Home work?

List area

Text box

151
3. Menu Components

152
Menu Components
import java.awt.event.*;
import javax.swing.*;
public class MenuComponent extends JFrame{
public MenuComponent(){
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
JMenuItem mi1 = new JMenuItem("Sub Menu 1");
menu.add(mi1);
JMenuItem mi2 = new JMenuItem("Sub Menu 2");
menu.add(mi2);
JMenuItem mi3 = new JMenuItem("Sub Menu 3");
menu.add(mi3);
menuBar.add(menu);
setJMenuBar(menuBar);
}
public static void main(String[] args){
MenuComponent frame = new MenuComponent();
frame.setTitle("Menu Demo");
frame.setSize(400,300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
153 }
THANK YOU
?

You might also like