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

Multithreading: Object Oriented Programming 1

This document discusses multi-threading in Java. It begins by defining multi-threading as a program that contains two or more parts that can run concurrently, with each part called a thread. It then covers thread states like ready, running, waiting, blocked, and dead. The document also discusses the main thread that runs when a Java program begins and how to get a reference to it. Finally, it introduces the Thread class, which contains methods to create, start, suspend, resume and stop threads, with the run() method defining how a thread will execute.

Uploaded by

Kalyan Majji
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views

Multithreading: Object Oriented Programming 1

This document discusses multi-threading in Java. It begins by defining multi-threading as a program that contains two or more parts that can run concurrently, with each part called a thread. It then covers thread states like ready, running, waiting, blocked, and dead. The document also discusses the main thread that runs when a Java program begins and how to get a reference to it. Finally, it introduces the Thread class, which contains methods to create, start, suspend, resume and stop threads, with the run() method defining how a thread will execute.

Uploaded by

Kalyan Majji
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 102

Object Oriented Programming 1

UNIT
4

MULTITHREADING

Syllabus:
Multi Threading: java.lang.Thread, The main Thread, Creation of new threads,
Thread priority, Multithreading – Using isAlive() and join(), Synchronization,
suspending and resuming threads, Communication between Threads.
Input/Output: reading and writing data, java.io package

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 2
4.1 MultiThreading:
A Multithreaded program contains two or more parts that can run concurrently.
Each part of such program is called a thread, and each thread defines a specific
path of execution. Multithreading is a specialized form of Multitasking.

4.2 Multitasking: -
All modern operating systems support the concept of multitasking. Multitasking is
the feature that allows the computer to run two or more programs concurrently.
CPU scheduling deals with the problem of deciding for which of the process, the
ready queue is to be allocated. It follows CPU(Processor) scheduling algorithms.

The priority scheduling follows on Sun Solaris systems. But it doesn’t work on the
present operating systems like windows NT etc., The thread with a piece of system
code is called the thread scheduler. It determines which thread is running actually
in the CPU.
The Solaris java platform runs a thread of given priority to completion or until
a higher priority thread becomes ready at that point preemption occurs.
b) Round-Robin Scheduling:

Round Robin scheduling is available on Windows 95 and Windows NT is time sliced.


Java supports thread implementation depending on round robin scheduling.
Here, each thread is given a limited amount of time called time quantum. While
executing the process when that time quantum expires the thread is made to wait
state and all threads that are equal priority get their chances to use their quantum
in round robin fashion.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 3

Note:
1. Java provides built-in support for multithreaded programming
2. Java multithreading is a platform independent
3. Elimination of main loop is the main benefit of multithreaded
programming.
4.3 Thread States (Life-Cycle of a Thread)
The life cycle of a thread contains several states. At any time the threads is falls into
any one of the states.
At any time a thread is said to be in one or more states.

 The thread that was just created is in the born state


 The thread remains in this state until the threads start method is called.
This causes the thread to enter the ready state.
 The highest priority ready thread enters the running state when the system
assigns a processor to the thread i.e., the thread begins executing.
 When a running thread calls wait the thread enters into a waiting state for
the particular object on which wait was called. Every thread in the waiting
state for a given object becomes ready on a call to notify all by another thread
associated with that object.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 4
 When a sleep method is called in a running thread, that thread enters into
the suspended (sleep) state. A sleeping thread becomes ready after the
designated sleep time expires. A sleeping thread cannot use a processor even
if one is available.
 A thread enters the dead state when its run( ) method complete ( or)
terminates for any reason. A dead thread is eventually be disposed of by the
system.
 One common way for a running thread to enter the blocked state is when the
thread issues an input or output request. In this case a blocked thread
becomes ready when the input or output waits for completes. A blocked
thread can’t use a processor even if one is available.

A thread is a single sequential (separate) flow of control within program. It is called


an execution context or a light weight process. A thread itself is not a program. A
thread cannot run on its own. Rather, It runs within a program. A program can be
divided into a number if packets of code-each representing a thread having its own
separate flow of control. That is, a thread can’t exist by itself. It is always a part of
program.
Light weight process: A thread is considered a light weight process because it runs
with in the context of a program (within the program) and takes advantage of the
resources allocated to that program.
Heavy weight process: In the heavy weight process, the control changes in between
threads belonging to different process(i.e. two different programs). (IN light weight
process, the control changes in between threads belonging to same(one) process)
Execution Context: A thread will have its own execution stack and program
counter. The code running within the thread works only within that context.

A thread is a flow of execution of a task in a program, which has a beginning and


end. The programs you have seen so far run in a single thread – that is, at any
given time, a single statement is being executed. With java, you can launch multiple
threads from a program concurrently.
The multiple thread share the CPU time, and the operating system is
responsible for scheduling and allocation resources to the threads. This
arrangement is practical because most of time the CPU is idle. Multithreading can
make your program more responsive and interactive, as well as enhance
performance.
Java provides built-in support for multithreaded programming. A
multithreaded program contains two or more parts that can run concurrently. Ach
part of such a program is called a thread, and each thread defines a separate path
of execution. Multithreading is specialized form of multitasking.
There are two distinct types of multitasking : process-based ad thread based.
A process is, in essence, a program that is executing. Thus, process-based
multitasking is the feature that allows your computer to run two or more programs
concurrently. For example, process-based multitasking enables you to run the java
compiler at the same time that your are using a text editor. In process-based

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 5
multitasking, a program is the smallest unit of code that can be dispatched by the
scheduler.
In a thread-based multitasking environment, the thead is the smallest unit of
dispatchable code. This means that a single program can perform two or more tasks
simultaneously. For instance, a text editor can format text at the same time that it
is printing, as long as these two actions are being performed by two separate
thread. Process-based multitasking deals with the “big picture”, and thread-based
multitasking handles the details.
Multithreading enables you to write very efficient programs that make
maximum use of the CPU, because idle time can be kept to a minimum.
The main thread: When a java program starts up, one thread begins running
immediately. This is usually called the main thread of your program, because it is
the one that is executed when your programs begins. The main thread is important
for two-reasons.
1. It is the thread for which other “child” threads will be spawned.
2. Often it must be the last thread to finish execution because it performs
various shutdown actions.
Although the main thread is created automatically when your program is started, it
can be controlled through a Thread object. You must obtain a reference to it by
calling the method currentThread( ), which is a public static member of thread. This
method returns a reference to the thread in which it is called. The setName()
method to change the internal name of the thread. The sleep( ) method causes the
thread from which it is called to suspend execution for the specified period of
milliseconds.
Program 1:
class mul1
{
public static void main(String arg[])
{
Thread t=Thread.currentThread();
System.out.println("current thread:"+t);
t.setName("ramesh");
System.out.println("After name change:"+t);
try
{
for(int n=5;n>0;n--)
{
System.out.println(n);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(" main thread interrupted ");
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 6
}
Output: Current Thread: Thread[main,5,main]
After name change: Thread [ramesh,5,main]
5
4
3
2
1
The output produced the name of the thread, its priority, and the name of its group.
By default, the name of main thread is main. Its priority is 5, which is the default
value, and main is also the name of the group of threads to which this thread
belongs.

4.4 Thread Class:


The thread class contains the constructor Thread(), as well as many useful methods
to run, start, suspend, resume, interrupt, and stop threads. To create and run a
thread, first define class that extends the Thread class. Your thread class must
override the run( ) method, which tells the system how the thread will be executed
when it runs. You then need a client class that creates an object running on the
thread. This object is referred to as a runnable object.
You create a runnable object by using the Thread() constructor. The start()
method tells the system that the thread is ready to run.
Constructor:
public Thread( )
It is called from the client class to create a runnable object if the user defined
thread class is used, the client program creates a thread by using the user defined
thread class constructor.
Methods:
public void run()
This method is invoked by the java runtime system to executed the thread. You
must override this method and provide the code you want your thread to execute in
your thread class. This method is never directly invoked by the runnable object in
the program, although it is an instance method of a runnable object
public void start()
This method starts the thread, which causes the run() method to be invoked. This
method is called by the runnable object in the client class.
public void stop( )
This method stops the thread.
public void suspend()
This method suspends the thread. You can use the resume( ) method to resume a
suspended thread.
public void resume( )
This method resumes the thread.
public static void sleep(long millis) throws InterruptedException
This method pus the runnable object to sleep for a specified time in milliseconds.
Note that sleep( ) is a class method

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 7
public void interrupt( )
This method interrupts the running thread.
public static Boolean interrupted()
This method test to see whether the current thread has been interrupted.
public Boolean isAlive()
This method test to see whether the thread is currently running.
public void setPriority(int p)
This method sets priority p(ranging from 1 to 10) for this thread.

The Thread class is included in java.lang package, a package that is implicitly


imported into every program. The super class of Thread is Object class.
Public class Thread extends Object implements Runnable
public Thread( ) creates a thread with default name
public Thread(String name) creates a thread with name
public Thread(Threadgroup group,
String name) creates a thread in a thread group
with name

public final static int MIN_PRIORITY=1 to associate a thread with minimum


priority
public final static int NORM_PRIORITY=5 to associate a thread with normal
priority
public final static int MAX_PRIORITY=10 to associate a thread with maximum
priority

public static native Thread currentThread( )


returns the current thread being
executed on the microprocessor.
public static native void sleep(long millis)
throws InterruptedException keeps thread in blocked state
public final void join( ) throws
InterruptedException waits until the target thread terminates.
public static void native yield( ) yield a waiting thread
public final String getName( ) returns the name of the thread
public final void setName(String name) sets a name to a thread

public final ThreadGroup getThreadGroup()


returns the thread’s group to which
thread belongs
public final native boolean isAlive( ) returns true if a thred is alive else false if
dead
public final boolean isDaemon( ) checks whether a thread is daemon or
not
public boolean isInterrupted( ) returns true if a thread is interrupted
public void run( ) by default run method is called
public final void setDeamon(boolean on) makes a thread daemon if true

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 8
public final int getPriority() returns the priority of the thread
public synchronized native void start( ) starts a thread
public final void stop( ) stops a thread and when stopped
garbage collected.
public final void suspend( ) to suspend a thread
public final void resume( ) to resume a thread which is
suspended

4.5 Package support for Threads:


Java.lang.Thread:
In Java language, threads are objects that derive from java.lang.Thread class. We
can subclass the Thread class to get the functionally of thread. Thread is a
concrete class.
Java.lang.Runnable: Runnable is an interface which provides an abstract method
run( ) for a thread.
Java.lang.Object: This is the root class for every class and defines the three
methods for use of threads. The methods are wait( ), notify( ) and notify All( )

Java language has two keywords related to the threads. Volatile and synchronized.
Both of these keywords help ensure the integrity of data that is shared between two
concurrently running threads.
Run( ) method:
The run( ) method is available both in Thread class and Runnable interface. We can
subclass a Thread class and override the run( ) method. We write the specific code,
which we would like to do by the thread, in the run( ) method. Run( ) method is the
heart of any Thread. Run( ) method is called implicitly by the start ( ) method.
In java, we can create threads in two ways – one by sub classing the Thread class
and one by implementing Runnable interface.
sleep( ) method:
Sleep( ) is a method of Thread class with the following syntax
Public static void sleep(long milliseconds) throws InterruptedException
Sleep() method is static and throws a checked exception, InterruptedException.
Sleep() method, we should take care of InterruptedException by providing try catch
block. Sleep( ) method makes a running(active) thread not to run(inactive) for the
specified milliseconds of time. When the sleep time expires, the thread becomes
automatically active. The active thread executres the run( ) method.
When the thread comes out of the run( ) method, it dies.
start( ) method:
UsingThread ut=new UsingThread();
Ut.start( );
In the above first statement, a thread by name ut is created. The thread ut is in
born state and is inactive. The inactive thread cannot call run() method. The thread
is born state occupies the memory resources but cannot take microprocessor time.
In the second statement, we call the start( ) method on the thread. Start( ) method
implicitly calls run( ) method. The thread in run state is active and utilizes
microprocessor time.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 9
Syntax: public void start( )
The start( ) method does not throw any checked exception
Note:
For getting to call the start( ) method is not an error, but run( ) method is not called.
Start() method implicitly calls run( ) method.

4.6 Creation of Threads:


Threads can be created in two ways.
i. By extending thread class
ii. By extending Runnable interface
By implementing the Runnable interface:
Everything is almost same but for the small difference of writing implements
instead of extends. Another difference is that the run() method in Thread class is a
concrete method and it is left to the subclass to override it or not. The run( )
method in Runnable interface is an abstract method. The subclass that
implements the Runnable interface must override the run( ) method.
By extending the Thread class:
We can create threads by extending Thread class to our class. By this, every object
of class Using Thread becomes implicitly a thread (i.e. it can utilize all the methods
of Thread class).
Program 2:
class fri extends Thread
{
public void run()
{
for(int i=1;i<5;i++)
{
System.out.println("first thread: "+i);
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class second extends Thread
{
public void run()
{
for(int i=1;i<5;i++)
{
System.out.println("Second Thread: "+i);

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 10
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
public class tworuns
{
public static void main(String arg[])
{
fri ft=new fri();
second st=new second();
ft.start();
st.start();
try
{
ft.join();
st.join();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}

4.7 Creating Multiple Threads:


Program 3:
class tt implements Runnable
{
String s;
Thread t;
tt(String st)
{

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 11
s=st;
t=new Thread(this,s);
System.out.println("new Thread: "+t);
t.start();
}
public void run( )
{
try
{
for(int i=5;i>0;i--)
System.out.println(s+" : "+i);
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(s+" existing ");
}
}
}
class ss
{
public static void main(String arg[]) throws Exception
{
new tt("one");
new tt("two");
new tt("three");
Thread.sleep(10000);
System.out.println(" main thread exiting ");
}
}

About join( ) method:


Join( ) method makes the thread to wait until other threads finish their task.
Join( ) method involves two threads. The invocation of join causes the currently
executing thread to suspend execution until target thread finished its execution.
The calling thread waits until called thread completes its execution and dies. By
using join( ), data consistency can be maintained.
Public final void join() throws InterruptedException
Program 4:
class tt implements Runnable
{
String s;
Thread t;
tt(String st)
{
s=st;

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 12
t=new Thread(this,s);
System.out.println("new Thread: "+t);
t.start();
}
public void run( )
{
try
{
for(int i=5;i>0;i--)
System.out.println(s+" : "+i);
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(s+" existing ");
}
}
}
class demo
{
public static void main(String arg[]) throws Exception
{
tt ob1=new tt("one");
tt ob2=new tt("two");
tt ob3=new tt("three");
System.out.println(" thread one is alive : "+ob1.t.isAlive());
System.out.println(" thread two is alive : "+ob2.t.isAlive());
System.out.println(" thread three is alive: "+ob3.t.isAlive());
System.out.println(" waiting for threads to finish ");
ob1.t.join();
ob2.t.join();
ob3.t.join();
System.out.println("thread one is alive :"+ob1.t.isAlive());
System.out.println("thread two is alive :"+ob2.t.isAlive());
System.out.println("thread three is alive :"+ob3.t.isAlive());
System.out.println(" main thread existing ");
}
}

4.8 Thread Priority:


The order of execution of multiple threads on a single CPU, depends on the
scheduling. The Java runtime supports a scheduling algorithm called fixed priority
scheduling. Every Java thread has a priority in the range Thread.MIN_PRIORITY
and Thread.MAX_PRIORITY. By default, each thread is given a priority of
Thread.NORM_PRIORITY. Each new thread inherits the priority of the thread that
creates it.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 13
The job of the thread scheduler is to keep the highest-priority thread running
all the time and for the threads of same priority, time slices are allocated in round-
robin fashion.
Program 5:
public class pdemo extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
String str=Thread.currentThread().getName();
System.out.println(str+" : "+i);
}
}
public static void main(String arg[])
{
pdemo pd1=new pdemo();
pdemo pd2=new pdemo();
pd1.setName("First Thread");
pd2.setName("Second Thread");
pd1.setPriority(MIN_PRIORITY);
pd2.setPriority(MAX_PRIORITY);
pd1.start();
pd2.start();
System.out. println("Priority of pd1: "+pd1.getPriority());
System.out.println("Priority of pd2: "+pd2.getPriority());
}
}

4.9 Thread Group:


Every thread belongs to some group. That is, no thread exists without a thread
group(like no file exists without a directory). While creating a thread, if no group is
specified, by default it is put into the main thread group. A thread group can have
both threads and other thread groups as members.

Public clas ThreadGroup extends Object


public ThreadGroup(String name) a thread group is created by a name
public ThreadGroup(ThreadGroup parent,

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 14
String name) assigning to a group with a name
Public int activeCount() returns the no. of active threads at the
current time.
Public final getMaxPriority( ) returns the max.priority a thread can
be assigned with
public String getName( ) returns the name of the thread group

4.10 Supspending and Resuming a Thread:


Suspend( ) method is used to temporarily stop the execution(making inactive) of the
thread. All the resources of the thread are intact(not destroyed). Resume( ) is a
method which can start a suspended thread (and making it active again).
Program 6:
public class susres extends Thread
{
public void run( )
{
try
{
for(int i=0;i<7;i++)
{
Thread.sleep(500);
System.out.println(this.getName( )+" "+i);
}
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String arg[])
{
susres sr1=new susres();
sr1.setName("sr1");
susres sr2=new susres();
sr2.setName("sr2");
sr1.start();
sr2.start();
try
{
Thread.sleep(1000);
sr1.suspend();
System.out.println("Suspending thread sr1");
Thread.sleep(1000);
sr1.resume();
System.out.println("Resuming thread sr1 ");

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 15
Thread.sleep(1000);
sr2.suspend();
System.out.println("Supsending thread sr2");
Thread.sleep(1000);
sr2.resume();
System.out.println("resuming thread sr2 ");
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}

A typical Output ( the output varies and depends on microprocessor speed):

4.11 Synchronization:
When two or more threads need access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by
which this is achieved is called synchronization. As you will see, java provides
unique language level support for it. Key to synchronization is the concept of the
monitor (also called a semaphore) a monitor is an object that is used as mutually
exclusive lock or mutex. Only one thread can own a monitor at a object that is used
as mutually exclusive lock or mutex. Only one thread can own a monitor at a given
time. When a thread acquires a lock it is said to have entered the monitor. All other
threads attempting to enter the locked monitor will be suspended until the first
thread exists the monitor. These other threads are said to be waiting for the
monitor. A thread get own a monitor can reenter the same monitor if it so desires.
Program 7: // This program is not synchronized
class callme
{
void call(String msg)
{
System.out.println(“[ “+msg);
try

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 16
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.prinln( “ interrupted “);
}
System.out.println(“]”);
}
}
class caller implements runnable
{
String msg;
Callme target;
Thread t;
Public caller(callme targ,String s)
{
target=targ;
msg=s;
t=new Thread(this);
t.start();
}
public void run()
{
target.call(msg);
}
}
class synch
{
public static void main(String arg[])
{
callme target=new callme();
caller ob1=new caller(target,”hello”);
caller ob2=new caller(target,”synchronized”);
caller ob3=new caller(target,”world”);
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch((InterruptedException e)
{
System.out.println(“ interrupted “);
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 17
}
The synchronized statement: While creating synchronized methods within classes
that you create is an easy and effective means of achieving synchronization, it will
not work in all classes.
This the general form of the synchronized statement
Synchronized(object)
{
//statements to be synchronized
}
here object is a reference to the object being synchronized. A synchronized block
ensures that a call to a method that in a member of object occurs only after the
current thread has successfully entered object monitor.
Here is an alternative version of the proceeding example, using a
synchronized block within the run() method.

4.12 Daemon Thread:


A daemon thread is a thread that runs for the benefit of other threads. Daemon
threads are known as service threads. Daemon threads run in the background and
come into execution when the microprocessor is idle. The garbage collector is an
example for a daemon thread. We can set a thread to be a daemon one, by calling
the thread setDaemon(true). If the parameter false, thread is not a daemon thred,
the default one. A thread must be set to daemon, if wanted, before it starts(i.e.,
start( ) is called; else illegalThreadStateException is thrown.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 18

UNIT
5&6

APPLETS,
EVENT
HANDLING,
AWT & SWING

Syllabus:
Applets – Applet class, Applet structure, An Example Applet Program, Applet Life
Cycle, paint(), update() and repaint()
Event Handling – Introduction, Event Delegation Model, java.awt.event,
Description, Sources of Events, Event Listeners, Adapter classes, Inner classes
AWT : Why Awt? Java.awt package, Components and Containers, Button, Label,
Checkbox, Radio buttons, List boxes, Choice boxes, Text Field and Text Area,
container classes, Layouts, Menu, Scroll bar
Swing : Introduction, JFrame, JApplet, JPanel, Components in swings, Layout
Managers, JList and JScroll Pane, Split Pane, JTabbedPane, Dialog box, Pluggale
Look and feel

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 19
The Applet Class:
All applets are subclasses of Applet. All applets must import java.applet.
Applets must also import java.awt. Recall that AWT stands for the Abstract
Windows Toolkit. Since all applets run in a window, it is necessary to include
support for that window. Applets are not executed by the console-based java run-
time interpreter. They are executed by either a web browser or an applet viewer.
Execution of an applet does not begin at main(). Actually few applets even have
main( ) method. Execution of an applet is started and controlled with an entirely
different mechanism, which will be explained shortly. Output to your applet’s
window is not performed by System.out.println(). It is handled with various AWT
methods, such as drawString(), which outputs a string to a specified X,Y location.
Input is also handled differently than in application.
Once an applet has been compiled, it is included in an HTML file using the
APPLET tag. The applet will be executed by a java-enabled web browser when it
encounters the applet tag with the HTML file. To view and test an applet more
conveniently, simply include a comment at the head of your java source code file
that contains the applet tag. This way, your code is documented with the necessary
HTML statements needed by your applet, and you can test the compiled applet by
starting the applet viewer with your java source code file specified as the target.
/*<applet code=”myapplet” width=200 height=300></applet>*/
This comment contains an applet tag that will run a applet called myapplet in
window that is 200 pixels wide and 60 pixels high.
Applet provides all necessary support for applet execution, such as starting
and stopping. It also provides methods that load and display images, and methods
that load and play audio clips. Applet extends that AWT class Panel. Panel extends
Container, which extends Component. These classes provide support for java’s
window-based graphical interface. Applet provides all of the necessary support for
window-based activities.
Applet viewer interfaces to the applet and controls its execution. Four of
these methods –init(), start(), stop( ), and destroy( ) – are defined by Applet. Paint()
is defined by the AWT component class. Default implementations for all of these
methods are provided.
Skeleton:
Import java.awt.*;
Import java.applet.*;
/*<applet code=”myapplet” width=200 height=300>
</applet>*/
public class myapplet extends Applet
{
public void init()
{
//initialization
}
public void start()
{
//start or resume execution

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 20
}
public void stop()
{
//suspends execution
}
public void destory()
{
//shut down activity
}
public void paint(Graphics g)
{
//redisplay the contents
}
}
The init( ) method:
It is invoked when the applet is first loaded and again if it is reloaded.
A subclass of Applet should override this method if the subclass has an
initialization to perform. Common functions implemented using this method
include creating new threads, loading images, setting up user-interface
components, and getting parameters from the <Applet> tag in the HTML page.
The start( ) method:
The start( ) method is invoked after the init( ) method. It also is called whenever the
applet becomes active again after a period of inactivity. The start( ) method is
called, for example, when the user returns to the web page containing the applet
after surfing other pages.
A subclass of Applet should override this method if the subclass has any operation
that needs to be performed each time the web page containing the applet is visited.
An applet with animation, for example, might want to use the start( ) method to
resume animation.
The stop( ) method:
The stop( ) method is the opposite of the start( ) method. The start( )method is
called when the user moves back to the page containing the applet. The stop( )
method is invoked when the user moves off the page.
The destroy( ) method:
The destroy( ) method is invoked when the browser exits normally to inform the
applet that it is no longer needed and that it should release any resources it has
allocated. The stop( ) method always is called before the destroy( ) method.
A subclass of Applet should override this method if the subclass has any operation
that needs to be performed before it is destroyed.
The <applet> Html tag:
To run applets, you must create an HTML file with the applet tag to specify the
applet bytecode file, the applet viewing are dimension (width and height), and other
associated parameters. The syntax of the <applet> tag is:
<applet code=classfilename.class
width=applet_viewing_width_in_pixels
height=aplet_viewing_height_in_pixels

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 21
[archieve=archivefile]
[codebase=applet_url]
[vspace=vertical_margin]
[hspace=horizontal_margion]
[align=applet_alignment]
[alt=alternative_text] >
<param name=param_name1 value=param_value1>
<param name=param_name2 value=param_value2>
……
<param name=param_name n value=param-valuen>
</applet>
The code, width, and height are required attributes; all others are optional.
Archive: you can use this attribute to instruct the browser to load an archive file
that contains all the class files needed to run the applet.
Codebase: If this attribute is not used, the web browser loads the applet from the
directory in which the HTML page is located. If your applet is located in a different
directory from the HTML page, you must specify the applet_url for the browser to
load the applet. This attribute enables you to load the class from anywhere on the
internet. The classes used by the applet are dynamically loaded when needed.
Vspace and hspace: These two attributes specify the size of the blank margin to
leave around the applet vertically and horizontally in pixels.
Align: This attribute specifies how the applet will be aligned in browser. One of nine
values is used : left, right, top, texttop, middle, absmiddle, baseline, bottom, and
absbottom.
Alt: This attribute specifies the text to be displayed incase the browser cannot run
java.
Passing parameters to Applets:
To pass parameters to an applet, the parameters must be declared before the applet
starts, and they must be read by the applet when the applet is initialized. The
parameters are declared using the <param> tag in the HTML page. The <param>
tag must be embedded in the <applet> tag, and it has no end tag.
The syntax for the < param > tag is:
<param name=parameter name value=parametervalue>
This tag specifies a parameter and its corresponding value.
Types of Applets:
Difference between Applet and Application:

The AWT contains the following essential classes


Component: - This is a super class of all AWT user interface classes
Container: - This used to group components. A container can be embedded in
another container. A layout manager is used to position and place the components
in the desires location and style in a container. Examples of containers are frames
and panels.
Window: - The Window class can be used to create a top-level window; Windows
subclasses- Frame and Dialog – are used instead.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 22
Frame : - This is a window that is not contained inside another window. Frame is
the basis to contain other user interface components in java graphical applications.
Dialog: - This is a pop-up window that is usually used as a temporary window to
receive additional information from the user or to provide notification that an event
has occurred.
Panel: - This is an invisible container that holds user interface components. You
can place panels in a frame in Java applications or in an applet in java applets.
Applet: - This is a subclass of Panel. Anything you place in a panel can also be
placed in an applet. You use Frame when writing applications and Applet when
writing applets.
Graphics: - This is an abstract class that provides a graphical context for drawing
strings, lines, and shapes.
Color: - This deals with colors of graphics component. For example, you can specify
background or foreground color in a component, such as Frame and Panel, or you
can specify colors of lines, shapes, and strings in drawings.
Font: - This used to draw strings in Graphics. For example, you can specify type
(Times New Roman), style(Bold) and size (24 points) for a string.
FontMetrics: - This is an abstract class that is used to get properties of the fonts
used in drawings.
Panel Applet
AWT Event
Container
Window
Font Frame
Button
FontMetrics Dialog File
Label
Dialog
Color TextField
Object TextComponen
Graphics TextArea
List
Component
Choice

CheckboxGroup

MenuComponent
LayoutManager
Ex:
import java.awt.*;
import java.applet.*;
/*<applet code=ap width=200 height=200></applet>*/
public class ap extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello ramesh !",80,30);

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 23
}
}

Color Class:
The Class Color defines methods and constants for manipulating colors in a java
program. The predefined constants are
Color.black, Color.magneta, Color.blue, Color.orange, Color.cyan, Color.pink,
Color.drakGray, Color.red, Color.gray, Color.white, Color.green, Color.yellow,
Color.lightGray.
The constructors are
Color(int red, int green, int blue)
Color(int rgb value)
Color(float red, float green, float blue)
The first constructor takes three integers that specify the color as a mix of red,
green, and blue. These values must be between 0 and 255.
The second constructor takes a single integer that contains the mix of red, green,
and blue packed into an integer. The integer is organized with red in bits 16 to 23,
green in bits 8 to 15, and blue in bits 0 to 7.
The final constructor takes three float values (between 0.0 to 1.0) that specify that
relative mix of red, green, and blue.
You can change the color by calling the Graphics method
setColor(Color newColor)
You can obtain the current color by calling method getColor()
Color getColor( )
Ex:
import java.awt.*;
import java.applet.*;
/*<applet code=ap width=200 height=200></applet>*/
public class ap extends Applet
{
public void paint(Graphics g)
{
Color c1=new Color(220,185,135);
Color c2=new Color(200,178,230);
Color c3=new Color(150,220,234);
g.setColor(c1);
g.drawString("Hello ramesh !",80,30);
g.setColor(c2);

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 24
g.drawString("Hai vandana ! ",80,60);
g.setColor(c3);
g.drawString(" Sridhar & siva ranjani ",80,120);
}
}

The Font and FontMetrics Classes:


You can set the font for the subjects you draw and use font metrics to obtain font
size. Fonts and font metrics are encapsulated in two AWT classes: Font and
FontMetrics.
Whatever font is current will be used in the subsequent drawing. To set a font, you
need to create a Font object from the Font class.
Font myfont=new Font(name,style,size);
You can choose a font name from TimesRoman,Courier, Helvetica, Symbol, or
Dialog and choose a style from Font.PLAIN,Font.BOLD,Font.ITALIC. The styles can
be combined.
Example:
Font myfont=new Font(“TimesRoman”,Font.BOLD,16);
Font myfont=new Font(“Courier”,Font.BOLD+Font.ITALIC,12);
The fontmetrics class can be used to get the detailed information about the current
font, such as the width or height of characters in pixels(i.e., properties of the font).
We can obtain the width of a single character or a string in pixels. This information
of width in pixels will be useful for centering the text or other text formatting jobs in
a text editor. Font Metrics is an abstract class from java.awt.package.

You can use FontMetrics to compute the exact length and width of a string, which
is helpful for measuring string size in order to display it in the right position. A
FontMetrics is measured by the following attributes:
Leading-Pronounced ledding, this is the amount of space between lines of
text.
Ascent – This the height of a character, from the baseline to the top.
Descent – This is the distance from the baseline to the bottom of a
descnding character, such as j,y, and g.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 25
Height – This is the sum of leading, ascent, and descent.
To get a FontMetrics object for a specific font, use
g.getFontMetrics(Font f)
g.getFontMetrics();
public int stringWidth(String): Given a string, returns the full width of that string
in pixels.
Public int charWidth(char) : Given a character, returns the width of that
Character
Public int getAscent( ) : Returns the ascent of the font
Public int getDescent( ) : Returns the descent of the font
Public int getLeading( ) : Returns the leading of the font
Public int getHeight( ) : Returns the height of the font
Ex:
import java.awt.*;
import java.applet.*;
/*<applet code=ap width=200 height=200></applet>*/
public class ap extends Applet
{
public void paint(Graphics g)
{
Font f1=new Font("Times New Roman",Font.BOLD,20);
Font f2=new Font("Comics Sans MS",Font.ITALIC,20);
Font f3=new Font("Courier New",Font.PLAIN,20);
g.setFont(f1);
g.drawString("Hello ramesh !",80,30);
g.setFont(f2);
g.drawString("Hai vandana ! ",80,60);
g.setFont(f3);
g.drawString(" Sridhar & siva ranjani ",80,120);
}
}

import java.applet.*;
import java.awt.*;

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 26
import javax.swing.*;
/*<applet code=font2 width=400 height=400></applet>*/
public class font2 extends JApplet
{
String s1=JOptionPane.showInputDialog("enter the string ");
String s[]={"Arial","Bookmark Old Style", "Courier
New","Garamond","Impact","Lucida Console", "Times New Roman"};
public void paint(Graphics g)
{
int k=18,y=50;
int red=50,green=50,blue=50;
for(int i=0;i<s.length;i++)
{
g.setFont(new Font(s[i],Font.PLAIN,k));
g.setColor(new Color(red,green,blue));
g.drawString(s1,125,y);
y=y+35;
}
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 27

import java.applet.*;
import java.awt.*;
import javax.swing.*;
/*<applet code=font1 width=400 height=400></applet>*/
public class font1 extends JApplet
{
String s1=JOptionPane.showInputDialog("enter the string ");
public void paint(Graphics g)
{
int k=12,y=50;
for(int i=0;i<s1.length();i++)
{
g.setFont(new Font("Times New Roman",Font.BOLD,k));
g.drawString(s1,125,y);
y=y+35;
k=k+5;
}
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 28

import java.applet.*;
import java.awt.*;
import javax.swing.*;
/*<applet code=font3 width=400 height=400></applet>*/
public class font3 extends Applet
{
String s1=JOptionPane.showInputDialog("enter the string ");
public void paint(Graphics g)
{
int k=15,x=100;
for(int i=0;i<s1.length();i++)
{
g.setFont(new Font("Times New Roman",Font.PLAIN,k));
g.drawString(String.valueOf(s1.charAt(i)),x,100);
x=x+35;
k=k+5;

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 29
}
}
}

import java.applet.*;
import java.awt.*;
import javax.swing.*;
/*<applet code=font4 width=400 height=400></applet>*/
public class font4 extends Applet
{
String s1=JOptionPane.showInputDialog("enter the string ");
public void paint(Graphics g)
{
for(int i=2,col=300,row=20;row<=500;i+=10,col-=20,row+=(40+i-10))
{
g.setFont(new Font("Arial",Font.BOLD,i));
g.drawString(s1,col,row);
}
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 30

Drawing Lines:
You can draw a straight line by using the following method:
drawLine(x1, y1, x2, y2);
The components (x1,y1) and (x2,y2) are the starting and ending points of the line.

(x1,y1)

(x2,y2)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 31
Drawing Rectangles:
Java provides six methods for drawing rectangles in outline or filled with color. You
can draw plain rectangles, rounded rectangles, or 3D rectangles.
To draw a plain rectangle, use
drawRect(x, y, w, h);
To draw a rectangle filled with color, use following code:
fillRect(x, y, w, h);
The component x, y is the upper-left corner of the rectangle, and w and h are the
width and height of the rectangle.

(x, y) W

To draw a rounded rectangle filled with color, use the following code:
fillRoundRect(x, y, w, h, aw, ah);
The component x, y, w and h are the same as in the drawRect() method, the
parameter aw is the horizontal diameter of the arcs at the corner, and ah is the
vertical diameter of the arcs at the corner.

(x, y) W

ah

To draw a 3D rectangle, use


draw3DRect(x, y, w, h, raised);
In which x, y, w, and h are the same as in drawRect( ). The last parameter, a
Boolean value, indicates whether the rectangle is raised or indiented from the
surface.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 32
Ovals:
You can use drawOval( ) or fillOval( ) to draw an oval in outline or filled soild. In
Java, the oval is drawn based on its bounding rectangle; give the parameter as if
you were to draw a rectangle.
To draw an oval, the syntax
drawOval(x, y, w, h);
To draw an oval with color, the syntax
fillOval(x, y, w, h);
The parameters x and y indicate the top-left corner of the bounding rectangle, and
w and h indicate the width and height, of the bounding rectangle.

(x, y) W

Arcs:
Like an oval, an arc is drawn based on its bounding rectangle. An arc is conceived
as part of an oval. The syntax to draw or fill an arc is as follows:
drawArc(x, y, w, h, angle1, angle2);
fillArc(x, y, w, h, angle1, angle2);
The components x, y, w and h are the same as in the drawOval( )method; the
parameter angle1 is the starting angle; angle2 is the spanning angle(that is, the
ending angle is angle1+angle2). Angles are measured in degree and follow the usual
mathematical conventions(that is, 0 degree is at 3’o clock, and positive angles
indicate counterclockwise rotation)
Polygons:
The Polygon class encapsulates a description of a closed, two-dimensional region
with a coordinate space. This region is bounded by a arbitrary number of lines
segments, each of which is one side(or edge) of the polygon. A polygon comprises a
list of (x, y) corrdinate pairs, in which each pair defines a vertex of the polygon, and
two successive pairs are the end points of a line that is a side of the polygon. The
first and final pairs of (x, y) points are joined by a line segment that closes the
polygon.
drawPolygon(x, y, n);
fillPolygon(x, y, n);
The components x and y are arrays of x-coordinates and y-coordinates, and n
indicates the number of points.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 33

import java.applet.*;
import java.awt.*;
import javax.swing.*;
/*<applet code=line1 width=400 height=400></applet>*/
public class line1 extends Applet
{
public void paint(Graphics g)
{
for(int i=0;i<400;i+=10)
{
g.drawLine(0,i,400,i);
g.drawLine(i,0,i,400);
}
}
}

import java.applet.*;
import java.awt.*;
import javax.swing.*;
/*<applet code=line2 width=400 height=400></applet>*/
public class line2 extends Applet
{
public void paint(Graphics g)
{
for(int i=0;i<400;i+=10)
{
g.drawLine(0,i,i,0);
g.drawLine(400,i,i,400);
}
for(int j=0;j<=400;j+=10)
{
g.drawLine(j,0,400,400-j);
g.drawLine(0,j,400-j,400);
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 34
}
}

import java.awt.*;
import javax.swing.*;
/*<applet code=draw width=400 height=500></applet>*/
public class draw extends JApplet
{
public void paint(Graphics g)
{
for(int i=1;i<=25;i++)
g.drawLine(10,10,250,i*10);
}
}

import java.awt.*;
import javax.swing.*
/*<applet code=circle width=300 height=300></applet>*/
public class circle extends JApplet

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 35
{
public void paint(Graphics g)
{
int c=1;
do
{
g.drawOval(110-c*10,110-c*10,c*20,c*20);
++c;
}
while(c<=10);
}
}

import java.applet.*;
import java.awt.*;
import javax.swing.*;
/*<applet code=fish width=600 height=250></applet>*/
public class fish extends Applet
{
public void paint(Graphics g)
{
g.drawArc(100,100,300,100,15,155);
g.drawArc(100,100,300,100,155,345);
g.drawOval(110,140,10,10);
g.drawArc(100,144,30,15,180,180);
for(int i=125;i<350;i+=25)
g.drawArc(i,122,50,75,45,45);
for(int i1=120;i1<350;i1+=25)
g.drawArc(i1,150,50,75,45,45);
for(int i2=125;i2<350;i2+=25)
g.drawArc(i2,175,50,75,45,45);
g.drawArc(400,100,150,100,180,90);

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 36
g.drawArc(400,100,150,100,90,180);
g.drawLine(475,100,420,150);
g.drawLine(420,150,475,200);
}
}

import java.applet.*;
import java.awt.*;
import javax.swing.*;
/*<applet code=lamp width=600 height=250></applet>*/
public class lamp extends Applet
{
public void paint(Graphics g)
{
g.drawArc(100,100,146,100,176,199);
g.drawArc(100,105,145,70,185,178);
g.drawOval(158,88,25,85);
g.fillRect(100,200,150,50);
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 37
Working with Frame Window: - After the applet, the type of window you will most
often create is derived from Frame or JFrame. You will be use it to create child
windows within applets, and top level or child windows for applications. It create a
standard-style window:
Frame()
Frame(String title)
The first form creates a standard window that does not contain a title. The
second form creates a window with the title specified by title. There are several
methods you will use when working with Frame windows.
Methods:
Void setSize(int newwidth,int newheight)
Void setSize(Dimension new size)
The new size the window is specified by new width and new height, or by the
width and height fields of the Dimension object passed in newSize. The dimensions
are specified in terms of pixels.
Dimension getSize()
This method returns the current size of the window contained within the
width and height fields of a Dimension object.
Void setVisible(Boolean on)
The component is visible if the argument to this method is true, otherwise it
is hidden.
SetTitle(String newtitle)
You can change the title in a frame window using setTitle()
import java.awt.*;
import java.awt.event.*;
public class frame1 extends Frame
{
public frame1()
{
addWindowListener(new winHandler());
}
class winHandler extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.setFont(new Font("Times New Roman",Font.BOLD,20));
g.drawString("Hello Srinivas, how r u",100,100);
}
public static void main(String arg[])
{

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 38
frame1 s= new frame1();
s.setBackground(Color.yellow);
s.setTitle("Ramesh Program");
s.setBounds(20,20,400,400);
s.show();
}
}

Event-Driven Programming:
Java graphics programming is event driven. In event-driven programming, the
codes are executed upon activation of events. This section introduces the java
event model
Event and Event Source:
When you are writing programs using the AWT, the program interacts with
the user and the events drive the execution of the program. An event can be
defined as a type of signal to the program that something has happended. The
event is generated by external user actions such as mouse movements, mouse
button clicks, and keystrokes, or by the operating system, such as a timer. The
program can choose to respond or ignore the event.
The GUI component on which the event is generated is called a source object.
For example, clicking a button triggers an event. The button is the souce object,
The source object can be obtained by using the getSource() method. Every event is a
subclass of the AWTEvent class. Various types of AWT events deal with user
component actions, mouse movement, and keystrokes. For convenience, all the
AWT event classes are included in the java.awt.event package.
An event is triggered when a user clicks over a component. The mechanism
being used to generate and handle the events (to execute the code for which the
event is meant) is called as Event Handling Mechanism. In 1.0 version of JDK, it is
known as Hierarchical – Event Model handling and in JDK1.1 on wards it is known
as Delegation-Event Model Handling.
Delegation Event Handling Mechanism:
Step 1: Import the event package
All the interfaces and classes required fro event handling are included by the
jaa designers in the package java.awt.even package(it is a subpackage of java.awt

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 39
package). We must import this package with the following statement and it is must
for every program that decides some actions for their compoenents
Import java.awt.event.*;
Step 2: Implement the Listener interface to be Java class
In the delegation event model, the job of handling and executing the
respective code is delegated to a listener. For each componenet a listener interface
is designed and depending upon the component, we must implement the
appropriate listener interface. For example, for a Button component, we must
implement ActionListener with the class header.
Step 3: Register the listener with the component
Every click over the button, the listener is to be called. For this the button
must be registered with the listener. addXXXListener() method is provided for this
purpose. Each component class defines its own addXXXListener(XXXListener x1)
method. For example Button class defines addActionListener(ActionListener al)
method(here, XXXisAction)
Button object should be registered whith the listener interface through this method.
For example
btn.addActionListener(this)
Here this refers to the current object which implemenents the interface.
Step 4:Implement all the abstract methods of the interface Listener
Being Listener an interface, we must implement all its methods.
ActionLIstener interface declares only one method called public void
actionPerformed(ActionEvent e) which must be overridden with our code that is to
be executed whenever the button is clicked.
As button is registered with the listener, the listener is called whenever
button is clicked.
In java, event handling is a delegation-based model. An external users action
then a user object triggers an event. The object must be registered as a listener by
the source object. The source object maintains a list of listeners and notifies all the
registered listeners when the event occurs. Upon receiving the notification the Java
run time system involves the event-handling on the listener object to respond to the
request.
ActionEvent ContainerEvent

AdjustmentEvent FocusEvent MouseEvent

Event Object AWTEvent ComponentEvent InputEvent

ItemEvent PaintEvent KeyEvent

TextEvent WindowEvent

User Action Source Object Event Type Generated


Clicked on a button Button ActionEvent
Changed text TextComponent TextEvent

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 40
Pressed return on a text field TextField ActionEvent
Double-clicked on a list item List ActionEvent
Selected or deselected an item
With a single click List ItemEvent
Selected or deselected an item Choice ItemEvent
Selected or deselected an item Checkbox ItemEvent
Selected a menu item MenuItem ActionEvent
Moved the scroll bar Scrollbar AdjustmentEvent
Window opened,closed,iconified
Deiconified, or closing Window WindowEvent
Added or removed from the
Container Container ContainerEvent
Component moved, resized,
Hidden or shown Component ComponentEvent
Component gained or lostfocus Component FocusEvent
Key released or pressed Component KeyEvent
Mouse movement Component MouseEvent

Event Registration, Listening, and Handling:


JDK1.1 event handling is a delegation-based model: An external user action on a
source object triggers an event. An object intersted in the event receives the event.
Such an object is called a listener. Not all objects can receive events. To become a
listener, the object must be registered as a listener by the source object. The source
object maintains a list of listeners and notifies all the registered listeners when the
event occurs. Upon receiving the notification, the java runtime system invokes the
event-handling method on the listener object to respond to the event.

Event Object
User
Action Generating an event
Notify Listener

Triggering an event
Listener Object
Source Object
Event Handler
Register a listener object

Event Class Listener Interface Listener Methods (Handlers)


ActionEvent ActionListener actionPerformed(ActionEvent)
ItemEvent ItemListener itemStateChanged(ItemEvent)
WindowEvent WindowListener windowClosing(WindowEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowDeiconfied(WindowEvent)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 41
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
ContainerEvent ContainerListener componentAdded(ContainerEvent)
componentRemoved(ContainerEvent)
ComponentEvent ComponentListener componentMoved(ComponentEvent)
componentHidden(ComponentEvent)
componentResized(ComponentEvent)
componentShown(ComponentEvent)
FocusEvent FocusListener focusGained(FocusEvent)
focusLost(FocusEvent)
TextEvent TextListener textValueChanged(TextEvent)
KeyEvent KeyListener keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)
MouseEvent MouseListener mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mouseClicked(MouseEvent)
MouseMotionListener mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
AdjustmentEvent AdjustmentListener adjustmentValueChanged
(AdjustmentEvent)
----------------------------------------------------------------------------------------------------

AWT Components:

Label:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 42
Labels are simple text strings used to label other components(usually text fields).
Like other components, the layout managers can place labels inside a container.
The constructors are
public Label(String s,int alignment)
This creates a label with the specified string and alignment (Label.LEFT,
Label.RIGHT, or Label.CENTER).
public Label(String s)
This creates a label with string s using default left alignment.
public Label( )
This creates an empty Label.

Methods:
public getText()
This returnsa string for the label.
public setText(String s)
This changes the text string of the label.
public getAlignment( )
This returns the alignment of the label.
public setAlignment(int Alignment)
This resets the alignment of the label.

Button:
A button is a component that triggers an event when pressed.
public Button()
This creates an empty button with no label.
public Button(String s)
This creates a button labeled with the specified string.
Methods:
public String getLabel( )
This returns the label of a button
Public void setLabel(String str)
This changes the label of the button with the new specified string str

Buttons generate ActionEvent. You must implement the actionPerformed() method


in the ActionListener interface.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*<applet code=car width=400 height=400></applet>*/
public class car extends Applet implements ActionListener
{
Label l1;
Button b1,b2;

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 43
String s1=" ";
public void init()
{
l1=new Label(" Do you know Car Driving ? ");
b1=new Button("Yes");
b2=new Button();
b2.setLabel("No");
add(l1);
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String s=e.getActionCommand();
if(s.equals("Yes"))
s1=" Congrats. You r selected ";
else
s1=" Sorry you r rejected ";
repaint();
}
public void paint(Graphics g)
{
g.drawString(s1,50,120);
}
}

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

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 44
import javax.swing.*;
/*<applet code=co1 width=400 height=400></applet>*/
public class co1 extends Applet implements ActionListener
{
Button b1,b2,b3,b4;
String s1=" ";
public void init()
{
b1=new Button("red");
b2=new Button("green");
b3=new Button("yellow");
b4=new Button("blue");
add(b1);
add(b2);
add(b3);
add(b4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
setBackground(Color.red);
else
if(e.getSource()==b2)
setBackground(Color.green);
else
if(e.getSource()==b3)
setBackground(Color.yellow);
else
if(e.getSource()==b4)
setBackground(Color.blue);
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 45

TextField:
A textfield is an input area where the user can type in characters. Text fields are
useful in that they enable the user to enter in variable data (a name or a
description)
The constructors are
public TextField(int width)
This creates an empty text field with the specified number of columns
Public TextField(String s)
This creates a text field initialized with the specified string s
Public TextField(String s, int width)
This creates a textfield initialized with the specififed string s and the column size
width.

Methods:
public String getText()
This returns the string from the text field.
public void setText(String s)
This puts the given string in the text field.
public void setEditable(boolean editable)
This enables or disables the textfield to be edited. By default, editable is true.
public void setColumns (int)
This sets the number of columns in this text field. The length of the text filed is
changeable.
TextField might generate ActionEvent and ItemEvent. Pressing return on a
text field triggers the ActionEvent. Changing contents on a text filed triggers the
ItemEvent.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=text1 width=400 height=400></applet>*/
public class text1 extends Applet implements ActionListener

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 46
{
Label l1,l2,l3;
TextField t1,t2,t3;
Button b1;
public void init()
{
l1=new Label(" enter the first value :");
l2=new Label(" enter the second value :");
l3=new Label(" result : ");
t1=new TextField(15);
t2=new TextField(15);
t3=new TextField(15);
b1=new Button(" Add ");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String s1=t1.getText();
String s2=t2.getText();
int x=Integer.parseInt(s1);
int y=Integer.parseInt(s2);
int z=x+y;
t3.setText(String.valueOf(z));
}
}

TextArea:
If you want to let the user enter multiple lines of text, you can’t use TextField unless
you create several of them. The solution is to use TextArea, which enables the user
to enter multiple lines of text.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 47
The constructors are
public TextArea(int rows, int cols)
This creates a text area with the specified number of rows and columns.
public TextArea(String s, int rows, int cols)
This creates a text area with the initial text and the number of rows and cols
specified.
public TextArea(String s, int nlines, int nchars, int sbars)
nlines specifies the height in lines, nchars specifies the width in characters.
s specifies the string filled with TextArea
Sbars specifies the scroll bars that are associated with the TextArea
Sbars must have one of these values:
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
Methods:
public void insert(String s,int pos)
This inserts string s in the specified position in the text area.
public void append(String s)
This appends string s to the end of the text.
public void replaceRange(String s, int start, int end)
This replaces partial texts in the range from position start to position end with
string s.
Public int getRows( )
This returns the number of rows in the text area.

Checkbox:
A Checkbox is a component that enables the user to toggle a choice on or off, like
a light switch.
The constructors are
public Checkbox()
public Checkbox(String label)
public Checkbox(String label,Boolean on)
The first form creates a checkbox whose label is initially blank. The state of
the checkbox is unchecked. The second form creates a checkbox whos lable is
specifid by label. The state of the check box is unchecked. The third form allows
you to set the initial state of the checkbox. If on is true, the checkbox is initially
checked; otherwise, it is cleared.
To retrieve the current state of a checkbox, call getState(), To set its state, call
setState(). You can obtain the current label associated with a check box by calling
getLabel(). To set the label, call setLabel()
Boolean getState()
Void setState(Boolean on)
String getLabel()
Void setLabel(String str)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 48
Here, if on is true, the box is checked. If it is false, the box is cleared. The string
passed in str becomes the new label associated with the invoking check box.
Handling Checkboxes: 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 the component. Each listener
implements the ItemListener interface. That interface defines the
itemStateChanged() method. An ItemEvent object is supplied as the argument to the
method.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=checkbox width=400 height=400></applet>*/
public class checkbox extends Applet implements ItemListener
{
Checkbox c1,c2,c3,c4;
public void init()
{
c1=new Checkbox("Windows 98");
c2=new Checkbox("Windows NT");
c3=new Checkbox("Windows Xp ",true);
c4=new Checkbox("Linux ");
add(c1);
add(c2);
add(c3);
add(c4);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
String s=" selected Item is ";
g.drawString(s,50,120);
g.drawString(" Window 98 : "+c1.getState(),50,140);
g.drawString(" Window NT : "+c2.getState(),50,160);
g.drawString(" Window Xp : "+c3.getState(),50,180);
g.drawString(" Linux : "+c4.getState(),50,200);
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 49

CheckboxGroup:
Checkbox groups, also known as option buttons, are variations of check boxes, but
only one box in the group can be checked at a time. Its appearance is similar to a
check box. Check boxes display a square that is either checked or blank, and a
check box in the group displays a circle that is either filled( if selected) or blank( not
selected).
The constructor are
CheckboxGroup cgb=new CheckboxGroup();
This creates the CheckboxGroup object cgb.

Checkbox cb1;
add(cb1=new Checkbox(“Choice name 1”,cgb,true));
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=text width=400 height=400></applet>*/
public class text extends Applet implements ItemListener
{
Checkbox c1,c2,c3,c4;
CheckboxGroup cb;
public void init()
{
cb=new CheckboxGroup();
c1=new Checkbox("Windows 98",cb,false);
c2=new Checkbox("Windows NT",cb,false);
c3=new Checkbox("Windows Xp ",cb,true);
c4=new Checkbox("Linux ",cb,false);
add(c1);
add(c2);
add(c3);
add(c4);
c1.addItemListener(this);
c2.addItemListener(this);

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 50
c3.addItemListener(this);
c4.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
String s=" selected Item is ";
g.drawString(s,50,120);
String s1=cb.getSelectedCheckbox().getLabel();
g.drawString(s1,50,140);
}
}

Choice:
A choice is a simple list of items from which the user can choose. It’s useful in
limiting a user’s range of choices and avoids the cumbersome validation of data
input. You can easily choose and extract the value in a choice box.
The constructors are
public Choice( )
This creates a Choice component.

Methods:
public void addItem(String s)
This adds the item s into the choice.
public String getItem(int index)
This gets an item from the choice at the specified index.
public int getSelectedIndex( )
This gets the index of the selected item.
public String getSelectedItem( )
This gets the selected item.
public void select(int pos)
This selects the item with the specified position.
public void select(String str)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 51
This selects the item with the specified string.
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
even 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.

List:
A List is a component that performs basically the same function as a Choice, but it
enables the user to choose a single value or multiple values.
public List(int rows, boolean multipleselection)
This creates a new scrolling list with the specified number of visible rows and the
parameter multipleselection indicates whether multiple selection is eabled.
public List(int rows)
This creates a new single selection scrolling list initialized with the specified number
of visible rows.
public List()
This creates a new scrolling list initialized with no visible lines or multiple
selections.

Methods:
public void addItem(String s)
Adds the item s into the list.
public String getItem(int row)
This gets an item from the list at the specified row.
public int getSelectedIndex( )
This gets the index of the selected item
public String getSelectedItem()
This gets the selected item
Public String[ ] getSelecteditems()
This returns an array of strings containing the selected items.

List may generate ActionEvent and ItemEvent. Clicking a list item triggers the
ItemEvent. To trigger the ActionEvent, you need to double-click the selected item.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*<applet code=choice width=400 height=400></applet>*/
public class choice extends Applet implements ItemListener
{
Choice c2;
List l1;
public void init()
{

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 52
l1=new List(4,true);
c2=new Choice();
String
s1[]={"suresh","sateesh","kumar","ashok","kiran","vinod","ramesh","kishore"};
for(int i=0;i<s1.length;i++)
l1.addItem(s1[i]);
String s[]={" grap ","banana","apple","orange"};
for(int i=0;i<s.length;i++)
c2.addItem(s[i]);
add(l1);
add(c2);
l1.addItemListener(this);
c2.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
String s2[]=l1.getSelectedItems();
String s3=" ";
for(int i=0;i<s2.length;i++)
s3=s3+" "+s2[i];
g.drawString(" Names :"+s3,50,120);
g.drawString(" Fruits :"+c2.getSelectedItem(),50,140);
}
}

Scrollbar: - 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 uit 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

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 53
user can drag the slider box to a new position. The scroll bar will then reflect this
value. In the background space on either side of the thumb, the user can click to
cause the thumb to jump in that direction by some increment larger than 1.
Typically, this action translates into some form of page up and page down.
The Scrollbar class encapsulates scroll bars
Scrollbar()
Scrollbar(int style)
Scrollbar(int style,int initialvalue, int thumbsize, int min,int max)
The first form creates a vertical scroll bar. The second and third forms allow
you to specify the orientation of the scroll bar. If style is Scrollbar.VERTICAL, a
vertical scroll bar is created. If style is Scrollbar.HORIZOTAL , the scroll bar is
horizontal. In the third form of the constructor, the intial value of the scroll bar is
passed in intial value. The number of units represented by the height of the thumb
is passed in thumb Size. The minimum and maximum values for the scrollbar are
specified by min and max.
To obtain the current value of the scrollbar, call getValue(). It returns the
current setting. To set the current value, call setValue().
int getValue()
int setValue(int new value)
Here, newvalue specifies the new value for the scroll bar. When you set a
value, the slider box inside the scroll bar will be positioned to reflect the new value.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=scroll width=400 height=400></applet>*/
public class scroll extends Applet implements AdjustmentListener
{
Scrollbar s1,s2;
TextField t1;
public void init()
{
s1=new Scrollbar(Scrollbar.HORIZONTAL,10,15,0,200);
s2=new Scrollbar(Scrollbar.VERTICAL,10,15,0,200);
t1=new TextField(15);
add(s1);
add(t1);
add(s2);
s1.addAdjustmentListener(this);
s2.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
if(e.getAdjustable()==s1)
{
s1.setValue(s1.getValue());
t1.setText("Horizontal value :"+s1.getValue());

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 54
}
else
{
s2.setValue(s2.getValue());
t1.setText("Vertical value : "+s2.getValue());
}
}
}

Point Constructor:
Point(int x,int y)
This constructs a Point object with the specified x and y coordinates.
You can use the move(int x,int y) method to move the point to the specified x and y
coordinates.
MouseEvent Methods:
public int getClickCount( )
This returns the number of mouse clicks associated with this event.
public Point getPoint( )
This returns the x-and y-coordinates of the event relative to the source component.
public int getX( )
This returns the x-coordinate of the event relative to the source component.
public int getY( )
This returns the y-corrdinate of the event relative to the source component.

The MouseEvent class inherits InputEvent. You can use the methods define in the
InputEvent class on a MouseEvent object.
InputEvent Methods:
public long getWhen( )
This returns the time stamp of when this event occurred.
public boolean isAltDown( )
This returns whether the Alt modifier is down on this event.
public boolean isControlDown( )
This returns whether the Control modifer is down on this event.
public boolean isMetaDown( )
This returns whether the Meta modifier is down on this event.
public boolean isShiftDown( )
This returns whether the Shift modifier is down on this event.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 55
Mouse Event Handling: This section presents the MouseListener and
MouseMotionListener event-listener interfaces for handling mouse events

Write a program to create an applet to the draw Rectangle using mouse


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code=mouse width=400 height=400></applet>*/
public class mouse extends Applet implements MouseListener,MouseMotionListener
{
int x=0,y=0,x1=0,y1=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
x=e.getX();
y=e.getY();
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseDragged(MouseEvent e)
{
x1=e.getX();
y1=e.getY();
repaint();
}
public void mouseMoved(MouseEvent e)
{
}
public void paint(Graphics g)
{
g.drawRect(x,y,x1-x,y1-y);
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 56
}

Keyboard Event Handling:


This section presents the KeyListener event-listener interface for handling key
events. Key events are generated when keys on he keyboard are pressed and
released. A class that implements KeyListener must provide definitions for methods
keyPreseed, keyReleased and keyTyped, each of which receives a KeyEvent as its
argument.

Key Constants:
Constant Description
VK_HOME The Home key
VK_END The End key
VK_PGUP The Page Up key
VK_PGDN The Page Down key
VK_UP The Up arrow key
VK_DOWN The down arrow key
VK_LEFT The left arrow key
VK_RIGHT The right arrow key
VK_ESCAPE The Esc key
VK_TAB The tab key
VK_BACK_SPACE The backspace key
VK_CAPS_LOCK The Caps lock key
VK_NUM_LOCK The Num lock key
VK_ENTER The Enter key
VK_F1 to VK_F12 The function keys f1 to f12
VK_0 to VK_9 The number keys from 0 to 9
VK_A to VK_Z The letter keys from A to Z
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class key extends Frame implements KeyListener
{

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 57

public key()
{
super("Using Key Events ");
addKeyListener(this);
setSize(200,200);
setVisible(true);
}
public void keyPressed(KeyEvent e){ }
public void keyReleased(KeyEvent e){ }
public void keyTyped(KeyEvent e)
{
char ch=e.getKeyChar();
if(ch=='r')
setBackground(Color.red);
else
if(ch=='R')
setBackground(Color.red);
else
if(ch=='g'||ch=='G')
setBackground(Color.green);
else
if(ch=='b')
setBackground(Color.blue);
else
if(ch=='m')
setBackground(Color.magenta);
else
if(ch=='c')
setBackground(Color.cyan);
else
System.out.println("type only r,g,b,c,m only");
}
public static void main(String arg[])
{
new key();
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 58

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code=keyevent width=400 height=400></applet> */
public class keyevent extends Applet implements KeyListener
{
int x=100,y=100;
char ch='A';
public void init()
{
addKeyListener(this);
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
switch(e.getKeyCode())
{
case KeyEvent.VK_DOWN:y+=10;break;
case KeyEvent.VK_UP:y-=10;break;
case KeyEvent.VK_LEFT:x-=10;break;
case KeyEvent.VK_RIGHT:x+=10;break;
default:ch=e.getKeyChar();
}
repaint();
}
public void paint(Graphics g)
{
g.setFont(new Font("Times New Roman",Font.BOLD,24));
g.drawString(String.valueOf(ch),x,y);
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 59
}

Adapter Classes: Many of the event-listener interfaces provide multiple methods;


MouseListener and MouseMotionListener are examples. It is not always desireable
to define every method in an event-listener interface. For example, a program many
only need the mouseClicked handler from interface MouseListener or the
mouseDragged handler from MouseMotionListener. In our windowed applications
(subclasses of JFrame) terminating the application has been handled with
windowClosing from interface WindowListener, which actually specifies seven
window-event handling methods. For many of the listener interfaces that contain
multiple methods, package java.awt.event and package javax.swing.event provide
event-lister adapter classes. An adapter class implements an interface and provides
a default implementation (with an empty method body) of every method in the
interface.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code=mouse1 width=400 height=400></applet>*/
public class mouse1 extends Applet
{
int x=0,y=0,x1=0,y1=0;
public void init()
{
addMouseListener(new adapter1());
addMouseMotionListener(new adapter2());
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 60
class adapter1 extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
x=e.getX();
y=e.getY();
}
}
class adapter2 extends MouseMotionAdapter
{
public void mouseDragged(MouseEvent e)
{
x1=e.getX();
y1=e.getY();
repaint();
}
}
public void paint(Graphics g)
{
g.drawRect(x,y,x1-x,y1-y);
}
}

Layout Managers: - A layout manager automatically arranges your controls withing


a window by using some typ of algorithm. 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 always set by
using method called setLayout() method. If suppose there is not call to setLayout( )
method then thedefault manager is used. Whenever a container is resized, the
layout manager is used to position each of the componenets within it.
The general format of the setLayout() method is as follows:
Void setLayout(layoutmanager l)

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 61
Here l is a reference to the desired layout manager. There are different types
of layout managers.
1. Flow Layout 2. BorderLayout 3. GridLayout
4. CardLayout 5. GridBagLayout
FlowLayout:
FlowLayout is the simplest layout manager. The components are arranged in the
container from left to right in the order in which they were added. When one row
becomes filled, a new row is started. You can specify the way the components are
aligned by using one of three constants: FlowLayout.RIGHT, FlowLayout.CENTER,
and FlowLayout.LEFT. You can also specify the gap between components in pixels.
Constructors:
public FlowLayout(int align,int hgap, int vgap)
This constructs a new FlowLayout with a specified alignment, horizontal gap, and
vertical gap. The gaps are the distances in pixels between components.
Public FlowLayout(int alignment)
This constructs a new FlowLayout with a specified alignment and a default gap of
pixels for both horizontal and vertical.
Public FlowLayout()
This constructs a new FlowLayout with a default center alignment and a default gap
of five pixels for both horizontal and vertical.

GridLayout:
The GridLayout manager arranges componets in a grid(matrix) formation with the
number of rows and columns defined by the constructor. The components are
placed in the grid from left to right starting with the first row, then the second, and
so on, in the order in which they are added.
Constructors:
Public GridLayout(int rows, int columns)
This constructs a new GridLayout with the specified number of rows and columns.
Public GridLayout(int rows, int columns, int hgap, int vgap)
This constructs a new GridLayout with the specified number of rows and columns,
along with specified horizontal and vertical gaps between components.

BorderLayout:
The BorderLayout manager divides the window into five areas: East, South, West,
North and Center. Components are added to a BorderLayout by using
add(String,Component), Where String is “East”,”South”,”West”,”North” or “Center”.
Constructors:
Public BorderLayout(int hgap, int vgap)
This constructs a new BorderLayout with the specified horizontal and vertical gaps
between the components.
Public BorderLayout()
This constructs a new BorderLayout without horizontal or vertical gaps.
The components are laid out according to their preferred sizes and the constraints
of the container’s size. The North and South components can be stretched

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 62
horizontally; the East and West components can be stretched vertically; the Center
component can stretch both horizontally and vertically to fill any empty space.

The CardLayout Manager:


The CardLayout manager arranges components in a queue of cards. You can only
see one card at a time. To construct a CardLayout manager, simply use the
constructor CardLayout()
Cards are usually placed in a container such as a panel. Components are placed
into the card queue in the order in which they are added. To add a component in
the CardLayout container, use the following method:
void add(component com, String name)
This adds the specified component to this container at the specified index denoted
by the specified string. The String argumnet of the method, name gives an explicit
identity to the component in the queue.
Methods:
public void first(container)
This method views the first card in the container.
public void last(container)
This method views the last card in the container.
public void next(container)
This method views the next card in the container.
public void previous(container)
This method views the previous card in the container.
public void show(Container, String name)
This method views the component with the specified name in the container.

The GridBagLayout Manager:


The GridBagLayout manager is the most flexible and the most complex. It is similar
to the GridLayout manager in the sense that both layout managers arrange
componenets in a grid. The components can vary in size, and can be added in any
order in GridBagLayout.
The constructor GridBagLayout() is used to create a new GridBagLayout. In the
GridLayout, the grid size( the number of rows and cols) is specified in the
constructor.
Each GridBagLayout uses a dynamic rectangular grid of cells, with each component
occupying one or more cells called its display area. Each component managed by a
GridBagLayout is associated with a GridbagConstriants instance that specifies how
the component is laid out within its display area. How a GridBagLayout places a
set of components depends on each component’s Grid BagConstraints and
minimum size, as well as the preferred size of the component’s container.

GridBagConstants variables are:

gridx and gridy: - Specifies the cell at the upper left of the component’s display area,
where the upper-left-most cell has address gridx=0, gridy=0. Note that gridx

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 63
specifies the column in which the component will be placed, and gridy specifies the
row in which the component will be placed.
gridwidth and gridheight: - Specifies the number of cells in a row(for gridwidth) or
column(for gridheight) in the component’s display area. The default value is 1.
weightx and weighty: - Specifies the extra space to allocate horizontally and
vertically for the component when the window is resized. Unless you specify a
weight for at least one component in a row(weightx) and a column(weighty), all the
components clump together in the center of their container. This is because when
the weight is zero(the default), the GridBagLayout puts any extra space between its
grid of cells and the edges of the container.
fill: - Specifies how the component should be resized if the component’s viewing
area is larger than its current size. Valid values are GridBagConstraints.NONE (the
default), GridBagConstraints.HORIZONTAL (make the componet wide enough to fill
its display area horizontally, but don’t change its height),
GridBagConstraints.VERTICAL (make the component tall enough to fill its display
area vertically, but don’t change its width), and GridBagConstraints.BOTH (make
the component fill its display area entirely).
anchor: - Specifies where in the area the component is palced when the component
does not fill in the entire area. Valid values are as follows:
GridBagConstaints.CENTER (the default)
GridBagConstaints.NORTH
GridBagConstaints.NETHEAST
GridBagConstaints.EAST
GridBagConstaints.SOUTHEAST
GridBagConstaints.SOUTH
GridBagConstaints.SOUTHWEST
GridBagConstaints.WEST
GridBagConstaints.NORTHWEST
The fill and anchor parameters deal withy how to fill and place the component when
the viewing area is larger than the requested area. The fill and anchor parameters
are class variables, while gridx, gridy, width, height, weightx, weighty are instance
variables.

Panels:
Suppose that you want to place 10 buttons and a text field on a frame. The buttons
are placed in grid formation, but the text field is placed on a separate row. It is
difficult to achieve the desired look by placing all the components using a single
container. With AWT programming, imagine dividing a window into panels. Panels
act as smaller containers for grouping user interface components. You can add the
butons in one panel and the text fields in another and then add the panels into the
frame.
Constructor:
Panel p= new Panel( );
By default, panels use FlowLayout.

Canvases:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 64
Canvas is a UI component that can be used to draw graphics and enable user
interaction. When you create and display a Canvas object, it appears as a blank
space inside the container. Only a few functions enable you to manipulate a
Canvas, sich as setting the color and size and getting events. If you extend this
class, you can customize your own canvas and use it as a backdrop for your GUI.

Menu:
Menus make selection easier, and are widely used in window applications. In Java,
menus can only appear on a frame. Java provides three classes-MenuBar, Menu
and MenuItem – to implement menus in a frame.
A frame can hold a menubar to which the pull-down menus are attached. Menus
consist of menu items that the user can select (or toggle on or off). Menu baras can
be viewed as a structure to support menus.
1. Create a menu bar and associate in with a frame.
Frame f=new Frame( );
f.setSize(300,200);
f.setVisible(true);
MenuBar mb=new MenuBar( );
f.setMenuBar(mb);
This code creates a frame and a menu bar, and sets the menu bar in the frame.
2. Create menus
You can use the following constructors to create a menu.
public Menu(String label, boolean f)
This constructs a new Menu instance with the specified label and f. The true f
enables the programmer to create a menu that displays even when the mouse
button is released.
public Menu(String label)
This constructs a new menu instance with the specified label. It is equivalenet to
Menu(label,false)

The character “-“ separates menu items. You may also use the addSeparator()
method to separate menu items.
F1.addSeparator( )

import java.awt.*;
import java.awt.event.*;
public class menu1 extends Frame implements ActionListener
{
MenuBar m;
Menu m1,m2,m3,m4;
MenuItem mm1,mm2,mm3,mm4,mm5,mm6,mm7,mm8,mm9,mm10;
String s=" ";
public menu1( )
{
setTitle(" Sample menu ");

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 65
setLayout(new FlowLayout());
m=new MenuBar();
setMenuBar(m);
m1=new Menu("Master");
mm1=new MenuItem(" Material Master ");
mm2=new MenuItem(" Vendor Master ");
mm3=new MenuItem(" Department Master ");
m1.add(mm1);
m1.add(mm2);
m1.add(mm3);
m.add(m1);
m2=new Menu("Entry");
mm4=new MenuItem("Purchase");
mm5=new MenuItem("Product");
m3=new Menu("Delivery");
mm6=new MenuItem(" Purchase Return ");
mm7=new MenuItem(" Sales ");
mm8=new MenuItem(" Transfer ");
m3.add(mm6);
m3.add(mm7);
m3.add(mm8);
m2.add(m3);
m2.add(mm4);
m2.add(mm5);
m.add(m2);
m4=new Menu("Quit");
mm9=new MenuItem("Software");
mm10=new MenuItem("Program");
m4.add(mm9);
m4.add(mm10);
m.add(m4);
mm1.addActionListener(this);
mm2.addActionListener(this);
mm3.addActionListener(this);
mm4.addActionListener(this);
mm5.addActionListener(this);
mm6.addActionListener(this);
mm7.addActionListener(this);
mm8.addActionListener(this);
mm9.addActionListener(this);
mm10.addActionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 66
}
});
setBounds(1,1,400,400);
show();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==mm1)
s="Material Master";
else
if(e.getSource()==mm2)
s="Vendor Master ";
else
if(e.getSource()==mm3)
s="Department Master";
else
if(e.getSource()==mm4)
s="Purchase Entry";
else
if(e.getSource()==mm5)
s="Product Entry ";
else
if(e.getSource()==mm6)
s="Purchase return delivery";
else
if(e.getSource()==mm7)
s="Sales Delivery Entry";
else
if(e.getSource()==mm8)
s="Transfer of Goods Entry ";
else
if(e.getSource()==mm9)
{
s="Software Quiting ";
System.exit(0);
}
else
if(e.getSource()==mm10)
{
s="Program Quiting ";
System.exit(0);
}
repaint();
}
public void paint(Graphics g)
{

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 67
g.drawString(s,50,250);
}
public static void main(String arg[])
{
new menu1();
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 68
Swing Overview:
Swing is a set of classes that provides more powerful and flexible functionality than
in possible with the standard AWT components. The classes that are used to create
the GUI components are part of the swing GUI components from package
javax.swing. These are the newest GUI components of the Java2 platform. Swing
components are written, manipulated and displayed completely in Java, so called
pure java components.
The outset that Swing is built upon the foundation of AWT. So, that Swing
provides all the facilities that are supported by the AWT in addition that it also
provides some additional components such as tabbed panes, scroll panes, trees and
tables.
Main difference between AWT and Swing components are in AWT , a
appearance and sometimes even different interactions on each platform. AWT
components are tied to the local platform are corresponding called heavy weight
components. Whereas, Swing component programs are gave same look in any java
platform even we change the environment. So, that the program running with Swing
components are often referred as lightweight components. These are platform
independent.
The classes that are used to create the GUI components below are part of the Swing
GUI components from package javax.swing. These are the newest GUI components
of the Java 2 platform. Swing components (as they are commonly called) are
written, manipulated and displayed completely in Java (so-called pure components)

Swing components package javax.swing


JLabel : An area where un editable text or icons can be displayed.
JTextField : An area in which the user inputs data from the keyboard. The
are can also display information.
JButton : An area that triggers an event when clicked.
JCheckBox : A GUI component that is either selected or not selected.
JComboBox: A drop-down list of items from which the user can make a
selection by clicking an item in the list or by typing into the box.
Jlist : An area where a list of items are displayed from which the user
can make a selection by clicking once on any element in the list.
Double-clicking an element in the list generates an action Event.
Multiple elements can be selected.
JPanel : A container in which components can be placed.

The original GUI components from the Abstract Windowing Toolkit package
java.awt (also called the AWT) are tied directly to the local platform’s graphical user
interface capabilities. So, a java program executing on different java platforms has a
different appearance and sometimes even different user interactions on each
platform. The appearance and how the user interacts with the program are known
as that program look and feel. The Swing components allow the programmer to
specify a different look and feel for each platform, or a uniform look and feel across
all platforms, or event to change the look-and-feel while the program is running.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 69
Swing components are often referred to as lightweight components –they are written
completely in java so they are not “weighted down” by the complex GUI capabilities
of the platform on which they are used. AWT components (many of which parallel
the swing components) that are ties to the local platform are correspondingly called
heavyweight components – they rely on the local platform’s windowing system to
determine they functionality and their look and feel. Each heavyweight component
has a per (from package java.awt.peer) that is responsible for the interactions
between the component and the local platform to display and manipulate the
component. Several swing components are still heavy weight component. In
particular, sub classes of java.awt.window that display windows on the screen still
require direct interaction with the local windowing system. As such, heavyweight
swing GUI components are less flexible that many of the lightweight components we
will demonstrate.
Each class is displayed with its fully qualified package name and class name.
Much of each GUI component’s functionality is derived from these classes. A class
that inherits from the Component class is a component. For example, class
Container inherits from class Component, and class Component inherits from class
Component, and class Component inherits from Object. A Container is a
Component and is an Object, and a Component is an Object. A class that inherits
from class Container is a Container. A JComponent is a Container.
Class Component defines the methods that can be applied to an object of any
subclass of Component. Two of the methods that originate in class Component have
been used frequently to this point in the text – paint and repaint. It is important to
understand the methods of class Component because much of the functionality
inherited by every subclass of Component is defined by the Component class
originally. Operations common to most GUI components (both Swing and AWT) are
found in class Component.
A Container is a collection of related components. In applications with
JFrames and in applets, we attach components to the content pane – a Container.
Class Container defines the set of methods that can be applied to an object of any
subclass of Container. One method that originates in class Container that has been
used frequently to this point in the text is add for adding components to a content
pane. Another method that originates in class Container is setLayout, which has
been used to specify that layout manager that helps a Container position and size
its components.
Class JComponent is the super class to most Swing components. This class
defines the set of methods that can be applied to any subclass of JComponent.
Swing components that subclass JComponent have many features including:
1. A pluggable look and feel that can be used to customize the look and fell when
the program executes on different platforms.
2. Shortcut keys for direct access to GUI components through the use of keyboard.
3. Common event handling capabilities for cases where several GUI components
initiate the same actions in a program.
4. Brief descriptions of a GUI component’s purpose (called tool tips) that are
displayed when the mouse cursor is positioned over the component for a short time.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 70
5. Support for assistive (related) technologies such as Braille screen readers for
blind people.
Working with Frame Window: - After the applet, the type of window you will most
often create is derived from Frame or JFrame. You will be use it to create child
windows within applets, and top level or child windows for applications. It create a
standard-style window:
A JFrame is a window with a title bar and border. Class JFrame is a sub
class of java.awt.Frame (which is a subclass of java.awt.window). JFrame is one of
the few swing GUI components that are not considered to be a light weight GUI
component.
Swing is a large set of components ranging from the very simple, such as
labels, to the very complex, such as tables, trees, and styled text documents.
Almost all Swing components are derived from a single parent called JComponent
which extends the AWT Container class. Thus, Swing is best described as a layer on
top of AWT rather than a replacement for it. Figure 1.2 shows a partial JComponent
hierarchy. If you compare this with the AWT Component heirarchy of figure 1.1 you
will notice that for each AWT component there is a Swing equivalent with prefix “J”.
The only exception to this is the AWT Canvas class, for which JComponent, JLabel,
or JPanel can be used as a replacement (in section 2.8 we discuss this in detail).
You will also notice many Swing classes with no AWT counterparts.
Figure 1.2 represents only a small fraction of the Swing library, but this
fraction consists of the classes you will be dealing with most. The rest of Swing
exists to provide extensive support and customization capabilities for the
components these classes define.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 71

Swing package overview


javax.swing
Contains the most basic Swing components, default component models, and
interfaces. (Most of the classes shown in Figure 1.2 are contained in this
package.)
javax.swing.border
Classes and interfaces used to define specific border styles. Note that borders
can be shared by any number of Swing components, as they are not
components themselves.
javax.swing.colorchooser
Classes and interfaces supporting the JColorChooser component, used for
color selection. (This package also contains some interesting undocumented
private classes.)
javax.swing.event

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 72
The event package contains all Swing-specific event types and listeners.
Swing components also support events and listeners defined in java.awt.event
and java.beans.
javax.swing.filechooser
Classes and interfaces supporting the JFileChooser component, used for file
selection.
javax.swing.plaf
Contains the pluggable look-and-feel API used to define custom user interface
components. Most of the classes in this package are abstract. They are sub
classed and implemented by look-and-feel implementations such as metal,
motif, and basic. The classes in this package are intended for use only by
developers who, for one reason or another, cannot build on top of existing
look-and-feels.
javax.swing.plaf.basic
Consists of the Basic look-and-feel implementation which all look-and-feels
provided with Swing are built on top of. We are normally expected to subclass
the classes in this package if we want to create our own customized look-and-
feel.
javax.swing.plaf.metal
Metal is the default look-and-feel of Swing components. It is the only lookand-
feel that ships with Swing not designed to be consistent with a specific
platform.
javax.swing.plaf.multi
This is the Multiplexing look-and-feel. This is not a regular look-and-feel
implementation in that it does not define the actual look or feel of any
components. Rather, it provides the ability to combine several look-and-feels
for simultaneous use. A typical example might be using an audio-based look-
and-feel in combination with metal or motif. Currently Java 2 does not ship
with any multiplexing look-and-feel implementations (however, rumor has it
that the Swing team is working on an audio look-and-feel as we write this).
javax.swing.table
Classes and interfaces supporting the JTable control. This component is used
to manage tabular data in spreadsheet form. It supports a high degree of
customization without requiring look-and-feel enhancements.
javax.swing.text
Classes and interfaces used by the text components including support for
plain and styled documents, the views of those documents, highlighting, caret
control and customization, editor actions and keyboard customization.
javax.swing.text.html
This extension of the text package contains support for HTML text
components. (HTML support was being completely rewritten and expanded
upon while we were writing this book. Because of this our coverage of it is
regrettably limited.)
javax.swing.text.html.parser
Support for parsing HTML.
javax.swing.text.rtf

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 73
Contains support for RTF documents.
javax.swing.tree
Classes and interfaces supporting the JTree component. This component is used for
the display and management of hierarchical data. It supports a high degree of
customization without requiring look-and-feel enhancements.
javax.swing.undo
The undo package contains support for implementing and managing undo/redo
functionality.

Frames and panels overview


JFrame
class javax.swing.JFrame
The main container for a Swing-based application is JFrame. All objects associated
with a JFrame are managed by its only child, an instance of JRootPane. JRootPane
is a simple container for several child panes. When we add components to a JFrame
we don’t directly add them to the JFrame as we did with an AWT Frame. Instead we
have to specify exactly which pane of the JFrame’s JRootPane we want the
component to be placed in. In most cases components are added to the contentPane
by calling:
myJFrame.getContentPane().add(myComponent);
Similarly when setting a layout for a JFrame’s contents we usually just want to set
the layout for the contentPane:
myJFrame.getContentPane().setLayout(new FlowLayout());
Each JFrame contains a JRootPane as protected field rootPane. Figure 3.1
illustrates the hierarchy of a JFrame and its JRootPane. The lines in this diagram
extend downward representing the “has a” relationship of each container. We will
see JFrame in action soon enough.

JRootPane
class javax.swing.JRootPane
Each JRootPane contains several components referred to here by variable name:

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 74
glassPane (a JPanel by default), layeredPane (a JLayeredPanel), contentPane (a
JPanel by default) and menuBar (a JMenuBar).
Note: GlassPane and contentPane are just variable names used by JRootPane. They
are not unique Swing classes, as some explanations might lead you to believe.

The glassPane is initialized as a non-opaque JPanel that sits on top of the


JLayeredPane as illustrated in Figure 3.3. This component is very useful in
situations where we need to intercept mouse events to display a certain cursor over
the whole frame or redirect the current application focus. The glassPane can be any
component but is a JPanel by default. To change the glassPane from a JPanel to
another component a call to the setGlassPane() method must be made:
setGlassPane(myComponent);
Though the glassPane does sit on top of the layeredPane it is, by default, not visible.
It can be set visible (i.e. show itself) by calling:
getGlassPane().setVisible(true);
The glassPane allows you to display components in front of an existing JFrame‘s
contents.

The menuBar does not exist by default but can be set by calling the
setJMenuBar() method:
JMenuBar menu = new JMenuBar();
setJMenuBar(menu);

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 75
When the JMenuBar is set it is automatically positioned at the top of the
FRAME_CONTENT_LAYER.
The contentPane is, by default, an opaque JPanel. It can be set to any other
component by calling:
setContentPane(myComponent);
Note: The default layout for the contentPane is BorderLayout. The default layout for
any other JPanel is FlowLayout. Be careful not to set the layout of a JFrame
directly. This will generate an exception. Setting the layout of the rootPane is also
something that should be avoided because every JRootPane uses its own custom
layout manager called RootLayout.

RootLayout
class javax.swing.JRootPane.RootLayout
RootLayout is a layout manager built specifically to manage JRootPane’s
layeredPane, glassPane, and menuBar. If it is replaced by another layout manager
that manager must be able to handle the positioning of these components.
RootLayout is an inner class defined within JRootPane and as such, is not intended
to have any use outside of this class. Thus it is not discussed in this text.
The RootPaneContainer interface
abstract interface javax.swing.RootPaneContainer
The purpose of the RootPaneContainer interface is to organize a group of methods
that should be used to access a container’s JRootPane and its different panes (see
API docs). Because JFrame‘s main container is a JRootPane, it implements this
interface (as does JFrame and JDialog). If we were to build a new component which
uses a JRootPane as its main container we would most likely implement the
RootPaneContainer interface. (Note that this interface exists for convenience,
consistency, and organizational purposes. We are encouraged to, but certainly not
required to, use it in our own container implementations.)
The WindowConstants interface
abstract interface javax.swing.WindowConstants
We can specify how a JFrame, JInternalFrame, or JDialog acts in response to the
user closing it through use of the setDefaultCloseOperation() method. There are
three possible settings, as defined by WindowConstants interface fields:
WindowConstants.DISPOSE_ON_CLOSE
WindowConstants.DO_NOTHING_ON_CLOSE
WindowConstants.HIDE_ON_CLOSE
The names are self-explanatory. DISPOSE_ON_CLOSE disposes of the JFrame and
its contents, DO_NOTHING_ON_CLOSE renders the close button useless, and
HIDE_ON_CLOSE just removes the container from view. (HIDE_ON_CLOSE may be
useful if we may need the conatiner, or something it contains, at a later time but do
not want it to be visible until then. DO_NOTHING_ON_CLOSE is very useful as you
will see below.)
The WindowListener interface
abstract interface java.awt.event.WindowListener
Classes that want explicit notification of window events (such as window closing,
iconification, etc.) need to implement this interface. Normally the WindowAdapter

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 76
class is extended instead. “When the window's status changes by virtue of being
opened, closed, activated or deactivated, iconified or deiconified, the relevant
method in the listener object is invoked, and the WindowEvent is passed to it.”API
The methods any implementation of this interface must define are:
void windowActivated(WindowEvent e)
void windowClosed(WindowEvent e)
void windowClosing(WindowEvent e)
void windowDeactivated(WindowEvent e)
void windowDeiconified(WindowEvent e)
void windowIconified(WindowEvent e)
void windowOpened(WindowEvent e)

WindowEvent
class java.awt.event.WindowEvent
The type of event used to indicate that a window has changed state. This
event is passed to every WindowListener or WindowAdapter object which is
registered on the source window to receive such events. Method getWindow()
returns the window that generated the event. Method paramString() retreives a
String describing the event type and its source, among other things.
There are six types of WindowEvents that can be generated; each is
represented by the following static WindowEvent fields: WINDOW_ACTIVATED,
WINDOW_CLOSED, WINDOW_CLOSING, WINDOW_DEACTIVATED,
WINDOW_DEICONIFIED, WINDOW_ICONIFIED, WINDOW_OPENED.

WindowAdapter
abstract class java.awt.event.WindowAdapter
This is an abstract implementation of the WindowListener interface. It is
normally more convenient to extend this class than to implement WindowListener
directly. Notice that none of the WindowConstants close operations actually
terminate program execution. This can be accomplished by extending
WindowAdapter and overriding the methods we are interested in handling (in this
case just the windowClosed() method). We can create an instance of this extended
class, cast it to a WindowListener object, and register this listener with the JFrame
using the addWindowListener() method. This can easily be added to any application
as follows:
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
myJFrame.addWindowListener(l);
The best method of all is to combine WindowAdapter and values from the
WindowConstants interface to present the user with an exit confirmation dialog as
follows:
myJFrame.setDefaultCloseOperation(
WindowConstants.DO_NOTHING_ON_CLOSE);

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 77
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Advanced Java Programming 47
Ramesh Ramesh
int confirm = JOptionPane.showOptionDialog(myJFrame,
"Really Exit?", "Exit Confirmation",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, null, null);
if (confirm == 0) {
myJFrame.dispose();
System.exit(0);
}
}
};
myJFrame.addWindowListener(l);

Note: This can also be done for JDialog. However, to do the same thing for a
JInternalFrame we must build a custom JInternalFrame subclass and implement
the PropertyChangeListener interface.

Inserting this code into your application will always display the dialog shown in
figure 3.4 when the JFrame close button is pressed. Note that this functionality is
not used until later chapters in which we work with applications where closing may
cause a loss of unsaved material.

Custom frame icons


Often we want to use a custom icon to represent our application frame. Because
JFrame is a subclass of awt.Frame we can set its icon using the setIconImage()
method. This method is intended to set the minimized icon to use for this frame.
On some platforms this icon is also used for a title bar image (e.g. Windows).
ImageIcon image = new ImageIcon("spiral.gif");
myFrame.setIconImage(image.getImage());
There is no limit to the size of the icon that can be used. A JFrame will resize any
image passed to setIconImage() to fit the bound it needs. Figure 3.5 shows the top of
a JFrame with a custom icon.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 78
Centering a frame on the screen
By default a JFrame displays itself in the upper left-hand corner of the screen.
Often it is desirable to place it in the center of the screen. Using the getToolkit()
method of the Window class (of which JFrame is a second level subclass), we can
communicate with the operating system and query the size of the screen. (The
Toolkit methods make up the bridge between Java components and their native,
operating-system-specific, peer components.)
The getScreenSize() method gives us the information we need:
Dimension dim = getToolkit().getScreenSize();

When setting the location of the JFrame, the upper left hand corner of the frame is
the relevant coordinate. So to center a JFrame on the screen we need to subtract
half its width and half its height from the center-of-screen coordinate:
myJFrame.setLocation(dim.width/2 - myJFrame.getWidth()/2,
dim.height/2 - myJFrame.getHeight()/2);
JApplet
class javax.swing.JApplet
JApplet is the Swing equivalent of the AWT Applet class. Like JFrame, JApplet’s
main child component is a JRootPane and its structure is the same. JApplet acts
just like Applet and we will not go into detail about how applets work.

JWindow
class javax.swing.JWindow
JWindow is very similar to JFrame except that it has no title bar, and is not
resizable, minimizable, maximizable, or closable. Thus it cannot be dragged without
writing custom code to do so (e.g. JToolBar’s UI delegate provides this functionality
for docking and undocking). We normally use JWindow to display a temporary
message or splash screen logo. Since JWindow is a RootPaneContainer, we can
treat it just like JFrame or JApplet when manipulating its contents.

Content pane: The content pane is associated with frame. The content pane is the
container that contains the components which resides in the frame. Components
should be added to a frame through content pane and not directly to the frame
itself. getContentPane( ) method of JFrame returns an object of Container class as
follows :
Container c = getContentPane( ) ;

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 79
JLabel: - Jlabel is used to display some message to the user. Jlabel does not
generate any events. The label can be aligned in different ways like left, right,
center etc.
SetToolTipText(String message) method is from Jcomponent class. All the
subclasses of Jcomponent class can make use of this method. That is, Jbutton,
JtextField etc., can make of this method. The message isdisplayed when we take
the mouse cursor over the label.
ImageIcon ic1=new ImageIcon(“Duke.gif”)
ImageIcon is a subclass of Icon. Both belong to javax.swing package. An icon can
be added to the label and if added the icon is displayed to the left of the label.
Lab3.setHorizontalTextPosition(SwingConstants.CENTER)
Lab3.setVerticalTextPosition(SwingConstants.BOTTOM)
SwingConstants is an interface from javax.swing package that includes many
constants with which we can set the alignment of components. The first statement
sets the horizontal alignment and the second statement sets the vertical alignment
of the label in the frame.

JTextField and JPasswordField:


JTextField and JPasswordField (pacakage javax.swing) are used to take
keyboard input from the user or a programmer can display some text to the user.
The limitation is we can enter or display the text in a single line only, but of any
length. The text entered in JPasswordField is by default is shown in asterisk form
which can be changed at our need. After entering the text, when we press enter key,
an event by name ActionEvent is generated.
example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class textandpass extends JFrame implements ActionListener
{
JTextField tf1,tf2,tf3;
JPasswordField pf;
public textandpass()
{
super("Learining text and password fields");
Container c=getContentPane();
c.setLayout(new FlowLayout());
tf1=new JTextField(15);
c.add(tf1);
tf2=new JTextField("Hello World");
c.add(tf2);
tf3=new JTextField("Y.Ramesh Kumar",25);
tf3.setEditable(false);
c.add(tf3);
pf=new JPasswordField(10);
c.add(pf);

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 80
tf1.addActionListener(this);
tf2.addActionListener(this);
tf3.addActionListener(this);
pf.addActionListener(this);
addWindowListener(new WindowAdapter( )
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setSize(350,200);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String str=e.getActionCommand();
String s1=" ";
JTextField tf=(JTextField)e.getSource();
if(tf==tf1)
s1="tf1: "+str;
else
if(tf==tf2)
s1="tf2: "+str;
else
if(tf==tf3)
s1="tf3: "+str;
else
if(e.getSource()==pf)
s1="Password: ="+str;
JOptionPane.showMessageDialog(null,s1,"I Display what u enter
",JOptionPane.PLAIN_MESSAGE);
}
public static void main(String arg[])
{
new textandpass();
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 81
JCheckBox:
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class jcheck extends JFrame implements ItemListener
{
JTextField tf;
JCheckBox jc1,jc2,jc3;
public jcheck()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
tf=new JTextField("J2EE or JAVA, which will be popular",30);
c.add(tf);
jc1=new JCheckBox("Monospeed");
jc2=new JCheckBox("Bold");
jc3=new JCheckBox("Italic");
c.add(jc1);
c.add(jc2);
c.add(jc3);
jc1.addItemListener(this);
jc2.addItemListener(this);
jc3.addItemListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setTitle("Learing JCheckbox");
setSize(400,200);
setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
String fname=" ";
int b=0,i=0;
if(jc1.isSelected())
fname="Monospaced";
else
fname="Serif";
if(jc2.isSelected())
b=Font.BOLD;
else

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 82
b=Font.PLAIN;
if(jc3.isSelected())
i=Font.ITALIC;
else
i=Font.PLAIN;
Font f=new Font(fname,b+i,15);
tf.setFont(f);
}
public static void main(String arg[])
{
new jcheck();
}
}

JRadioButton: Radio Buttons(defined with class JRadioButton) are similar to


check boxes in that they have two states – selected and not selected (also called
deselected). RadioButtons appear as a group in which only one radio button can be
selected at a time. Selecting a different radio button in the group automatically
forces the other radio button in the group to get deselected. Radio buttons are used
to represent a set of mutually exclusive options (i.e., multiple positions in the group
would not be selected at the same time). The logically relationship between radio
buttons is maintained by a ButtonGroup object(package javax.swing). The
ButtonGroup object itself is not a GUI component. Therefore, a ButtonGroup object
is not displayed in a user interface. JRadioButton objects from the group are
displayed in the GUI.
A JRadioButton is different from a JCheckBox in that there are normally
several JRadioButtons that are grouped together and only one of the JRadioButtons
in the group can be selected (true) at any time.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class radiobutton extends JFrame implements ItemListener
{
String s="";
JTextField t;

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 83
JRadioButton r1,r2,r3,r4;
ButtonGroup bg;
public radiobutton()
{
super(" RadioButton test ");
Container c=getContentPane();
c.setLayout(new FlowLayout());
t=new JTextField(" ramesh and vandana ",25);
c.add(t);
r1=new JRadioButton("Plain",true);
r2=new JRadioButton("Bold",false);
r3=new JRadioButton("Italic",false);
r4=new JRadioButton("Bold/Italic",false);
c.add(r1);
c.add(r2);
c.add(r3);
c.add(r4);
r1.addItemListener(this);
r2.addItemListener(this);
r3.addItemListener(this);
r4.addItemListener(this);
bg=new ButtonGroup();
bg.add(r1);
bg.add(r2);
bg.add(r3);
bg.add(r4);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setSize(300,100);
show();
}
public void itemStateChanged(ItemEvent e)
{
if(e.getSource()==r1)
t.setFont(new Font("Times New Roman",Font.PLAIN,14));
else
if(e.getSource()==r2)
t.setFont(new Font("Times New Roman",Font.BOLD,14));
else
if(e.getSource()==r3)
t.setFont(new Font("Times New Roman",Font.ITALIC,14));

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 84
else
if(e.getSource()==r4)
t.setFont(new Font("Times New
Roman",Font.BOLD+Font.ITALIC,14));
t.repaint();
}
public static void main(String arg[])
{
new radiobutton();
}
}

JComboBox: A combo box (sometimes called a drop-down list) provides a list of


items from which the user can make selection. Combo boxes are implemented with
class JComboBox, which inherits from class Jcomponent. JComboBoxes generate
Item Events like JCheckBoxes and JRadioButtons. This is similar to AWT Choice
component.

JList:
A list displays a series of items from which the user may select one or more items.
Lists are created with class JList, which inherits from class JComponent. Class
JList supports both single-selection lists (i.e., lists that allows only one item to be
selected at a time) and multiple-selection lists(lists that allow any number of items
to be selected
Single-selection Lists:
In Single-selection list, we can select one item only. The difference with combobox
is that the list displays scrollbars.
Example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
public class jlist extends JFrame implements ListSelectionListener
{
JList co;
Container c;
public jlist()
{
c=getContentPane();
c.setLayout(new FlowLayout());

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 85
String names[]={"Red","Green","Blue","Cyan","Magenta","Yellow"};
co=new JList(names);
co.setVisibleRowCount(5);
co.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
c.add(co);
c.add(new JScrollPane(co));
co.addListSelectionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setTitle("Practicing JList");
setSize(300,300);
setVisible(true);
}
public void valueChanged(ListSelectionEvent e)
{
String str=(String)co.getSelectedValue();
if(str.equals("Red"))
c.setBackground(Color.red);
else
if(str.equals("Green"))
c.setBackground(Color.green);
else
if(str.equals("Blue"))
c.setBackground(Color.blue);
else
if(str.equals("Cyan"))
c.setBackground(Color.cyan);
else
if(str.equals("Magenta"))
c.setBackground(Color.magenta);
else
if(str.equals("Yellow"))
c.setBackground(Color.yellow);
}
public static void main(String arg[])
{
new jlist();
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 86

ListSelectionListener is an interface defined in javax.swing package used with Jlist.


It includes only one abstract method valueChanged(ListSelectionEvent e) which
must be given a body in our class with the even-handling code.

Multiple-Selection List:
A multiple-selection list enables the user to select many items from a Jlist. A
SINGLE_INTERVAL_SELECTION list allows selection of a contiguous range of items
in the list by clicking the first item while holding shift key, then clicking the last
item to select in the range (while holding shift key). A
MULTIPLE_INTERVAL_SELECTION list allows continuous range selection described
for a SINGLE_INTERVAL_SELECTION list and allows miscellaneous items to be
selected by holding the Ctrl key while clicking each item to select. To deselect an
item, hold the Ctrl key while clicking the item a second time.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
public class jmlist extends JFrame implements ListSelectionListener
{
JList p;
public jmlist()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
String names[]={"Banglore","Hyderabad","Ooty","Chennai","Mumbai",
"Delhi","Kochi","Darjeeling"};
p=new JList(names);
p.setVisibleRowCount(5);
p.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
c.add(new JScrollPane(p));
p.addListSelectionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 87
System.exit(0);
}
});
setTitle("Practicing Mulitple selection JList ");
setSize(300,300);
setVisible(true);
}
public void valueChanged(ListSelectionEvent e)
{
String s1=" ";
Object obj[]=p.getSelectedValues();
for(int i=0;i<obj.length;i++)
s1+=(String)obj[i];
JOptionPane.showMessageDialog(null,"you go: "+s1,"Learning Multiple
Selections",JOptionPane.PLAIN_MESSAGE);
}
public static void main(String arg[])
{
new jmlist();
}
}

JTextArea:-
The limitation of JTextField is that we can enter or display the text in one line only.
The limitation is overcome with JtextArea. In JtextArea, we can enter or display and
number of lines of text. We can make a text area not to be used by the user by
using setEditable(false) method
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class jtextarea extends JFrame implements ActionListener
{
JButton b1;
JTextArea tf;

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 88
public jtextarea()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
String s="greeting from the authors \n "+"ramesh & vandana \n"
+"sridhar & siva ranjani \n" + " kiran & sai ";
b1=new JButton(" Display ");
tf=new JTextArea(s,10,30);
c.add(tf);
c.add(b1);
b1.addActionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setTitle(" Learning JTextArea ");
setSize(400,300);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String s1=tf.getSelectedText();
JOptionPane.showMessageDialog(null,s1,"Practcing
JTextArea",JOptionPane.PLAIN_MESSAGE);
}
public static void main(String arg[])
{
new jtextarea();
}
}

JSlider:
JSlider enable the user to select from a range of integer values. Class JSlider
inherits from JComponent. The following figure creates a horizontal JSlider with
tick marks and the thumb that allows the user to select a value.

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 89
JSlider can be customized so that they can display major tick marks, minor tick
marks and labels for the tick marks. They also support snap-to-ticks where
positioning the thumb between two tick marks causes the thumb to snap to the
closest tick mark.
Most Swing GUI components support user interactions through the mouse and the
keyboard. JSliders have either a horizontal orientation or a vertical orientation.
For a horizontal JSlider, the minimum value is at the extreme left and the
maximum value is at the extreme right of the JSlider. For a vertical JSlider, the
minimum value is at the extreme bottom and the maximum value is at the extreme
top of the JSlider. The relative position of the thumb indicates the current value of
the JSlider.
In the following program, slider is used to change its value when the slider thumb is
dragged. The slider is set to a minimum value 0 and to a maximum value 255.
These values are used as the green component in making a color object. This color
object is applied as a background color to the canvas. Canvas is a component on
which we can do a free-hand writing or painting as in paint of accessories in
Windows. Whenever, the slider is moved, the background color of the canvas is
changed.
We used a swing listener, ChangeListener to handle the slider events. It defines
one abstract method stateChagned(Change Event e) which we must override in our
program.
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class jslider extends JFrame implements ChangeListener
{
Canvas cvas;
JSlider js;
public jslider()
{
Container c=getContentPane();
cvas=new Canvas();
js=new JSlider(SwingConstants.HORIZONTAL,0,255,17);
c.add(cvas,"Center");
c.add(js,"South");
js.setMajorTickSpacing(10);
js.setPaintTicks(true);
js.addChangeListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 90
});
setTitle(" Learing JTestArea ");
setSize(400,300);
setVisible(true);
}
public void stateChanged(ChangeEvent e)
{
int value=js.getValue();
Color clr=new Color(200,value,100);
cvas.setBackground(clr);
cvas.repaint();
}
public static void main(String arg[])
{
new jslider();
}
}

JMenu:
Steps in total menu creation:
1. create a menu bar (e.g JmenuBar mb=new JmenuBar())
2. add menu bar to the frame (e.g. setJMenuBar(mb))
3. create menus (e.g. Jmenu file=new Jmenu(“File”))
4. add items to each menu (e.g file.add(new JmenuItem(“Open”))
5. add each menu to menu (e.g mb.add(file))
6. add the menubar to the frame (e.g. setJMenuBar(mb))
The character “-“ separates menu items. You may also use the addSeparator()
method to separate menu items.
f1.addSeparator( )

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 91
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class menu3 extends JFrame
{
Color c[]={Color.black,Color.blue,Color.red,Color.green};
JRadioButtonMenuItem citems[],fonts[];
JCheckBoxMenuItem sitems[];
JLabel d;
ButtonGroup fgroup,cgroup;
int style;
public menu3()
{
super(" Using JMenus ");
JMenuBar jm=new JMenuBar();
setJMenuBar(jm);
JMenu fm=new JMenu("File");
fm.setMnemonic('F');
JMenuItem aitem=new JMenuItem("About......");
aitem.setMnemonic('A');
aitem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null,"This is an example
\n of using menus","About",JOptionPane.PLAIN_MESSAGE);
}
});
fm.add(aitem);
JMenuItem eitem=new JMenuItem(" Exit ");
eitem.setMnemonic('x');
eitem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
fm.add(eitem);
jm.add(fm);
JMenu formatMenu=new JMenu("Format");
formatMenu.setMnemonic('r');
String cols[]={"Black","Blue","Red","Green"};
JMenu cmenu=new JMenu("Color");
cmenu.setMnemonic('C');
citems=new JRadioButtonMenuItem[cols.length];

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 92
cgroup=new ButtonGroup();
ItemHandler ih=new ItemHandler();
for(int i=0;i<cols.length;i++)
{
citems[i]=new JRadioButtonMenuItem(cols[i]);
cmenu.add(citems[i]);
cgroup.add(citems[i]);
citems[i].addActionListener(ih);
}
citems[0].setSelected(true);
formatMenu.add(cmenu);
formatMenu.addSeparator();
String fnames[]={"TimesRoman","Courier","Helvetica"};
JMenu fontmenu=new JMenu("Font");
fontmenu.setMnemonic('n');
fonts=new JRadioButtonMenuItem[fnames.length];
fgroup=new ButtonGroup();
for(int i=0;i<fonts.length;i++)
{
fonts[i]=new JRadioButtonMenuItem(fnames[i]);
fontmenu.add(fonts[i]);
fgroup.add(fonts[i]);
fonts[i].addActionListener(ih);
}
fonts[0].setSelected(true);
fontmenu.addSeparator();
String snames[]={"Bold","Italic"};
sitems=new JCheckBoxMenuItem[snames.length];
StyleHandler sh=new StyleHandler();
for(int i=0;i<snames.length;i++)
{
sitems[i]=new JCheckBoxMenuItem(snames[i]);
fontmenu.add(sitems[i]);
sitems[i].addItemListener(sh);
}
formatMenu.add(fontmenu);
jm.add(formatMenu);
d=new JLab el("Ramesh & Vandana",SwingConstants.CENTER);
d.setForeground(c[0]);
d.setFont(new Font("TimesRoman",Font.PLAIN,52));
getContentPane().setBackground(Color.cyan);
getContentPane().add(d,BorderLayout.CENTER);
setSize(500,200);
show();
}
public static void main(String arg[])

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 93
{
menu3 k=new menu3();
k.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
class ItemHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
for(int i=0;i<citems.length;i++)
if(citems[i].isSelected())
{
d.setForeground(c[i]);
break;
}
for(int i=0;i<fonts.length;i++)
if(e.getSource()==fonts[i])
{
d.setFont(new Font(fonts[i].getText(),style,72));
break;
}
repaint();
}
}
class StyleHandler implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
style=0;
if(sitems[0].isSelected())
style+=Font.BOLD;
if(sitems[1].isSelected())
style+=Font.ITALIC;
d.setFont(new Font(d.getFont().getName(),style,72));
repaint();
}
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 94

JPopupMenus:
Many computer applications provide so-called context-sensitive popup menus. In
Swing, such menus are created with class JPopupMenu (a subclass of
JComponent). These menus provide options that are specific to the component for
which the popup trigger event was generated. On most systems, the popup trigger
event occurs when the user presses and releases the right mouse button. A popup
menu appears anywhere on the screen when a right mouse button is clicked. A
popup menu appears anywhere on the screen when a right mouse button is clicked.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
public class PopupMenuDemo extends JApplet
{
private JPopupMenu popup = new JPopupMenu( ) ;
public void init( )
{
Container cp = getContentPane( ) ;
popup.add( new JMenuItem( "undo" ) ) ;
popup.add( new JMenuItem( "redo" ) ) ;
popup.addSeparator( ) ;
popup.add( new JMenuItem( "cut" ) ) ;
popup.add( new JMenuItem( "copy" ) ) ;
popup.add( new JMenuItem( "paste" ) ) ;
cp.addMouseListener( new MouseAdapter( )
{
public void mouseReleased(MouseEvent e )

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 95
{
showPopup( e ) ;
}});
}
void showPopup( MouseEvent e )
{
if( e.isPopupTrigger( ) )
popup.show( e.getComponent( ), e.getX( ), e.getY( ) ) ;
}
}

JTabbedPane:
Tabbed pane is a common user interface component that provide an easy access to
more than one panel( like cardlayout manager ). Each tab is associated with a
single component that will be displayed when the tab is selected.
In the following program, three tabs are added to the tabbed pane. 3 classes are
made for each tab.
import java.awt.*;
import javax.swing.*;
public class TabbedPaneDemo extends JApplet
{
public void init( )
{
JTabbedPane jt = new JTabbedPane( ) ;
jt.add( "Colors", new CPanel( ) ) ;
jt.add( "Fruits", new FPanel( ) ) ;
jt.add( "Vitamins", new VPanel( ) ) ;
getContentPane( ).add( jt );
}
}
class CPanel extends JPanel
{
public CPanel( )
{
JCheckBox cb1 = new JCheckBox( "Red" ) ;
JCheckBox cb2 = new JCheckBox( "Green" ) ;
JCheckBox cb3 = new JCheckBox( "Blue" ) ;
add(cb1) ; add(cb2) ; add(cb3) ;
}
}
class FPanel extends JPanel
{
public FPanel( )
{
JComboBox cb = new JComboBox( ) ;
cb.addItem( "Apple" ) ;

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 96
cb.addItem( "Mango" ) ;
cb.addItem( "Pineapple" ) ;
add(cb) ;
}
}
class VPanel extends JPanel
{
public VPanel( )
{
JButton b1 = new JButton( "Vit-A" ) ;
JButton b2 = new JButton( "Vit-B" ) ;
JButton b3 = new JButton( "Vit-C" ) ;
add( b1 ) ; add( b2 ) ; add( b3 ) ;
}
}

JScrollPane:
JScrollPane scrolls to view its contents. Scrollbars are used to scroll the view
horizontally and vertically.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class ScrollPaneDemo extends JApplet
{
public void init( )
{
Container cp = getContentPane();
cp.setLayout( new BorderLayout( ) ) ;
JPanel jp = new JPanel( ) ;
jp.setLayout( new GridLayout( 20, 20 ) ) ;
for( int i = 0 ; i < 20 ; i + + )
for( int j = 0 ; j < 20 ; j + + )
jp.add( new JButton( "Button " + j ) ) ;
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED ;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ;

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 97
JScrollPane js = new JScrollPane( jp, v, h ) ;
cp.add( js, BorderLayout.CENTER ) ;
}
}

JColorChooser:
JColorChooser class provides a pane of controls designed to allow a user to
manipulate and select a color.
import javax.swing. * ;
import java.awt. * ;
import java.awt.event. * ;
public class ColorChooser extends JFrame
{
public ColorChooser( )
{
setTitle("Jcolorchooser Example");
JColorChooser jcc = new JColorChooser( ) ;
JPanel content = ( JPanel ) getContentPane();
content.setLayout(new BorderLayout());
content.add( jcc, "Center" ) ;
addWindowListener( new WindowAdapter( )
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 ) ;
}});
}
public static void main( String args[] )
{
JFrame jf = new JFrame( "Choose the Best Shade" ) ;
ColorChooser cc = new ColorChooser( ) ;
cc.setVisible(true);
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 98
JProgressMonitor: ProgressMonitor monitors the progress of the operation.
Displays in percentage of completion of the operation.
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.* ;
public class ProgressiveTest
{
public static void main ( String args[ ] )
{
JFrame frame = new JFrame( "Swing’s ProgressMonitor” ) ;
JButton button = new JButton( "Start Iteration" ) ;
frame.getContentPane().add( button, BorderLayout.CENTER );
int min = 0 ; int max = 100 ;
String[ ] message = new String[ 2 ] ;
message[ 0 ] = "Performing Iterations." ;
message[ 1 ] = "Wait for completion……." ;
final ProgressMonitor monitor = new ProgressMonitor(frame,
message,"Iteration", min, max ) ;
final Runnable runnable = new Runnable( )
{
public void run( )
{
int sleepTime = 500 ;
for( int i = 1 ; i < 100 ; i + + )
{
try
{
monitor.setNote( "Iteration " + i ) ;
monitor.setProgress( i ) ;
if ( monitor.isCanceled( ) )
{
monitor.setProgress( 100 ) ;
break ;
}
Thread.sleep( sleepTime ) ;
}
catch ( InterruptedException e ) { }
}
monitor.close( ) ;
}
};
button.addActionListener( new ActionListener( )
{
public void actionPerformed( ActionEvent event )
{
// run the iterations in a separate thread

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 99
Thread thread = new Thread( runnable );
thread .start( ) ;
}});
frame.pack( ) ;
frame.setVisible( true ) ;
frame.addWindowListener( new WindowAdapter( )
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 ) ;
}})
}
}

JTrees
Tree is a swing component that can be used to display a hierarchy of data like
Window Explorer.
DefaultMutableTreeNode class is used to create a node.
TreePath getPathForLocation( int x, int y ) returns the path of the node
clicked.
import java.awt.*;
import java.awt.event.* ;
import javax.swing.* ;
import java.util.* ;
import javax.swing.tree.* ; // for DefaultMutableTreeNode and JTree
// import java.applet.* ; not required as Japplet extends Applet
public class JTreeDemo extends JApplet
{
JTree jt ; JTextField jtf ;
public void init( )
{
Container c = getContentPane( ) ;
c.setLayout( new BorderLayout( ) ) ;
// this is the root node and top in the hierarchy
DefaultMutableTreeNode rootnode = new DefaultMutableTreeNode(" Sports ") ;
DefaultMutableTreeNode anode = new DefaultMutableTreeNode( " Air games " ) ;
rootnode.add( anode ) ; // becomes a file to rootnode
// create ogames node add to the rootnode(becomes child node of rootnode )
DefaultMutableTreeNode ogames = new DefaultMutableTreeNode( " OutDoor
Games ") ;
DefaultMutableTreeNode bnode = new DefaultMutableTreeNode( " Basket ball " ) ;
DefaultMutableTreeNode vnode = new DefaultMutableTreeNode( " Volley ball " ) ;
ogames.add( bnode ) ; // becomes file to ogames
ogames.add( vnode ) ; // becomes file to ogames
rootnode.add( ogames ) ; // add ogames to rootnode
// create igames node add to the rootnode(becomes child node of rootnode )

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 100
DefaultMutableTreeNode igames =new DefaultMutableTreeNode( "Indoor Games " ) ;
DefaultMutableTreeNode cnode = new DefaultMutableTreeNode( " Carroms " ) ;
DefaultMutableTreeNode tnode = new DefaultMutableTreeNode( " Table Tennis " ) ;
igames.add( cnode ) ; // becomes file to igames
igames.add( tnode ) ; // becomes file to igames
rootnode.add( igames ) ; // add igames to rootnode
// this node becomes child node to igames
DefaultMutableTreeNode snode = new DefaultMutableTreeNode( " Skill Games " ) ;
DefaultMutableTreeNode shnode = new DefaultMutableTreeNode( " Shooting " ) ;
DefaultMutableTreeNode banode = new DefaultMutableTreeNode("Bar Dancing ") ;
snode.add( banode ) ; // becomes a file to snode
igames.add( snode ) ; // becomes a file to snode
snode.add( shnode ) ; // snode is the child node to igames
jt = new JTree( rootnode ) ; // add root node to the JTree
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED ;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ;
JScrollPane jsp = new JScrollPane( jt , v , h ) ;
c.add( jsp , "Center " ) ; // add scroll pane to the container
jtf = new JTextField( 20 ) ;
c.add( jtf , " South " ) ;
jt.addMouseListener( new MouseAdapter( )
{
public void mouseClicked( MouseEvent e )
{
display( e ) ;
}});
}
public void display( MouseEvent e )
{
TreePath tp = jt.getPathForLocation( e.getX( ) , e.getY( ) ) ;
if( tp ! = null )
jtf.setText( tp.toString( ) ) ;
else
jtf.setText( " " ) ;
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 101

JTables
Table displays data in horizontal and vertical columns. A table can be resized or
moved. We create a table and add it to a scroll pane. Scroll pane is added to the
container.
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.* ;
public class JTableDemo extends JApplet
{
public void init( )
{
Container c = getContentPane( ) ;
c.setLayout( new BorderLayout( ) ) ;
String fields [ ] = { " empid ", " empname ", " empsal " } ;
Object details [ ] [ ] = { { " 1 " , " S N Rao " , " 4500.50 " } ,
{ " 2 " , " S umathi " , " 4567.50 " } ,
{ " 3 " , " Sridhar " , " 2246.30 " } ,
{ " 4 " , " Jyothi " , " 3245.75 " } ,
{ " 5 " , " Jyostna " , " 2500.25 " } } ;
JTable jt = new JTable( details , fields ) ;
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED ; // if the
rows are more than
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED ; //
height of the applet,
JScrollPane jsp = new JScrollPane( jt , v , h ) ; // scroll bar is added
c.add( jsp , " Center " ) ;
}
}

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology


Object Oriented Programming 102

Y. Ramesh Kumar, HOD of CSE, Avanthi Institute of Engg. & Technology

You might also like