Java Unit - IV
Java Unit - IV
SYLLABUS
Multithreaded Programming: Java Thread life cycle model – Thread creation - Thread Exceptions -
Thread Priority – Synchronization - Runnable Interface - Interthread Communication - Deadlock -
Suspending, Resuming and stopping threads.
Java AWT: AWT Hierarchy, Event Delegation Model, Adapter classes, Listeners, Layout management,
AWT Components, Simple UI for Email registration.
Multithreaded Programming
1
22PC1IT201 UNIT - IV OOP Through Java
Threads
• A thread is also known as a lightweight process.
• The idea is to achieve parallelism by dividing a process into multiple threads.
• For example, in a browser, multiple tabs can be different threads. MS Word uses multiple threads: one
thread to format the text, another thread to process inputs, etc
• Each thread belongs to exactly one process and no thread can exist outside a process.
• Each thread represents a separate flow of control. Threads have been successfully used in implementing
network servers and web server.
.
Benefits:
1. Responsiveness
2. Resource sharing
3. Economy
4. Scalability
2
22PC1IT201 UNIT - IV OOP Through Java
Threads exist in several states. A thread can be running. It can be ready to run as soon as it gets CPU time. A
running thread can be suspended, which temporarily halts its activity. A suspended thread can then be
resumed, allowing it to pick up where it left off. A thread can be blocked when waiting for a resource. At
any time, a thread can be terminated, which halts its execution immediately. Once terminated, a thread
cannot be resumed.
3
22PC1IT201 UNIT - IV OOP Through Java
Thread creation
There are two ways to create a thread:
1. By extending Thread class
2. By implements Runnable interface.
1. Thread class
• A class can extending by Thread class then thread will be created.
• Thread class provide constructors and methods to create and perform operations on a thread.
• Syntax: public class Thread extends Object implements Runnable
• Constructors are as follow
Thread( )
Thread(Runnable target)
Thread(String name)
Thread(Runnable target, String name)
Thread(ThreadGroup group, String name)
Thread(ThreadGroup group, Runnable target)
Thread(ThreadGroup group, Runnable target, String name)
Thread(ThreadGroup group, Runnable target, String name, long stackSize)
• Methods are as follow
Method Description
public void run( ) Used to perform action for a thread.
Starts the execution of the thread. JVM calls the run( ) method on
public void start( )
the thread.
public static void sleep(long Causes the currently executing thread to sleep (temporarily cease
miliseconds) execution) for the specified number of milliseconds.
public void join( ) waits for a thread to die.
public void join(long miliseconds) waits for a thread to die for the specified miliseconds.
public int getPriority( ) returns the priority of the thread.
public int setPriority(int priority) changes the priority of the thread.
public String getName( ) returns the name of the thread.
public void setName(String name) changes the name of the thread.
public Thread currentThread( ) returns the reference of currently executing thread.
public int getId( ) returns the id of the thread.
public Thread.State getState( ) returns the state of the thread.
public boolean isAlive( ) tests if the thread is alive.
causes the currently executing thread object to temporarily pause
public void yield( )
and allow other threads to execute.
public void suspend( ) used to suspend the thread(depricated).
public void resume( ) used to resume the suspended thread(depricated).
public void stop( ) used to stop the thread(depricated).
public boolean isDaemon( ) tests if the thread is a daemon thread.
public void setDaemon(boolean b) marks the thread as daemon or user thread.
public void interrupt( ) interrupts the thread.
public boolean isInterrupted( ) tests if the thread has been interrupted.
public static boolean interrupted( ) tests if the current thread has been interrupted
4
22PC1IT201 UNIT - IV OOP Through Java
5
22PC1IT201 UNIT - IV OOP Through Java
2. Runnable interface
• By implementing the Runnable interface, we can create a thread.
• To implement Runnable, a class need only implement a single method called run( ).
• syntax:
public void run( )
• run( ) is used to perform action for a thread.
• After the new thread is created, you need to call start( ) method to execute run( ) method.
• This is a functional interface and can therefore be used as the assignment target for a lambda
expression or method reference.
Method Description
When an object implementing interface Runnable is used to create a thread, starting the
void run( )
thread causes the object's run method to be called in that separately executing thread.
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread("java");
Thread obj1 = new Thread(t1);
obj1.start();
MyThread t2 = new MyThread("C Program");
Thread obj2 = new Thread(t2);
obj2.start();
}
}
Thread Exceptions
Here are some of the most common thread exceptions in Java:
• IllegalThreadStateException:
This exception is thrown when you try to invoke a method on a thread that is not in the correct
state. For example, you cannot call the start( ) method on a thread that has already been started.
• InterruptedException:
This exception is thrown when a thread is interrupted. This can happen when you call
the interrupt() method on the thread, or when another thread sends an interrupt signal to the thread.
• UnsupportedClassVersionError:
This exception is thrown when you try to run a class that was compiled with a newer version of the
Java Virtual Machine (JVM) on a JVM that is running an older version of the JVM.
• ClassNotFoundException:
This exception is thrown when the JVM cannot find a class file on the classpath.
• NullPointerException:
This exception is thrown when you try to access a null object.
• NoClassDefFoundError:
This exception occurs in two flavors. The first scenario is where we provide class full name with .class
extension. The second scenario comes when Class is not found.
7
22PC1IT201 UNIT - IV OOP Through Java
Thread Priority
• Each thread has a priority. Priorities are represented by a number between 1 and 10.
• Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run.
• In theory, higher-priority threads get more CPU time than lower-priority threads.
• In practice, the amount of CPU time that a thread gets often depends on several factors besides its
priority.
• A higher-priority thread can also preempt a lower-priority one.
setPriority( ) :
• setPriority( ) method, updates or assign the priority of the thread to newPriority.
• The method throws IllegalArgumentException if the value newPriority goes out of the range.
• Syntax: public final void setPriority(int level)
• There are three constants to specify the thread priority
1. public static int MIN_PRIORITY: The value of MIN_PRIORITY is 1
2. public static int NORM_PRIORITY: The value of MAX_PRIORITY is 5(default)
3. public static int MAX_PRIORITY: The value of MAX_PRIORITY is 10
getPriority( ):
• getPriority( ) method returns the priority of the given thread.
• Syntax: public final int getPriority( )
8
22PC1IT201 UNIT - IV OOP Through Java
Synchronization
• Synchronization is a mechanism that allows multiple threads to access a shared resource without
interfering with each other.
• It is a way to coordinate the activities of multiple threads so that they can work together safely and
efficiently.
• The synchronization is mainly used to prevent thread interference and prevent consistency problem.
• There are two main ways to implement synchronization in Java: using synchronized methods and
synchronized blocks.
Synchronized methods:
A synchronized method is a method that can only be executed by one thread at a time. When a thread
enters a synchronized method, it acquires a lock on the object that the method is synchronized on. Any
other threads that try to enter the synchronized method will be blocked until the first thread releases the
lock.
Example: Demonstrate the Synchronization using synchronized method.
class Table {
public synchronized void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n+" * "+i+" = "+(n*i));
try{
Thread.sleep(100);
}catch(InterruptedException e){System.out.println(e);}
}
}
}
class MyThread extends Thread{
int n;
Table obj;
MyThread(Table obj, int n){
this.obj = obj;
this.n = n;
}
public void run(){
obj.printTable(n);
}
}
public class Synchronization {
public static void main(String[] args) {
Table dis = new Table();
MyThread obj = new MyThread(dis,1);
obj.start();
MyThread obj2 = new MyThread(dis,5);
obj2.start();
}
}
9
22PC1IT201 UNIT - IV OOP Through Java
Synchronized blocks:
A synchronized block is a block of code that can only be executed by one thread at a time. To create a
synchronized block, you use the synchronized keyword followed by the object that the block is
synchronized on. Any other threads that try to enter the synchronized block will be blocked until the
first thread releases the lock.
class Table {
public void printTable(int n){
for(int i=1;i<=10;i++){
System.out.println(n+" * "+i+" = "+(n*i));
try{
Thread.sleep(100);
}catch(InterruptedException e){System.out.println(e);}
}
}
}
class MyThread extends Thread{
int n;
Table obj;
MyThread(Table obj, int n){
this.obj = obj;
this.n = n;
}
public void run(){
synchronized(obj) {
obj.printTable(n);
}
}
}
public class Synchronization {
public static void main(String[] args) {
Table dis = new Table();
MyThread obj = new MyThread(dis,1);
obj.start();
MyThread obj2 = new MyThread(dis,5);
obj2.start();
}
}
10
22PC1IT201 UNIT - IV OOP Through Java
Example: Implementing synchronization of Bank application with debit and credit operation.
class Bank {
public static double bal = 1000;
public void credit(double amt){
System.out.println("Before credit bal :"+bal);
double temp = bal; //read
temp = temp + amt; //update
try { Thread.sleep(1000);}
catch (InterruptedException e) {throw new RuntimeException(e);}
bal = temp; //write
System.out.println("After credit bal :"+bal);
}
public void debit(double amt){
System.out.println("Before Debit bal :"+bal);
double temp = bal; //read
temp = temp - amt; //update
try { Thread.sleep(1000);}
catch (InterruptedException e) {throw new RuntimeException(e);}
bal = temp; //write
System.out.println("After Debit bal :"+bal);
}
}
class User1 extends Thread{
Bank b;
User1(Bank b){ this.b = b; }
public void run(){
synchronized (b) { b.credit(10000); }
}
}
class User2 extends Thread{
Bank b;
User2(Bank b){ this.b = b; }
public void run(){
synchronized (b) { b.debit(500); }
}
}
public class SynchronizationDemo {
public static void main(String[] args) {
Bank b = new Bank();
User1 c = new User1(b);
User2 d = new User2(b);
c.start();
d.start();
}
}
11
22PC1IT201 UNIT - IV OOP Through Java
Interthread Communication
• Inter-thread communication (Co-operation) is all about allowing synchronized threads to communicate
with each other.
• It is a mechanism in which a thread is paused running in its critical section and another thread is allowed
to enter (or lock) in the same critical section to be executed.
• polling is the situation to check some condition repeatedly, to take appropriate action, once the condition
is true. That means, in inter-thread communication, a thread waits until a condition becomes true such
that other threads can execute its task.
• To avoid polling, Java includes an elegant inter-process communication mechanism via the wait( ),
notify( ), and notifyAll( ) methods. These methods are implemented as final methods in Object, so all
classes have them. All three methods can be called only from within a synchronized context. Although
conceptually advanced from a computer science perspective, the rules for using these methods are
actually quite simple:
• wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the
same monitor and calls notify( ) or notifyAll( ).
• notify( ) wakes up a thread that called wait( ) on the same object.
• notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the threads will be
granted access. These methods are declared within Object class.
12
22PC1IT201 UNIT - IV OOP Through Java
Output:
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5
13
22PC1IT201 UNIT - IV OOP Through Java
Example: Implementation of inter thread communication of Bank with credit and transfer.
import java.util.Scanner;
class Bank {
public static double bal = 1000;
public synchronized void credit(double amt){
System.out.println("Before credit bal :"+bal);
double temp = bal;//read
temp = temp + amt;//update
bal = temp;//write
System.out.println("After credit bal :"+bal);
notify();
}
public synchronized void transfer(double amt){
System.out.println("Before Transfer bal :"+bal);
if(bal<amt) {
System.out.println("do you want to add amount?");
char option = new Scanner(System.in).next().charAt(0);
if(option == 'y' || option == 'Y'){
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Resume Transfer");
bal = bal-amt;
System.out.println("After Transfer bal :"+bal);
}else{
System.out.println("In sufficient funds");
}
}else{
bal = bal-amt;
System.out.println("After Transfer bal :"+bal);
}
}
}
class User1 extends Thread{
Bank b;
User1(Bank b){ this.b = b; }
public void run(){ b.credit(10000); }
}
class User3 extends Thread{
Bank b;
User3(Bank b){ this.b = b; }
public void run(){ b.transfer(5000); }
}
public class SynchronizationDemo {
public static void main(String[] args) {
Bank b = new Bank();
User1 c = new User1(b);
User3 t = new User3(b);
t.start();
c.start();
}
}
14
22PC1IT201 UNIT - IV OOP Through Java
Deadlock
• A deadlock is a situation where a set of threads are blocked because each thread is holding a resource
and waiting for another resource acquired by some other thread.
• Deadlock is a difficult error to debug for two reasons:
✓ In general, it occurs only rarely, when the two threads time-slice in just the right way.
✓ It may involve more than two threads and two synchronized objects.
}
}
Output:
ThreadX started
ThreadY started
class DeadlockDemo{
public static void main(String[] args) {
String resourceA = "Hello";
String resourceB = "Hi";
Thread t1 = new Thread(()->{
synchronized (resourceA) {
System.out.println("ThreadX started");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (resourceB){
System.out.println("Request the lock for resourceB");
}
System.out.println("ThreadX ended");
}
});
Thread t2 = new Thread(()->{
synchronized (resourceB) {
System.out.println("ThreadY started");
try {
Thread.sleep(1000);
Output:
} catch (InterruptedException e) {
ThreadX started
throw new RuntimeException(e);
} ThreadY started
synchronized (resourceA){
16
22PC1IT201 UNIT - IV OOP Through Java
resume( ):
The resume( ) method of thread class is only used with suspend( ) method. This method is used to resume a
thread which was suspended using suspend( ) method.
Syntax: public final void resume( )
stop( ):
The stop() method of thread class terminates the thread execution. Once a thread is stopped, it cannot be
restarted by start() method.
Syntax
public final void stop()
public final void stop(Throwable obj)
• Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.
• Java AWT components are platform-dependent i.e. components are displayed according to the view of
operating system.
• AWT is heavy weight i.e. its components are using the resources of underlying operating system (OS).
• AWT is in applets, it is also used to create stand-alone windows that run in a GUI environment, such as
Windows.
18
22PC1IT201 UNIT - IV OOP Through Java
Applet:
• Applet is a java program that is embedded in the webpage to generate the dynamic content.
• It runs inside the browser and works at client side.
• Applets are embedded in an HTML page using the APPLET or OBJECT tag and hosted on a web server.
• Applets are used to make the website more dynamic and entertaining.
• Applets have limited access to resources so that it can run complex computations without introducing the
risk of viruses or breaching data integrity.
• Applet programs are primarily used in Internet programming.
• These programs are either developed in local systems or in remote systems and are executed by either a
java compatible “Web browser” or “appletviewer”.
• There two types of applets-
1. Local Applet: An applet developed locally and stored in a local system is known as a Local Applet.
When a Web page is trying to find a local applet, it does not need to use the Internet and therefore the
local system does not require the Internet connection. It simply searches the directories in the local
system and locates and loads the specified applet.
2. Remote Applet: An applet developed by someone else and stored on a remote computer is known as
Remote Applet. If our system is connected to the Internet, we download the remote applet onto our
system via the Internet and run it. In order to locate the remote applet, we must know the applet’s
address on the Web. This address is known as Uniform Resource Locator (URL).
• Every java applet inherits a set of default behaviors from the Applet class defined in java.applet
package.
• When an applet is loaded, it undergoes a series of changes in its states.
• The important states of the Applet Life Cycle are:
1. Born or Initialization State
2. Running State
3. Idle State
4. Dead or Destroyed State
19
22PC1IT201 UNIT - IV OOP Through Java
20
22PC1IT201 UNIT - IV OOP Through Java
//applet code
<applet code=”AppletDemo.class” width=”400” height=”300”>
</Applet>
Output:
21
22PC1IT201 UNIT - IV OOP Through Java
Frame:
• The class Frame is a top-level window with border and title.
• Other components like buttons, text fields, and scrollbars can be added to a Frame.
• Constructs a new Frame that is initially invisible.
• It uses BorderLayout as default layout manager.
• Syntax: public class Frame extends Window implements MenuContainer
constructors
Constructor Description
Frame( ) Constructs a new instance of Frame that is initially invisible.
Constructs a new, initially invisible Frame with the specified
Frame(GraphicsConfiguration gc)
GraphicsConfiguration.
Constructs a new, initially invisible Frame object with the specified
Frame(String title)
title.
Frame(String title, Constructs a new, initially invisible Frame object with the specified
GraphicsConfiguration gc) title and a GraphicsConfiguration.
Method
Methos Description
addNotify( ) Creates the Frame's peer.
dispose( ): Disposes of the Frame.
getCursorType( ) Return the cursor type
getIconImage( ) Returns the icon image for this Frame.
getMenuBar( ) Gets the menu bar for this Frame.
getTitle( ) Gets the title of the Frame.
isResizable( ) Returns true if the user can resize the Frame.
paramString( ) Returns the parameter String of this Frame.
remove(MenuComponent) Removes the specified menu bar from this Frame.
setCursor(int) Set the cursor image to a predefined cursor.
setIconImage(Image) Sets the image to display when this Frame is iconized.
setMenuBar(MenuBar) Sets the menubar for this Frame to the specified menubar.
setResizable(boolean) Sets the resizable flag.
setTitle(String) Sets the title for this Frame to the specified title.
Output:
Example: Demonstrate the window using Frame
import java.awt.*;
public class FrameDemo extends Frame {
Label l;
FrameDemo(){
setVisible(true);
setLayout(null);
setTitle("Home Window");
setSize(400,200);
l = new Label("Welcome to My Window");
l.setBounds(100,100,200,30);
add(l);
}
public static void main(String[] args) {
new FrameDemo();
} }
22
22PC1IT201 UNIT - IV OOP Through Java
Event Handling
Event
• An event is an object that represents a change in the state of an object.
• Events are notifications that something has happened.
• For example, as a user clicking a button or a file being opened.
• The event object contains information about the event, such as the type of event, the source of the event,
and the time the event occurred.
• Events are handled by listeners.
Event Sources
• A source is an object that generates an event.
• This occurs when the internal state of that object changes in some way.
• Sources may generate more than one type of event.
• A source must register listeners in order for the listeners to receive notifications about a specific type of
event.
• Each type of event has its own registration method.
• Syntx: public void addTypeListener (TypeListener el )
• Here, Type is the name of the event, and el is a reference to the event listener.
• For example, the method that registers a keyboard event listener is called addKeyListener( ).The method
that registers a mouse motion listener is called addMouseMotionListener( ).
• When an event occurs, all registered listeners are notified and receive a copy of the event object. This is
known as multicasting the event.
23
22PC1IT201 UNIT - IV OOP Through Java
Event Listeners
• A listener is an object that is notified when an event occurs.
• It has two major requirements.
✓ First, it must have been registered with one or more sources to receive notifications about specific
types of events.
✓ Second, it must implement methods to receive and process these notifications.
• The methods that receive and process events are defined in a set of interfaces, those found in
java.awt.event.
• For example, the MouseMotionListener interface defines two methods to receive notifications when the
mouse is dragged or moved.
24
22PC1IT201 UNIT - IV OOP Through Java
ActionListener Interface
• This interface defines the actionPerformed( ) method that is invoked when an action event occurs.
• Syntax: void actionPerformed(ActionEvent ae)
AdjustmentListener Interface
• This interface defines the adjustmentValueChanged( ) method that is invoked when an adjustment event
occurs.
• Syntax: void adjustmentValueChanged(AdjustmentEvent ae)
ComponentListener Interface
• This interface defines four methods that are invoked when a component is resized, moved, shown, or
hidden.
• Syntax: void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
ContainerListener Interface
• This interface contains two methods. When a component is added to a container, componentAdded( ) is
invoked. When a component is removed from a container, componentRemoved( ) is invoked.
• Syntax: void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
FocusListener Interface
• This interface defines two methods. When a component obtains keyboard focus, focusGained( ) is
invoked. When a component loses keyboard focus, focusLost( ) is called.
• Syntax: void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
ItemListener Interface
• This interface defines the itemStateChanged( ) method that is invoked when the state of an item changes.
• Syntax: void itemStateChanged(ItemEvent ie)
KeyListener Interface
• This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked when a
key is pressed and released, respectively. The keyTyped( ) method is invoked when a character has been
entered.
• For example, if a user presses and releases the a key, three events are generated in sequence: key
pressed, typed, and released.
• If a user presses and releases the home key, two key events are generated in sequence: key pressed and
released.
• Syntax: void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
MouseListener Interface
• This interface defines five methods. If the mouse is pressed and released at the same point,
mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method is called.
• When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are
invoked when the mouse is pressed and released, respectively.
• Syntax: void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
25
22PC1IT201 UNIT - IV OOP Through Java
WindowFocusListener Interface
• This interface defines two methods: windowGainedFocus( ) and windowLostFocus( ). These are called
when a window gains or loses input focus.
• Syntax: void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
WindowListener Interface
• This interface defines seven methods. The windowActivated( ) and windowDeactivated( ) methods are
invoked when a window is activated or deactivated, respectively.
• If a window is iconified, the windowIconified( ) method is called. When a window is deiconified, the
windowDeiconified( ) method is called.
• When a window is opened or closed, the windowOpened( ) or windowClosed( ) methods are called,
respectively.
• The windowClosing( ) method is called when a window is being closed.
• Syntax: void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
Event Delegation Model
• The modern approach to handling events is based on the delegation event model.
• Mechanism: A source generates an event and sends it to one or more listeners. The listener simply waits
until it receives an event. Once an event is received, the listener processes the event and then returns.
• The advantage of this design is that the application logic that processes events is cleanly separated from
the user interface logic that generates those events.
• A user interface element is able to “delegate” the processing of an event to a separate piece of code.
• In the delegation event model, listeners must register with a source in order to receive an event
notification.
• This provides an important benefit: notifications are sent only to listeners that want to receive them.
26
22PC1IT201 UNIT - IV OOP Through Java
27
22PC1IT201 UNIT - IV OOP Through Java
28
22PC1IT201 UNIT - IV OOP Through Java
29
22PC1IT201 UNIT - IV OOP Through Java
@Override
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
@Override
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
@Override
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
@Override
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
@Override
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
}
30
22PC1IT201 UNIT - IV OOP Through Java
Adapter classes
• An adapter class provides an empty implementation of all methods in an event listener interface.
• Adapter classes are useful when you want to receive and process only some of the events that are handled
by a particular event listener interface.
• For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and mouseMoved( ),
which are the methods defined by the MouseMotionListener interface.
• If you were interested in only mouse drag events, then you could simply extend MouseMotionAdapter
and override mouseDragged( ).
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener and MouseMotionListener and MouseWheelListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener, WindowFocusListener, and WindowStateListener
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter {
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
public void mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
}
}
31
22PC1IT201 UNIT - IV OOP Through Java
AWT Components
• An AWT component can be considered as an object that can be made visible on a graphical interface
screen and through which interaction can be performed.
• Sytax:
public abstract class Component extends Object
implements ImageObserver, MenuContainer, Serializable
• AWT Control Fundamentals
• The AWT supports the following types of controls, these controls are subclasses of Component.
1. Labels
2. Push buttons
3. Check boxes
4. Choice lists
5. Lists
6. Scroll bars
7. Text Field
8. Text Area
1. Labels: A label is an object of type Label, and it contains a string, which it displays. Labels are
passive controls that do not support any interaction with the user.
Constructors: Description
Label( ) creates a blank label
Label(String str) creates a label that contains the string specified by str
creates a label that contains the string specified by str using the
Label(String str, int how) alignment specified by how.
how: Label.LEFT, Label.RIGHT, or Label.CENTER.
Methods Description
void setText(String str) set or change the text in a label
String getText( ) get the current label
void setAlignment(int how) how must be one of the alignment constants shown earlier
int getAlignment( ) get the alignment.
2. Push buttons: A push button is a component that contains a label and that generates an event when
it is pressed. Push buttons are objects of type Button.
Constructors: Description
Button( ) creates a blank Button
Button(String str) creates a Button that contains the string specified by str as label
Methods Description
void setLabel(String str) set or change the label
String getLabel( ) get the current label
Handling Buttons
• Each time a button is pressed, an action event is generated.
• An ActionEvent object is supplied as the argument to this method. It contains both a reference to
the button that generated the event and a reference to the action command string associated with
the button.
• Each listener implements the ActionListener interface. That interface defines the
actionPerformed( ) method, which is called when an event occurs.
32
22PC1IT201 UNIT - IV OOP Through Java
3. Check boxes
• A check box is a control that is used to turn an option on or off.
• It consists of a small box that can either contain a check mark or not.
• There is a label associated with each check box that describes what option the box represents.
• You change the state of a check box by clicking on it. Check boxes can be used individually or
as part of a group.
• Check boxes are objects of the Checkbox class.
Constructors: Description
Checkbox( ) creates a blank check box and state is unchecked.
creates a check box that specified by str as label state is
Checkbox(String str)
unchecked.
allows you to set the initial state of the check
Checkbox(String str, boolean on) box. If true, the check box is initially checked; otherwise, it
is cleared.
create a check box whose label is specified by str and
Checkbox(String str, boolean on, whose group is specified by
CheckboxGroup cbGroup) cbGroup. If this check box is not part of a group, then
cbGroup must be null.
create a check box whose label is specified by str and
Checkbox(String str, CheckboxGroup whose group is specified by
cbGroup, boolean on) cbGroup. If this check box is not part of a group, then
cbGroup must be null.
Methods Description
void setState(boolean on) set or change the state
boolean getState( ) get the current state
void setLabel(String str) set or change the label
String getLabel( ) get the current label
Handling CheckBox:
• Each time a check box is selected or deselected, an item event is generated.
• This is sent to any listeners that previously registered an interest in receiving item event
notifications from that component.
• Each listener implements the ItemListener interface. That interface defines the
itemStateChanged( ) method.
• An ItemEvent object is supplied as the argument to this method.
33
22PC1IT201 UNIT - IV OOP Through Java
CheckboxGroup
It used to create radio button, create a set of mutually exclusive check boxes in which one and only
one in the group can be checked at any one time.
Constructors: Description
CheckboxGroup( ) creates an empty group
Methods Description
void setSelectedCheckbox(Checkbox which) which is the check box that you want to be selected
Checkbox getSelectedCheckbox( ) get the selected check box.
4. Choice lists
• The Choice class is used to create a pop-up list of items from which the user may choose.
• When the user clicks on it, the whole list of choices pops up, and a new selection can be made.
• Each item in the list is a string that appears as a left-justified label in the order it is added to the
Choice object.
• When inactive, a Choice component takes up only enough space to show the currently selected
item.
Constructors: Description
Choice( ) creates an empty list
Methods Description
void add(String name) name of the item being added.
String getSelectedItem( ) returns a string containing the name of the item
int getSelectedIndex( ) returns the index of the item. The first item is at index 0.
int getItemCount( ) obtain the number of items in the list
void select(int index) Set the item to be selected based on index
void select(String name) Set the item to be selected based on string
String getItem(int index) obtain the name associated with the item at that index
5. Lists
• The List class provides a compact, multiple-choice, scrolling selection list.
• A List object can be constructed to show any number of choices in the visible window.
• It can also be created to allow multiple selections
Constructors: Description
List( ) allows only one item to be selected at any one time
numRows specifies the number of entries in the list that will always
List(int numRows)
be visible.
List(int numRows, boolean If multipleSelect is true, then the user may select two or more items
multipleSelect) at a time. If it is false, then only one item may be selected.
Methods Description
void add(String name) name of the item being added.
34
22PC1IT201 UNIT - IV OOP Through Java
adds the item at the index specified by index. You can specify
void add(String name, int index)
–1 to add the item to the end of the list
String getSelectedItem( ) returns a string containing the name of the item
int getSelectedIndex( ) returns the index of the item. The first item is at index 0.
returns an array containing the names of the currently selected
String[ ] getSelectedItems( )
items
int[ ] getSelectedIndexes( )
int getItemCount( ) obtain the number of items in the list
void select(int index) Set the item to be selected based on index
String getItem(int index) obtain the name associated with the item at that index
Handling Lists
• Each time a List item is double-clicked, an ActionEvent object is generated.
• Its getActionCommand( ) method can be used to retrieve the name of the newly selected item.
• Each time an item is selected or deselected with a single click, an ItemEvent object is generated.
• Its getStateChange( ) method can be used to determine whether a selection or deselection
triggered this event. getItemSelectable( ) returns a reference to the object that triggered this event.
6. Scroll bars
• Scroll bars are used to select continuous values between a specified minimum and maximum.
• Scroll bars may be oriented horizontally or vertically. A scroll bar is actually a composite of
several individual parts.
• Each end has an arrow that you can click to move the current value of the scroll bar one unit in the
direction of the arrow.
• The current value of the scroll bar relative to its minimum and maximum values is indicated by
the slider box (or thumb) for the scroll bar.
• The slider box can be dragged by the user to a new position.
Constructors: Description
Scrollbar( ) creates a vertical scroll bar.
specify the orientation of the scroll bar.
Scrollbar(int style)
style are Scrollbar.VERTICAL, Scrollbar.HORIZONTAL
The initial value of the scroll bar is passed in initialValue. The
Scrollbar(int style, int initialValue, number of units represented by the height of the thumb is
int thumbSize, int min, int max) passed in thumbSize. The minimum and maximum
values for the scroll bar are specified by min and max.
Methods Description
void setValues(int initialValue, int set its parameters.
thumbSize, int min, int max)
int getValue( ) obtain the current value of the scroll bar.
void setValue(int newValue) set the current value.
int getMinimum( ) retrieve the minimum value
int getMaximum( ) retrieve the maximum value
35
22PC1IT201 UNIT - IV OOP Through Java
7. Text Field
• The TextField class implements a single-line text-entry area, usually called an edit control.
• Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and paste
keys, and mouse selections.
Constructors: Description
TextField( ) creates a default text field
TextField(int numChars) creates a text field that is numChars width
TextField(String str) initializes the text field with the string contained in str
TextField(String str, int numChars) initializes a text field and sets its width
Methods Description
void setText(String str) Set the text specified in str
String getText( ) Get the text with in text field.
void select(int startIndex, int endIndex) select a portion of text
String getSelectedText( ) returns the selected text
void setEditable(boolean canEdit) if canEdit is true, the text may be changed. If it is false,
the text cannot be altered.
boolean isEditable( ) isEditable( ) returns true if the text may be changed and
false if not.
void setEchoChar(char ch) disable the echoing of the characters as they are typed
boolean echoCharIsSet( ) check a text field to see if it is in this mode
char getEchoChar( ) retrieve the echo character
Handling a TextField
Generally will not respond to individual key events that occur within a text field. However, you may
want to respond when the user presses enter. When this occurs, an action event is generated.
8. Text Area
Sometimes a single line of text input is not enough for a given task. To handle these situations, the AWT
includes a simple multiline editor called TextArea.
Constructors: Description
TextArea( ) creates a default text area
creates a text area that numLines specifies the
TextArea(int numLines, int numChars)
height, and numChars characters width
TextArea(String str) Initial text can be specified by str
TextArea(String str, int numLines, int numChars) Specify the initial string, height and width.
Specify the initial string, height, width and
scroll bar. sBars must be one of these values:
TextArea(String str, int numLines, int numChars, SCROLLBARS_BOTH
int sBars) SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
Methods Description
void setText(String str) Set the text specified in str
36
22PC1IT201 UNIT - IV OOP Through Java
37
22PC1IT201 UNIT - IV OOP Through Java
Layout management
• A layout manager automatically arranges your controls within a window by using some type of
algorithm.
• While it is possible to lay out Java controls by hand, too, you generally won’t want to, for two main
reasons.
✓ First, it is very tedious to manually lay out a large number of components.
✓ Second, sometimes the width and height information is not yet available when you need to arrange
some control, because the native toolkit components haven’t been realized.
• This is a chicken-and-egg situation.
• Each Container object has a layout manager associated with it.
• A layout manager is an instance of any class that implements the LayoutManager interface.
• The layout manager is set by the setLayout( ) method. If no call to setLayout( ) is made, then the default
layout manager is used.
• Syntax: void setLayout(LayoutManager layoutObj)
FlowLayout
• FlowLayout is the default layout manager.
• FlowLayout implements a simple layout style, which is similar to how words flow in a text editor.
• The direction of the layout is governed by the container’s component orientation property, which, by
default, is left to right, top to bottom.
• A small space is left between each component, above and below, as well as left and right.
Constructors: Description
Centers components and leaves five pixels of space between each
FlowLayout( )
component.
centers components and leaves five pixels of space between each
component.
FlowLayout.LEFT
FlowLayout(int how) FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout.LEADING
FlowLayout.TRAILING
specify the horizontal and vertical space left between components
FlowLayout(int how, int horz, int vert)
in horz and vert.
38
22PC1IT201 UNIT - IV OOP Through Java
39
22PC1IT201 UNIT - IV OOP Through Java
BorderLayout:
• The BorderLayout class implements a common layout style for top-level windows.
• It has four narrow, fixed-width components at the edges and one large area in the center.
• The four sides are referred to as north, south, east, and west. The middle area is called the center.
Constructors Description
BorderLayout( ) creates a default border layout
BorderLayout(int horz, int vert) specify the horizontal and vertical space left between
components in horz and vert, respectively
• BorderLayout defines the following constants that specify the regions:
BorderLayout.CENTER ,BorderLayout.SOUTH, BorderLayout.EAST, BorderLayout.WEST,
BorderLayout.NORTH
• When adding components, you will use these constants with the following form of add( ), which is
defined by Container:
• Syntax: void add(Component compRef, Object region)
Example: Demonstrate the BorderLayout.
import java.awt.*;
import java.applet.*;
import java.util.*;
/* <applet code="BorderLayoutDemo" width=400 height=200> </applet> */
public class BorderLayoutDemo extends Applet {
public void init() {
setLayout(new BorderLayout());
add(new Button("This is across the top."),
BorderLayout.NORTH);
add(new Label("The footer message might go here."),
BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);
String msg ="The reasonable man adapts himself to the world;\n"+
"the unreasonable one persists in " +
"trying to adapt the world to himself.\n" +
"Therefore all progress depends " +
"on the unreasonable man.\n\n" +
" - George Bernard Shaw\n\n";
add(new TextArea(msg), BorderLayout.CENTER);
}
}
40
22PC1IT201 UNIT - IV OOP Through Java
GridLayout:
• GridLayout lays out components in a two-dimensional grid.
• When you instantiate a GridLayout, you define the number of rows and columns.
Constructors: Description
GridLayout( ) creates a single-column grid layout
creates a grid layout with the specified number of rows
GridLayout(int numRows, int numColumns)
and columns
GridLayout(int numRows, int numColumns, specify the horizontal and vertical space left between
int horz, int vert) components in horz and vert.
Example: sample program that creates a 4×4 grid and fills it in with 15 buttons, each labeled with its index.
import java.awt.*;
import java.applet.*;
/*
<applet code="GridLayoutDemo" width=300 height=200>
</applet>
*/
public class GridLayoutDemo extends Applet {
static final int n = 4;
public void init() {
setLayout(new GridLayout(n, n));
setFont(new Font("SansSerif", Font.BOLD, 24));
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int k = i * n + j;
if(k > 0)
add(new Button("" + k));
}
}
}
}
output:
41
22PC1IT201 UNIT - IV OOP Through Java
CardLayout
• CardLayout class is unique among the other layout managers in that it stores several different layouts.
• Each layout can be thought of as being on a separate index card in a deck that can be shuffled so that any
card is on top at a given time.
• This can be useful for user interfaces with optional components that can be dynamically enabled and
disabled upon user input.
• You can prepare the other layouts and have them hidden, ready to be activated when needed.
• Constructors:
✓ CardLayout( ): creates a default card layout.
✓ CardLayout(int horz, int vert): specify the horizontal and vertical space left between components in
horz and vert.
• Methods:
✓ void first(Container deck)
✓ void last(Container deck)
✓ void next(Container deck)
✓ void previous(Container deck)
✓ void show(Container deck, String cardName)
Here, deck is a reference to the container (usually a panel) that holds the cards, and cardName is the name
of a card.
Example: Demonstrate the CardLayout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CardLayoutDemo" width=300 height=100> </applet>
*/
public class CardLayoutDemo extends Applet implements ActionListener {
Checkbox windowsXP, windows7, windows8, android, solaris, mac;
Panel osCards;
CardLayout cardLO;
Button Win, Other;
public void init() {
Win = new Button("Windows");
Other = new Button("Other");
add(Win);
add(Other);
cardLO = new CardLayout();
osCards = new Panel();
osCards.setLayout(cardLO); // set panel layout to card layout
windowsXP = new Checkbox("Windows XP", null, true);
windows7 = new Checkbox("Windows 7", null, false);
windows8 = new Checkbox("Windows 8", null, false);
android = new Checkbox("Android");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
// add Windows check boxes to a panel
Panel winPan = new Panel();
winPan.add(windowsXP);
winPan.add(windows7);
winPan.add(windows8);
42
22PC1IT201 UNIT - IV OOP Through Java
43
22PC1IT201 UNIT - IV OOP Through Java
GriBagLayout
• The grid bag useful is that you can specify the relative placement of components by specifying their
positions within cells inside a grid.
• The key to the grid bag is that each component can be a different size, and each row in the grid can have a
different number of columns.
• The location and size of each component in a grid bag are determined by a set of constraints linked to it.
Constructor
GridBagLayout(): The parameterless constructor is used to create a grid bag layout manager.
Fields
44
22PC1IT201 UNIT - IV OOP Through Java
• When a component is smaller than its cell, you can use the anchor field to specify where within the cell
the component’s top-left corner will be located.
• There are three types of values that you can give to anchor.
• The first are absolute:
The third type of values that can be given to anchor allows you to position components relative to the
baseline of the row.
Methods
Method Description
void addLayoutComponent(Component comp, It adds specified component to the layout, using the
Object constraints) specified constraints object.
void addLayoutComponent(String name, It has no effect, since this layout manager does not use
Component comp) a per-component string.
protected void It adjusts the x, y, width, and height fields to the
adjustForGravity(GridBagConstraints constraints, correct values depending on the constraint geometry
Rectangle r) and pads.
protected void
AdjustForGravity(GridBagConstraints constraints, This method is for backwards compatibility only
Rectangle r)
protected void arrangeGrid(Container parent) Lays out the grid.
This method is obsolete and supplied for backwards
protected void ArrangeGrid(Container parent)
compatibility
GridBagConstraints getConstraints(Component It is for getting the constraints for the specified
comp) component.
float getLayoutAlignmentX(Container parent) It returns the alignment along the x axis.
float getLayoutAlignmentY(Container parent) It returns the alignment along the y axis.
45
22PC1IT201 UNIT - IV OOP Through Java
Output:
47
22PC1IT201 UNIT - IV OOP Through Java
Model Questions
2 marks
1. Define thread and list its advantages.
2. Distinguish between thread and process.
3. Distinguish between runnable and running states.
4. What is the purpose of the run( ) method?
5. What is the purpose of the stop( ) method?
6. Create a thread by writing the syntax.
7. Describe some thread exceptions.
8. Synchronization must be defined.
9. Inter-thread communication should be defined.
10. Define the term "deadlock."
11. What is the use of AWT.
12. List some AWT components in Java.
13. Applet should be defined.
14. Define the Frame.
15. Create the applet tag syntax.
16. Define event and provide a list of event classes.
17. What is the purpose of event listeners, and what are some examples of event listeners?
18. What is the event delegation model?
19. What exactly is the adapter class?
20. What is the purpose of the layout manager?
Essay Questions
1. Draw and describe the thread life cycle process.
2. List and explain various methods for creating threads in Java using an example program.
3. Explain what thread priority is.
4. Define synchronization and demonstrate how to implement it with an example program.
5. Explain inter-thread communication with an example program.
6. Define dead lock and demonstrate with an example program.
7. With an example program, draw and explain the applet life cycle process.
8. List and explain the different event listener interfaces.
9. Create a Java program that shows key events.
10. Create a java program that displays mouse events.
11. List and explain the different AWT controls.
12. List and explain the different AWT layout managers.
48