Lecture Slide - Week 8 (4)
Lecture Slide - Week 8 (4)
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?
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
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
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 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.
yield(), or Running
time out run() returns
Thread created start()
New Ready run() join() Finished
sleep()
interrupt()
Target wait()
finished
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.
• 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
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
} }
} }
▪ Synchronization
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
Multithreading 57
Program and Process
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
Multithreading 59
Thread Model
▪ Control in a normal program usually follows a single thread of
execution.
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
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).
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;
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.
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;
▪ 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
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);
Multithreading 76
Topic
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.
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.
▪ 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.
▪ 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 …
}
…
}
Multithreading 87
Synchronization of Java Threads
▪ To program the synchronization behavior we use the Object class’
methods wait(), notify() and notifyAll().
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.
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.
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");
Button
Combo
// Create a text field with text "Type Name Here"
JTextField jtfName = new JTextField("Type Name Here"); Box
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
104
GUI Helper Classes
FontMetrics
Graphics
JMenuItem JMenu
JToggleButton JCheckBox
JRadioButton
JComponent JEditorPane
JTextArea
TextArea
Graphics List
Component Choice
CheckBox
LayoutManager CheckBoxGroup
Canvas
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
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.
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.
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).
125
The BorderLayout Manager
126
BorderLayout - Example
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).
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)
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.
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.
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.
Methods
state = cb.isSelected(); Returns true if the check box is checked.
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.
144
JPasswordField
Password field
145
JTextArea
A JTextArea enables the user to enter multiple lines of text
Text Area
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.
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.
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
?