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

Java Unit - IV

The document outlines the syllabus for a unit on Object-Oriented Programming through Java, focusing on multithreaded programming and Java AWT. It covers key concepts such as the Java thread life cycle, thread creation methods, thread exceptions, thread priority, and synchronization techniques. Additionally, it provides examples of creating threads using both the Thread class and the Runnable interface, along with explanations of thread states and common exceptions encountered in multithreading.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Java Unit - IV

The document outlines the syllabus for a unit on Object-Oriented Programming through Java, focusing on multithreaded programming and Java AWT. It covers key concepts such as the Java thread life cycle, thread creation methods, thread exceptions, thread priority, and synchronization techniques. Additionally, it provides examples of creating threads using both the Thread class and the Runnable interface, along with explanations of thread states and common exceptions encountered in multithreading.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

22PC1IT201 UNIT - IV OOP Through Java

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

Process and Process Life Cycle


• Process is a unit of work to be implemented in the computer system.
• For Examples browser, Word document, game, program execution, playing video etc.
• A process in a program that is being executed.
• The state of a process is defined in part by the current activity of that process

Fig: Process State Diagram


• A process may be in one of the following states:
➢ New: The process is being created.
➢ Ready: The process is waiting to be assigned to a processor.
➢ Running: Instructions are being executed.
➢ Waiting: The process is waiting for some resources (such as an I/O completion).
➢ Terminated: The process has finished execution.
Note: It is important to realize that only one process can be running on any processor at any instant. Many
processes may be ready and waiting, however.

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

Java Thread life cycle model


A thread is a path of execution in a program that enters any one of the following five states during its life
cycle. The five states are as follows:
1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Dead

2
22PC1IT201 UNIT - IV OOP Through Java

1. New (Newborn State)


• When we create a thread object, thread is born and is known to be in Newborn state.
• When a thread is born, it enters into new state.
• Only start( ) method can be called on a new thread; otherwise, an IllegalThreadStateException will
be thrown.
2. Runnable state:
• When the start( ) method is called on a new thread, thread enters into a runnable state.
• In this state, thread is ready for execution and is waiting for availability of the processor (CPU time).
• That is, thread has joined queue (line) of threads that are waiting for execution.
• If all threads have equal priority, CPU allocates time slots for thread execution on the basis of first-
come, first-serve manner.
• The process of allocating time to threads is known as time slicing.
• A thread can come into runnable state from running, waiting, or new states.
3. Running state
• Running means Processor (CPU) has allocated time slot to thread for its execution.
• When thread scheduler selects a thread from the runnable state for execution, it goes into running state.
• In running state, processor gives its time to the thread for execution and executes its run method.
• A thread can come into running state only from runnable state.
• A running thread may give up its control in any one of the following situations and can enter into the
blocked state.
a) When sleep( ) method is invoked on a thread to sleep for specified time period, the thread is out of
queue during this time period. The thread again re-enters into the runnable state as soon as this time
period is elapsed.
b) When suspend( ) method is invoked for some time in order to satisfy some conditions. A suspended
thread can be revived by using resume( ) method.
c) When wait( ) method is invoked on a thread to wait for some time. The thread in wait state can be
run again using notify( ) or notifyAll( ) method.
4. Blocked state
• A thread is considered to be in the blocked state when it is suspended, sleeping, or waiting for some
time in order to satisfy some condition.
5. Terminated (Dead state)
• A thread dies or moves into dead state automatically when its run( ) method completes the execution
of statements.
• A thread can also be dead when the stop( ) method is called.

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

Example 1: creating a thread using Thread class


class MyThread extends Thread{
String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
for(int i=1;i<=10;i++){
System.out.println(name+" : "+i);
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
for(int i=1;i<=5;i++) {
MyThread t1 = new MyThread("java");
t1.start();
MyThread t2 = new MyThread("C Program");
t2.start();
}
}
}

Example 2: creating a thread using Thread class with sleep( ) method.


class MyThread extends Thread{
String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
for(int i=1;i<=10;i++){
System.out.println(name+" : "+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread("java");
t1.start();
MyThread t2 = new MyThread("C Program");
t2.start();
}
}

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.

Example: creating a thread using Runnable interface.


class MyThread implements Runnable{
String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
for(int i=1;i<=10;i++){
System.out.println(name+" : "+i);
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
for(int i=1;i<=5;i++) {
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();
}
}
}

Example: creating a thread using Runnable interface with sleep( ) method.


class MyThread implements Runnable{
String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
for(int i=1;i<=10;i++){
System.out.println(name+" : "+i);
try {
Thread.sleep(1000);
6
22PC1IT201 UNIT - IV OOP Through Java

} 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( )

Example: Demonstrate the setPriority( ) and getPriority( ) methods.


import java.lang.*;
class ThreadPriorityExample extends Thread
{
public void run() {
System.out.println("Inside the run() method");
}
}
class ThreadMain {
public static void main(String argvs[])
{
ThreadPriorityExample th1 = new ThreadPriorityExample( );
ThreadPriorityExample th2 = new ThreadPriorityExample( );
ThreadPriorityExample th3 = new ThreadPriorityExample( );
System.out.println("Priority of the thread th1 is : " + th1.getPriority( ));
System.out.println("Priority of the thread th2 is : " + th2.getPriority( ));
System.out.println("Priority of the thread th3 is : " + th2.getPriority( ));
th1.setPriority(8);
th2.setPriority(7);
th3.setPriority(2);
System.out.println("Priority of the thread th1 is : " + th1.getPriority( ));
System.out.println("Priority of the thread th2 is : " + th2.getPriority( ));
System.out.println("Priority of the thread th3 is : " + th3.getPriority( ));
}
}
Output:
Priority of the thread th1 is : 5
Priority of the thread th2 is : 5
Priority of the thread th3 is : 5
Priority of the thread th1 is : 8
Priority of the thread th2 is : 7
Priority of the thread th3 is : 2

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.

Example: Demonstrate the Synchronization using synchronized block.

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.

Example: Implementation of a producer and consumer.


class Q {
int n;
boolean valueSet = false;
synchronized int get() {
while(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {while(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}

12
22PC1IT201 UNIT - IV OOP Through Java

class Producer implements Runnable {


Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
class PQ {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

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.

Example: Implements Deadlock on ThtreadX and ThreadY


class ThreadX extends Thread{
String resourceA,resourceB;
ThreadX(String resourceA,String resourceB){
this.resourceA = resourceA;
this.resourceB = resourceB;
}
public void run(){
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");
}
}
}
class ThreadY extends Thread{
String resourceA,resourceB;
ThreadY(String resourceA,String resourceB){
this.resourceA = resourceA;
this.resourceB = resourceB;
}

public void run(){


synchronized (resourceB) {
System.out.println("ThreadY started");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
15
22PC1IT201 UNIT - IV OOP Through Java

throw new RuntimeException(e);


}
synchronized (resourceA){
System.out.println("Request the lock for resourceA");
}
System.out.println("ThreadY ended");
}
}
}
class DeadlockDemo{
public static void main(String[] args) {
String resourceA = "Hello";
String resourceB = "Hi";
ThreadX t1 = new ThreadX(resourceA,resourceB);
ThreadY t2 = new ThreadY(resourceA,resourceB);
t1.start();
t2.start();

}
}

Output:
ThreadX started
ThreadY started

Example: Implements Deadlock on ThtreadX and ThreadY using lambda expression.

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

System.out.println("Request the lock for resourceA");


}
System.out.println("ThreadY ended");
}
});
t1.start();
t2.start();
}
}

Suspending, Resuming and stopping threads


suspend( ):
The suspend( ) method of thread class puts the thread from running to waiting state. This method is used if
you want to stop the thread execution and start it again when a certain event occurs.
Syntax: public final void suspend( )

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)

Example: Demonstrate the suspend( ). Resume( ) and stop( ) methods.


class MyThread extends Thread {
public void run(){
for(int i=1;i<=5;i++) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
public class Example {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.start();
t2.start();
t2.suspend();
t3.start();
t2.resume();
t3.stop();
}
}
17
22PC1IT201 UNIT - IV OOP Through Java

Java AWT (Abstract Window Toolkit)


AWT Hierarchy

• 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.

The AWT hierarchy is as follows:


• Component: This is the base class for all AWT components. It defines the basic properties and
methods that are common to all AWT components.
• Container: This is a subclass of Component that can contain other components. Containers are used
to organize and layout components in a GUI.
• Window: This is a subclass of Container that provides a top-level window for a GUI application.
• Frame: This is a subclass of Window that provides a basic window with a title bar, borders, and a
close button.
• Dialog: This is a subclass of Window that provides a modal dialog box.
• Panel: This is a subclass of Container that is used to group and layout components in a GUI.
• Button: This is a subclass of Component that provides a button that can be clicked by the user.
• Label: This is a subclass of Component that provides a label for displaying text.
• TextField: This is a subclass of Component that provides a text field for the user to enter text.
• Checkbox: This is a subclass of Component that provides a checkbox that can be selected or
deselected by the user.
• Choice: This is a subclass of Component that provides a drop-down list of choices for the user to
select from.
• List: This is a subclass of Component that provides a list of items for the user to select from.

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).

Applet Life Cycle:

• 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

1. Born or Initialization State


• Applet enters the initialization state when it is first loaded.
• This is achieved by calling the init( ) method of Applet class. The applet is born.
• The initialization occurs only once in the applet’s life cycle.
• Generally all the initialization variables are to be placed in the init( ) method.
• Syntax: public void init( )
{
....
. . . . (Action)
}
2. Running State
• An applet enters into running state when the system calls the start( ) method of Applet class.
• This occurs automatically after the applet is initialized.
• Starting can also occurs if the applet is already in “Stopped State”.
• The start( ) method may be called more than once.
• Syntax: public void start( )
{
....
. . . . (Action)
}
3. Idle or Stopped State
• An applet becomes idle when it is stopped from running.
• Stopping occurs automatically when we leave the page containing the currently running
applet.
• This can also done by calling the stop( ) method explicitly.
• Syntax: public void stop()
{
....
. . . . (Action)
}
4. Dead State
• An applet is said to be dead when it is removed from memory.
• This occurs automatically by invoking the destroy( ) method when we quit the browser.
• Destroying stage occurs only once in the applet life cycle.
• Syntax: public void destroy()
{
....
. . . . (Action)
}
5. Display State
• Display state is useful to display the information on the output screen.
• This happens immediately after the applet enters into the running state.
• The paint( ) is called to accomplish this task. Almost every applet will have a paint( )
method.
• Syntax: public void paint(Graphics g)
{
....
. . . . (Display Statements)
}

20
22PC1IT201 UNIT - IV OOP Through Java

Example: Demonstrate the applet life cycle process

Source code: AppletDemo.java


import java.awt.*;
import java.applet.Applet;
public class AppletDemo extends Applet
{
String msg=" ";
public void init( ) {
msg=msg+"init( ) called";
}
public void start( ) {
msg=msg+"start( ) called";
}
public void paint(Graphics g) {
msg=msg+"paint( ) called";
g.drawString(msg,50,100);
}
}

//applet code
<applet code=”AppletDemo.class” width=”400” height=”300”>
</Applet>

The steps involved in developing and testing an applet are:


1. Building an applet code (.java file)
2. Creating an executable applet (.class file)
3. Create HTML page with the <APPLET> tag
4. Testing the Applet code with appletviewer

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

Note: Some sources may allow only one listener to register.

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

void mousePressed(MouseEvent me)


void mouseReleased(MouseEvent me)
MouseMotionListener Interface
• This interface defines two methods. The mouseDragged( ) method is called multiple times as the mouse is
dragged. The mouseMoved( ) method is called multiple times as the mouse is moved.
• Syntax: void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
MouseWheelListener Interface
• This interface defines the mouseWheelMoved( ) method that is invoked when the mouse wheel is moved.
• Syntax: void mouseWheelMoved(MouseWheelEvent mwe)
TextListener Interface
• This interface defines the textValueChanged( ) method that is invoked when a change occurs in a text
area or text field.
• Syntax: void textValueChanged(TextEvent te)

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

Example: Demonstration of KeyEvent and KeyListener using Applet.


import java.applet.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/*<applet code="MyApplet.class" width="500" height="300"></applet>*/
public class MyApplet extends Applet implements KeyListener {
Label l1, l2, l3;
TextField t;
public void init() {
setLayout(null);
l1 = new Label("Enter Text");
l1.setBounds(80, 80, 100, 20);
add(l1);
t = new TextField();
t.setBounds(200, 85, 150, 20);
add(t);
l2 = new Label("Key Status");
l2.setBounds(80, 110, 100, 20);
add(l2);
l3 = new Label();
l3.setBounds(200, 110, 100, 20);
add(l3);
t.addKeyListener(this);
}
@Override
public void keyTyped(KeyEvent e) {
l2.setText("Key Typed");
}
@Override
public void keyPressed(KeyEvent e) {
l2.setText("Key Pressed");
}
@Override
public void keyReleased(KeyEvent e) {
l3.setText(t.getText());
}
}
Output:

27
22PC1IT201 UNIT - IV OOP Through Java

Example: Demonstration of KeyEvent and KeyListener using Frame.


import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class FrameDemo extends Frame implements KeyListener {
Label l,l2,l3;
TextField t;
FrameDemo() {
setVisible(true);
setLayout(null);
setTitle("Home Window");
setSize(500,250);
l = new Label("Enter Text");
l.setBounds(80,80,100,30);
add(l);
t = new TextField();
t.setBounds(200,85,200,20);
add(t);
l2 = new Label("Your text");
l2.setBounds(80,110,500,30);
add(l2);
l3 = new Label("Key Status");
l3.setBounds(80,140,100,30);
add(l3);
t.addKeyListener(this);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
public static void main(String[] args) {
new FrameDemo();
}
@Override
public void keyTyped(KeyEvent e) {
l3.setText("Key Typed");
}
@Override
public void keyPressed(KeyEvent e) {
l3.setText("Key Pressed");
}
@Override
public void keyReleased(KeyEvent e) {
l3.setText("Key Released");
l2.setText(t.getText());
}
}

28
22PC1IT201 UNIT - IV OOP Through Java

Example: Demonstration of MouseEvent and MouseListener using Applet.


import java.applet.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

/*<applet code="MyApplet.class" width="500" height="300">


</applet>*/

public class MyApplet extends Applet implements MouseListener {


Label l;
public void init() {
Frame title = (Frame) this.getParent().getParent();
title.setTitle("My Applet");
setLayout(null);
addMouseListener(this);
l = new Label();
l.setBounds(200, 100, 150, 30);
add(l);
}
@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");
}
}

29
22PC1IT201 UNIT - IV OOP Through Java

Example: Demonstration of MouseEvent and MouseListener using Frame.


import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class FrameDemo extends Frame implements MouseListener {
Label l;
FrameDemo(){
setVisible(true);
setLayout(null);
setTitle("Home Window");
setSize(400,250);
l = new Label();
l.setBounds(80,80,100,30);
add(l);
addMouseListener(this);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
public static void main(String[] args) {
new FrameDemo();
}

@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

• Multiple buttons can be compared


• By label: The Label is obtained by calling the getActionCommand( ) method on the
ActionEvent object passed to actionPerformed( ).
• By object: The object is obtained by calling the getSource( ) method on the ActionEvent object
passed to actionPerformed( ).

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

Handling Choice Lists


• Each time a choice is selected, 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.

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

Handling Scroll Bars


• To process scroll bar events, you need to implement the AdjustmentListener interface.
• Each time a user interacts with a scroll bar, an AdjustmentEvent object is generated.
• Its getAdjustmentType( ) method can be used to determine the type of the adjustment.

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

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 append(String str) appends the string specified by str to the end of the
current text.
void insert(String str, int index) string passed in str at the specified index
void replaceRange(String str, int tartIndex, replaces the characters from startIndex to endIndex–1
int endIndex)

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.

Example: Demonstrate the FlowLayout using CheckBox aligned in left.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="FlowLayoutDemo" width=240 height=200>
</applet>
*/
public class FlowLayoutDemo extends Applet implements ItemListener {
String msg = "";
Checkbox windows, android, solaris, mac;
public void init() {
// set left-aligned flow layout
setLayout(new FlowLayout(FlowLayout.LEFT));

38
22PC1IT201 UNIT - IV OOP Through Java

windows = new Checkbox("Windows", null, true);


android = new Checkbox("Android");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
add(windows);
add(android);
add(solaris);
add(mac);
// register to receive item events
windows.addItemListener(this);
android.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
// Repaint when status of a check box changes.
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows: " + windows.getState();
g.drawString(msg, 6, 100);
msg = " Android: " + android.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac: " + mac.getState();
g.drawString(msg, 6, 160);
}
}
Output:

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

// Add other OS check boxes to a panel


Panel otherPan = new Panel();
otherPan.add(android);
otherPan.add(solaris);
otherPan.add(mac);
// add panels to card deck panel
osCards.add(winPan, "Windows");
osCards.add(otherPan, "Other");
// add cards to main applet panel
add(osCards);
// register to receive action events
Win.addActionListener(this);
Other.addActionListener(this);
// register mouse events
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == Win) {
cardLO.show(osCards, "Windows");
}
else {
cardLO.show(osCards, "Other");
}
}
}
Output:

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 second type of values that can be given to anchor is relative

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

It determines column widths and row heights for the


int[][] getLayoutDimensions()
layout grid.
protected GridBagLayoutInfo This method is obsolete and supplied for backwards
getLayoutInfo(Container parent, int sizeflag) compatibility.
protected GridBagLayoutInfo This method is obsolete and supplied for backwards
GetLayoutInfo(Container parent, int sizeflag) compatibility.
It determines the origin of the layout area, in the
Point getLayoutOrigin()
graphics coordinate space of the target container.
It determines the weights of the layout grid's columns
double[][] getLayoutWeights()
and rows.
protected Dimension getMinSize(Container parent, It figures out the minimum size of the master based on
GridBagLayoutInfo info) the information from getLayoutInfo.
protected Dimension GetMinSize(Container parent, This method is obsolete and supplied for backwards
GridBagLayoutInfo info) compatibility only

Example: Demonstrate the GridBoxLayout


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="GridBagDemo" width=250 height=200> </applet>
*/
public class GridBagDemo extends Applet implements ItemListener {
String msg = "";
Checkbox windows, android, solaris, mac;
public void init() {
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbag);
// Define check boxes.
windows = new Checkbox("Windows ", null, true);
android = new Checkbox("Android");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
// Define the grid bag.
// Use default row weight of 0 for first row.
gbc.weightx = 1.0; // use a column weight of 1
gbc.ipadx = 200; // pad by 200 units
gbc.insets = new Insets(4, 4, 0, 0); // inset slightly from top
left
gbc.anchor = GridBagConstraints.NORTHEAST;
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(windows, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(android, gbc);
// Give second row a weight of 1.
gbc.weighty = 1.0;
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(solaris, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(mac, gbc);
46
22PC1IT201 UNIT - IV OOP Through Java

// Add the components.


add(windows);
add(android);
add(solaris);
add(mac);
// Register to receive item events.
windows.addItemListener(this);
android.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
// Repaint when status of a check box changes.
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows: " + windows.getState();
g.drawString(msg, 6, 100);
msg = " Android: " + android.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac: " + mac.getState();
g.drawString(msg, 6, 160);
}
}

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

You might also like