CS3391-Object Oriented Programming PRIMARY
CS3391-Object Oriented Programming PRIMARY
Unit – III
Exception Handling and I/O
An exception (or exceptional event) is a problem that arises during the execution of a
program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended,
therefore, these exceptions are to be handled.
If an exception is raised, which has not been handled by programmer then program
execution can get terminated and system prints a non user friendly error message.
A network connection has been lost in the middle of communications or the JVM
1. try A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code.
Uncaught Exceptions
This small program includes an expression that intentionally causes a divide-by- zero error: class
Exc0 { public static void main(String args[]) { int d = 0; int a =42 / d; } } When the Java run-time
system detects the attempt to divide by zero, it constructs a new exception object and then throws
this exception. This causes the execution of Exc0 to stop, because once an exception has been
thrown, it must be caught by an exception handler and dealt with immediately
Any exception that is not caught by your program will ultimately be processed by the default
handler. The default handler displays a string describing the exception, prints a stack trace from
the point at which the exception occurred, and terminates the program. Here is the exception
generated when this example is executed:
java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)
Stack Trace:
Stack Trace is a list of method calls from the point when the application was started to the point
where the exception was thrown. The most recent method calls are at the top. A stacktrace is a
very helpful debugging tool. It is a list of the method calls that the application was in the middle
of when an Exception was thrown. This is very useful because it doesn't only show you
where the error happened, but also how the program ended up in that place of the code.
Using try and Catch
To guard against and handle a run-time error, simply enclose the code that you want to monitor
inside a try block. Immediately following the try block, include a catch clause that specifies the
exception type that you wish to catch. A try and its catch statement form a unit. The the following
program includes a try block and a catch clause that processes the ArithmeticException generated
by the division-by-zero error:
class Exc2 {
public static void main(String args[]) { int d, a;
try { // monitor a block of code. d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
This program generates the following output:
Division by zero.
After catch statement.
The call to println( ) inside the try block is never executed. Once an exception is thrown, program
control transfers out of the try block into the catch block.
catch(ArrayIndexOutOfBoundsException e) {
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
Primitive types, such as int or char, as well as non-Throwable classes, such as String and
Object, cannot be used as exceptions. There are two ways you can obtain a Throwable object:
using a parameter in a catch clause, or creating one with the new operator.
The flow of execution stops immediately after the throw statement; any subsequent statements are
not executed. The nearest enclosing try block is inspected to see if it has a catch statement that
matches the type of exception. If it does find a match, control is transferred to that statement. If
not, then the next enclosing try statement is inspected, and so on. If no matching catch is found,
then the default exception handler halts the program and prints the stack trace
// Demonstrate throw. class
ThrowDemo { static void
demoproc() { try {
throw new NullPointerException("demo");
} catch(NullPointerException e)
{ System.out.println("Caught inside demoproc."); throw e; //
rethrow the exception
}
}
public static void main(String args[]) { try {
demoproc();
} catch(NullPointerException e) { System.out.println("Recaught: " +
e);
}
}
}
class ThrowsDemo {
static void throwOne() throws IllegalAccessException { System.out.println("Inside
throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) { try {
throwOne();
} catch (IllegalAccessException e) {
finally
The finally keyword is designed to address this contingency. finally creates a block of code that will be
executed after a try/catch block has completed and before the code following the try/catch block. The
finally block will execute whether or not an exception is thrown. If an exception is
If an exception is thrown, the finally block will execute even if no catch statement matches the
exception. Any time a method is about to return to the caller from inside a try/catch block, via an
uncaught exception or an explicit return statement, the finally clause is also executed just before
the method returns. This can be useful for closing file handles and freeing up any other resources
that might have been allocated at the beginning of a method with the intent of disposing of them
before returning. The finally clause is optional.
// Demonstrate finally. class
FinallyDemo {
// Through an exception out of the method. static
void procA() {
try {
System.out.println("inside procA"); throw
new
System.out.println("procA's finally");
}
}
// Return from within a try block. static void
procB() {
try {
System.out.println("inside procB"); return;
} finally { System.out.println("procB's
finally");
}
}
// Execute a try block normally. static
void procC() {
try {
System.out.println("inside procC");
} finally { System.out.println("procC's
finally");
}
}
public static void main(String args[]) { try {
procA();
} catch (Exception e)
{ System.out.println("Exception caught");
}
procB();
procC();
}
}
Here is the output generated by the preceding program: inside
procA
procA’s finally
Exception caught inside
procB procB’s finally
inside procC procC’s
finally
Categories of Exceptions
Checked exceptions −A checked exception is an exception that occurs at the compiletime, these
are also called as compile time exceptions. These exceptions cannot simply be ignored at the
time of compilation, the programmer should take care of (handle) these exceptions.
Unchecked exceptions − An unchecked exception is an exception that occurs at thetime of
execution. These are also called as Runtime Exceptions. These include programming bugs, such
as logic errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation.
User defined exception needs to inherit (extends) Exception class in order to act as an
exception.
throw keyword is used to throw such exceptions.
Java I/O (Input and Output) is used to process the input and produce the output based
on the input. Java uses the concept of stream to make I/O operation fast. The java.io
package contains all the classes required for input and output operations.
Stream
A stream can be defined as a sequence of data. there are two kinds of Streams
InputStream: The InputStream is used to read data from a source.
OutputStream: the OutputStream is used for writing data to a
destination.
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes FileInputStream ,
FileOutputStream.
Character Streams
Java Character streams are used to perform input and output for 16-bit unicode. FileReader
, FileWriter
Standard Streams
Standard Input: This is used to feed the data to user's program and
usually a keyboard is used as standard input stream and represented as System.in.
Standard Output: This is used to output the data produced by the user's
program and usually a computer screen is used to standard output stream and
represented as System.out.
Standard Error: This is used to output the error data produced by the user's
program and usually a computer screen is used to standard error stream and represented as
System.err.
ByteStream classes have been designed to provide functional features for creating and manipulating
streams and files for reading and writing bytes. Since the streams are unidirectional, they can
transmit bytes in only one direction and therefore, Java provides two kinds of byte stream classes:
InputStream class and OutputStream class.
Input Stream Classes
Input stream classes that are used to read 8-bit bytes include a super class known as InputStream and
number of subclasses for supporting various input- related functions.
Hierarchy of Input Stream Classes
The super class InputStream is an abstract class, so we cannot create object for the class.
InputStream class defines the methods to perform the following functions:-
Reading Bytes
Closing Streams
Marking position in
Streams
Skipping ahead in streams
Finding the number of bytes in
stream.
OutputStream Class
The super class InputStream is an abstract class, so we cannot create object for the class.
InputStream class defines the methods to perform the following functions:
Writing Bytes
Closing Streams
Flushing
Streams
Hierarchy of OutputStream Classes
OutputStream Methods
Following constructor takes a file object to create an input stream object to read the file. First
we create a file object using File() method as follows −
Byte Stream
Byte streams process data byte by byte (8 bits). For example FileInputStream is used to read from
source and FileOutputStream to write to the destination.
// Java Program illustrating the Byte Stream to copy
// contents of one file to another file.
importjava.io.*; publicclassBStream
{
Public static void main(String[] args) throws IOException {
FileInputStream sourceStream = null;
FileOutputStream targetStream = null; try
{
sourceStream = newFileInputStream("sorcefile.txt");
targetStream = newFileOutputStream ("targetfile.txt");
// Reading source file and writing content to target // file byte by byte
inttemp;
while((temp = sourceStream.read()) != -1)
targetStream.write((byte)temp);
}
finally
{
if(sourceStream != null)
sourceStream.close(); if(targetStream != null)
targetStream.close();
}
Final Keyword In Java – Final variable, Method and Class
final keyword can be used along with variables, methods and classes.
1) final variable
2) final method
3) final class
1) final variable
final variables are nothing but constants. We cannot change the value of a final variable once it is
initialized. Lets have a look at the below code:
classDemo{
finalint MAX_VALUE=99; void
myMethod(){
MAX_VALUE=101;
}
Public static void main(String args[]){ Demo
obj=newDemo();
obj.myMethod();
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final field Demo.MAX_VALUE cannot be assigned at
beginnersbook.com.Demo.myMethod(Details.java:6) at
beginnersbook.com.Demo.main(Details.java:10)
We got a compilation error in the above program because we tried to change the
value of a final variable “MAX_VALUE”.
2) final method
A final method cannot be overridden. Which means even though a sub class can call the final
method of parent class without any issues but it cannot override it. Example:
class XYZ{
finalvoid demo(){ System.out.println("XYZ Class
Method");
}
}
class ABC extends XYZ{ void demo()
{
System.out.println("ABC Class Method");
}
public static void main(String args[]){ ABC
obj=new ABC(); obj.demo();
}
}
The above program would throw a compilation error, however we can use the parent class final
method in sub class without any issues. Lets have a look at this code: This program would run
fine as we are not overriding the final method. That shows that final methods are inherited but
they are not eligible for overriding.
class XYZ{ finalvoid
demo(){
System.out.println("XYZ Class Method");
}
}
class ABC extends XYZ{
public static void main(String args[]){ ABC
obj=new ABC(); obj.demo();
}
}
Output:
XYZ ClassMethod
3) final class
We cannot extend a final class. Consider the below example: finalclass XYZ{
}
class ABC extends XYZ{ void demo()
{
System.out.println("My Method");
}
Public static void main(String args[]){ ABC
obj=new ABC(); obj.demo();
}
}
Output:
The type ABC cannot subclass the final class XYZ
UNIT IV
MULTITHREADING AND GENERIC PROGRAMMING
Thread:
A thread is a single sequential (separate) flow of control within program.
Sometimes, it is called an execution context or light weight process.
Multithreading
Multithreading is a conceptual programming concept where a program (process)
is divided into two or more subprograms (process), which can be implemented
at the same time in parallel. A multithreaded program contains two or more
parts that can run concurrently. Each part of such a program is called a thread,
and each thread defines a separate path of execution.
Multitasking
Executing several tasks simultaneously is called multi-tasking.
There are 2 types of multi-tasking
1. Process-based multitasking
2. Thread-based multi-tasking
1. Process-based multi-tasking
Executing various jobs together where each job is a separate independent
operation is called process-based multi-tasking.
2. Thread-based multi-tasking
Executing several tasks simultaneously where each task is a separate
independent part of the same program is called Thread-based multitasking and
each independent part is called Thread. It is best suitable for the programmatic
level. The main goal of multi-tasking is to make or do a better performance of
the system by reducing response time
Multithreading vs Multitasking
Multitasking is to run multiple
Multithreading is to execute multiple
processes on a computer
threads in a process concurrently.
concurrently.
Execution
Resource Sharing
In Multithreading, resources are
In Multitasking, resources are shared
shared among multiple threads in a
among multiple processes.
process.
Complexity
Multithreading is light-weight and Multitasking is heavy-weight and
easy to create. harder to create.
Creation Of Thread
Thread Can Be Implemented In Two Ways
1) Implementing Runnable Interface
2) Extending Thread Class
General Syntax :
synchronized(object)
{
//statement to be
synchronized }
Why use Synchronization
The synchronization is mainly used to
o To prevent thread interference.
o To prevent consistency
problem.
Types of Synchronization
There are two types of synchronization
Process Synchronization
Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
Synchronized
method. Synchronized
block.
static
synchronization.
2. Cooperation (Inter-thread communication in java)
Synchronized method
If you declare any method as synchronized, it is known as synchronized
method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires
the lock for that object and releases it when the thread completes its task.
Example of synchronized method
package Thread; public
class SynThread {
public static void main(String
args[]) {
share s = new share();
MyThread m1 = new MyThread(s,
"Thread1"); MyThread m2 = new
MyThread(s, "Thread2");
MyThread m3 = new MyThread(s, "Thread3");
}
}
class MyThread extends Thread
{
share s;
MyThread(share s, String str)
{
super(str);
this.s = s;
start();
}
public void run()
{
s.doword(Thread.currentThread().getName());
}
}
class share
{
public synchronized void doword(String str)
{
for (int i = 0; i < 5; i++)
{
System.out.println("Started:" + str);
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
}}}}
Synchronized block.
Synchronized block can be used to perform synchronization on any
specific resource of the method.
Suppose you have 50 lines of code in your method, but you want to
synchronize only 5 lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will
work same as the synchronized method.
Example of synchronized block
class Table{
void printTable(int n)
{ synchronized(this){//synchronized
block for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
class MyThread1 extends
Thread{ Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends
Thread{ Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class
TestSynchronizedBlock1{ public static
void main(String args[]){ Table obj = new
Table();//only one object MyThread1
t1=new MyThread1(obj); MyThread2
t2=new MyThread2(obj); t1.start();
t2.start();
}
}
Static synchronization
If you make any static method as synchronized, the lock will be on the
class not on object.
Example of static synchronization
In this example we are applying synchronized keyword on the static
method to perform static synchronization.
class Table{
synchronized static void printTable(int n)
{ for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){}
}
}
}
class MyThread1 extends
Thread{ public void run(){
Table.printTable(1);
}
}
class MyThread2 extends
Thread{ public void run(){
Table.printTable(10);
}
}
class MyThread3 extends
Thread{ public void run(){
Table.printTable(100);
}
}
class MyThread4 extends
Thread{ public void run(){
Table.printTable(1000);
}
}
public class
TestSynchronization4{ public static
void main(String t[]){
MyThread1 t1=new
MyThread1(); MyThread2
t2=new MyThread2();
MyThread3 t3=new
MyThread3(); MyThread4
t4=new MyThread4(); t1.start();
t2.start();
t3.start();
t4.start();
}
}
Inter-thread communication
Inter-thread communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
Inter-thread communication is a mechanism in which a thread is paused
running in its critical section and another thread is allowed to enter (or lock) in
the same critical section to be executed.It is implemented by following methods
of Object class:
wait()
notify()
notifyAll()
wait()
tells calling thread to give up monitor and go to sleep until some
other thread enters the same monitor and call notify.
notify()
wakes up a thread that called wait() on same
object. notifyAll()
wakes up all the thread that called wait() on same object.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the
lock.
class Customer{
int
amount=10000;
synchronized void withdraw(int amount)
{ System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{ System.out.println("going to
deposit..."); this.amount+=amount;
System.out.println("deposit completed...
");
}
}
class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}
Daemon Thread in Java
Daemon thread in java is a service provider thread that provides services
to the user thread. Its life depend on the mercy of user threads i.e. when all the
user threads dies, JVM terminates this thread automatically.
Example:
public class TestDaemonThread1 extends
Thread{ public void run(){
if(Thread.currentThread().isDaemon()){//checking for daemon thread
System.out.println("daemon thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args){
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start();
t3.start();
}
}
Thread Group
Java provides a convenient way to group multiple threads in a single
object. In such way, we can suspend, resume or interrupt group of threads by a
single method call.
Constructors of ThreadGroup class
There are only two constructors of ThreadGroup class.
1. ThreadGroup(String name)-creates a thread group with given
name.
2. ThreadGroup(ThreadGroup parent, String name)-creates a
thread group with given parent group and name.
Important methods of ThreadGroup class
There are many methods in ThreadGroup class. A list of
important methods are given below.
Now all 3 threads belong to one group. Here, tg1 is the thread group
name, MyRunnable is the class that implements Runnable interface and "one",
"two" and "three" are the thread names.
Now we can interrupt all threads by a single line of
code only.
Thread.currentThread().getThreadGroup().interrupt();
ThreadGroup Example
public class ThreadGroupDemo implements
Runnable{ public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
Thread t1 = new Thread(tg1, runnable,"one");
t1.start();
Thread t2 = new Thread(tg1, runnable,"two"); t2.start();
Thread t3 = new Thread(tg1, runnable,"three");
t3.start();
System.out.println("Thread Group Name:
"+tg1.getName()); tg1.list();
}
}
Output:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent
ThreadGroup,maxpri=10]
Thread[one,5,Parent ThreadGroup]
Thread[two,5,Parent ThreadGroup]
Thread[three,5,Parent ThreadGroup]
Generic Programming
Generic programming enables the programmer to create
classes,interfaces and methods that automatically works with all types of
data(Integer, String, Float etc). It has expanded the ability to reuse the code
safely and easily. Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:
1) Type-safety : We can hold only a single type of objects in generics. It doesn’t
allow to store other objects.
2) Type casting is not required: There is no need to typecast the object.
3)Compile-Time Checking: It is checked at compile time so problem will not
occur at runtime. The good programming strategy says it is far better to handle
Generic class
A class that can refer to any type is known as generic class.
Generic class declaration defines set of parameterized type one for
each possible invocation of the type parameters
Example:
class TwoGen<T, V>
{
T ob1;
V ob2;
TwoGen(T o1, V o2)
{
ob1 = o1; ob2
= o2;
}
void showTypes() {
System.out.println("Type of T is " + ob1.getClass().getName());
System.out.println("Type of V is " + ob2.getClass().getName());
}
T getob1()
{
return ob1;
}
V getob2()
{
return ob2;
}
}
public class MainClass
{
public static void main(String args[])
{
TwoGen<Integer, String> tgObj = new TwoGen<Integer,
String>(88,"Generics");
tgObj.showTypes();
int v = tgObj.getob1();
System.out.println("value: " + v);
String str = tgObj.getob2();
System.out.println("value: " + str);
}
}
Generic Method
Like generic class, we can create generic method that can accept any type
of argument.
public class TestGenerics4{
public static < E > void printArray(E[] elements)
{ for ( E element : elements){
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] )
{ Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A'};
System.out.println( "Printing Integer Array"
); printArray( intArray );
System.out.println( "Printing Character Array" );
printArray( charArray );
}
}
Bounded type
The type parameters could be replaced by any class type. This is fine for
many purposes, but sometimes it is useful to limit the types that can be passed
to a type parameter
Syntax :
<T extends superclass>
Example
class Stats<T extends Number>
{ T[] nums;
Stats(T[] o)
{ nums = o;}
double average()
{ double sum =
0.0;
for(int i=0; i < nums.length; i+
+) sum +=
nums[i].doubleValue(); return
sum / nums.length;
}
}
public class MainClass {
public static void main(String args[]) {
Integer inums[] = { 1, 2, 3, 4, 5 };
Stats<Integer> iob = new
Stats<Integer>(inums); double v =
iob.average(); System.out.println("iob average
is " + v);
Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Stats<Double> dob = new Stats<Double>(dnums);
double w = dob.average();
System.out.println("dob average is " + w);
}
}
Restrictions on Generics
To use Java generics effectively, you must consider the following
restrictions:
Graphics programming
Java contains support for graphics that enable programmers to visually enhance applications
Java contains many more sophisticated drawing capabilities as part of the Java 2D API
AWT
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications
in java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system.
AWT is heavyweight i.e. its components are using the resources of OS.The java.awt package
provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox,
Choice, List etc.
1
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extend Container class are known as container such as Frame,
Dialog and Panel. Window
The window is the container that has no borders and menu bars. You must use frame, dialog or
another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components
like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
There are two ways to create a Frame. They are,
By Instantiating Frame class
By extending Frame class
Example:
import java.awt.*;
import java.awt.event.*;
class MyLoginWindow extends Frame
{
TextField name,pass;
Button b1,b2;
MyLoginWindow()
{
setLayout(new FlowLayout());
this.setLayout(null);
Label n=new Label("Name:",Label.CENTER);
Label p=new Label("password:",Label.CENTER);
name=new TextField(20);
pass=new TextField(20);
pass.setEchoChar('#');
b1=new Button("submit");
b2=new Button("cancel");
this.add(n);
this.add(name);
this.add(p);
this.add(pass);
this.add(b1);
this.add(b2);
2
n.setBounds(70,90,90,60);
p.setBounds(70,130,90,60);
name.setBounds(200,100,90,20);
pass.setBounds(200,140,90,20);
b1.setBounds(100,260,70,40);
b2.setBounds(180,260,70,40);
}
public static void main(String args[])
{
MyLoginWindow ml=new
MyLoginWindow();
ml.setVisible(true);
ml.setSize(400,400);
ml.setTitle("my login window");
}}
Event handling:
Changing the state of an object is known as an event. For example, click on button, dragging mouse
etc. The java.awt.event package provides many event classes and Listener interfaces for event handling.
Event handling has three main components,
Events : An event is a change in state of an object.
Events Source : Event source is an object that generates an event.
Listeners : A listener is an object that listens to the event. A listener gets notified when
an event occur
3
How Events are handled ?
A source generates an Event and send it to one or more listeners registered with the source. Once
event is received by the listener, they process the event and then return. Events are supported by a number
of Java packages, like java.util, java.awt and java.awt.event.
Important Event Classes and Interface
4
FocusEvent generated when component gains or loses keyboard FocusListener
focus
Mouse Listener
package Listener;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
5
public class Mouse implements MouseListener
{ TextArea s;
public Mouse()
{
Frame d=new Frame("kkkk");
s=new TextArea("");
d.add(s);
s.addMouseListener(this);
d.setSize(190, 190);
d.show();
}
public void mousePressed(MouseEvent e) {
System.out.println("MousePressed");
int a=e.getX();
int b=e.getY();
System.out.println("X="+a+"Y="+b);
}
public void mouseReleased(MouseEvent e) {
System.out.println("MouseReleased");
}
public void mouseEntered(MouseEvent e) {
System.out.println("MouseEntered");
}
public void mouseExited(MouseEvent e) {
System.out.println("MouseExited");
}
public void mouseClicked(MouseEvent e) {
System.out.println("MouseClicked");
}
public static void main(String arg[])
{
Mouse a=new Mouse();
6
}
}
package Listener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class MouseMotionEventDemo extends JPanel implements MouseMotionListener
{MouseMotionEventDemo()
{
JTextArea a=new JTextArea();
a.addMouseMotionListener(this);
JFrame b=new JFrame();
b.add(a);
b.setVisible(true);
}
public void mouseMoved(MouseEvent e)
{ System.out.println("Mouse is Moving");
}
public void mouseDragged(MouseEvent e) {
System.out.println("MouseDragged");
}
public static void main(String arg[])
{
MouseMotionEventDemo a=new MouseMotionEventDemo();
}
}
7
KEY LISTENER
package Listener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class KeyEventDemo implements KeyListener
{
public KeyEventDemo()
{
JFrame s=new JFrame("hai");
JTextField typingArea = new JTextField(20);
typingArea.addKeyListener(this);
s.add(typingArea);
s.setVisible(true);
}
public void keyTyped(KeyEvent e) {
System.out.println("KeyTyped");
}
/** Handle the key-pressed event from the text field. */
public void keyPressed(KeyEvent e) {
System.out.println("KeyPressed");
}
/** Handle the key-released event from the text field. */
public void keyReleased(KeyEvent e) {
System.out.println("Keyreleased");
}
public static void main(String g[])
{
KeyEventDemo a=new KeyEventDemo();
}
}
8
ITEM LISTENER
package Listener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class itemlistener implements ItemListener
{
public itemlistener()
{
JFrame s=new JFrame("hai");
JCheckBox a=new JCheckBox("Ok");
a.addItemListener(this);
s.add(a);
s.setVisible(true);
}
public static void main(String g[])
{
itemlistener l=new itemlistener();
}
public void itemStateChanged(ItemEvent arg0) {
System.out.println("State changed");
}
}
9
Window Listener
package Listener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class window extends JPanel implements WindowListener {
window()
{
JFrame b=new JFrame();
b.addWindowListener(this);
b.setVisible(true);
}
public static void main(String arg[])
{
window a=new window();
}
public void windowActivated(WindowEvent arg0) {
System.out.println("Window activated");
}
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Window closed");
}
public void windowClosing(WindowEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Window closing");
}
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
10
System.out.println("Window deactivated");
}
public void windowDeiconified(WindowEvent arg0)
{
// TODO Auto-generated method stub
System.out.println("Window deiconified");
}
public void windowIconified(WindowEvent arg0)
{
// TODO Auto-generated method stub
System.out.println("Window Iconified");
}
public void windowOpened(WindowEvent arg0)
{
// TODO Auto-generated method stub
System.out.println("Window opened");
}}
package Listener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class window1 extends JPanel implements WindowFocusListener
{ window1()
{
JFrame b=new JFrame();
11
public static void main(String
arg[]) {
window1 b=new window1();
}
public void windowGainedFocus(WindowEvent e)
{
// TODO Auto-generated method stub
System.out.println("Window gained");
}
public void windowLostFocus(WindowEvent e)
{
// TODO Auto-generated method stub
System.out.println("Windowlostfocus");
}}
WindowStateListener
package Listener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class window2 extends JPanel implements WindowStateListener
{ window2()
{
JFrame b=new JFrame();
b.addWindowStateListener(this);
b.setVisible(true);
}
public static void main(String
12
}
public void windowStateChanged(WindowEvent e)
{
// TODO Auto-generated method
stub System.out.println("State
Changed");
}}
ACTION LISTENER
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class A extends JFrame implements ActionListener
{
Scientific() {
JPanel buttonpanel = new JPanel();
JButton b1 = new JButton("Hai");
buttonpanel.add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
System.out.println(“Hai button”);
}
public static void main(String args[])
{ A f = new A();
f.setTitle("ActionListener");
f.setSize(500,500);
f.setVisible(true);
}}
13
The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
14
}
public static void main(String[] args)
{ new AdapterExample();
} }
15
f.addMouseMotionListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseDragged(MouseEvent e)
{ Graphics g=f.getGraphics();
g.setColor(Color.ORANGE);
g.fillOval(e.getX(),e.getY(),20,20);
}
public static void main(String[] args) {
new MouseMotionAdapterExample();
} }
16
public void keyReleased(KeyEvent e)
{ String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
public static void main(String[] args)
{ new KeyAdapterExample();
} }
Swing
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in
java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
17
The hierarchy of java swing API is given
below
18
Layout management
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an
interface that is implemented by all the classes of layout managers. There are following classes that
represents the layout managers:
AWT Layout Manager Classes
Following is the list of commonly used controls while designing GUI using AWT.
BorderLayout
1 The borderlayout arranges the components to fit in the five regions: east, west,
north, south, and center.
CardLayout
2 The CardLayout object treats each component in the container as a card. Only one
card is visible at a time.
3 FlowLayout
The FlowLayout is the default layout. It layout the components in a directional flow.
4 GridLayout
The GridLayout manages the components in the form of a rectangular
grid.
GridBagLayout
This is the most flexible layout manager class. The object of GridBagLayout aligns
the component vertically, horizontally, or along their baseline without requiring the
components of the same size.
GroupLayout
6 The GroupLayout hierarchically groups the components in order to position them
in a Container.
SpringLayout
7 A SpringLayout positions the children of its associated container according to a
set of constraints.
8 BoxLayout
The BoxLayout is used to arrange the components either vertically or horizontally.
ScrollPaneLayout
9 The layout manager used by JScrollPane. JScrollPaneLayout is responsible for nine
components: a viewport, two scrollbars, a row header, a column header, and four
"corner" components.
19
Border layout:
Example:
import java.awt.*;
import javax.swing.*;
public class Border
{ JFrame f;
Border(){
f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{ new Border();
} }
ScrollPaneLayout:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
public class ScrollPaneDemo extends JFrame
20
{
public ScrollPaneDemo()
{ super("ScrollPane
Demo");
ImageIcon img = new ImageIcon("child.png");
JScrollPane png = new JScrollPane(new JLabel(img));
getContentPane().add(png);
setSize(300,250);
setVisible(true);
}
public static void main(String[] args) {
new ScrollPaneDemo();
} }
Boxlayout
import java.awt.*;
import javax.swing.*;
public class BoxLayoutExample1 extends Frame
{ Button buttons[];
public BoxLayoutExample1 ()
{ buttons = new Button [5];
for (int i = 0;i<5;i++) {
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}
public static void main(String args[]){
BoxLayoutExample1 b=new BoxLayoutExample1();
}
21
Group layout:
Example
public class GroupExample
{
public static void main(String[] args)
{
JFrame frame = new JFrame("GroupLayoutExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPanel = frame.getContentPane();
GroupLayout groupLayout = new GroupLayout(contentPanel);
contentPanel.setLayout(groupLayout);
JLabel clickMe = new JLabel("Click
Here"); JButton button = new JButton("This
Button"); groupLayout.setHorizontalGroup(
groupLayout.createSequentialGroup()
.addComponent(clickMe)
.addGap(10, 20, 100)
.addComponent(button));
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(clickMe)
.addComponent(button));
frame.pack();
frame.setVisible(true);
} }}
Swing components:
Text Fields
The object of a JTextField class is a text component that allows the editing of a single line text. It
inherits JTextComponent class.
Text Areas
The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class
22
Buttons
The JButton class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed. It inherits AbstractButton
class. import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class SwingFirstExample {
public static void main(String[] args) {
// Creating instance of JFrame
JFrame frame = new JFrame("My First Swing Example");
// Setting the width and height of frame
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/* Creating panel. This is same as a div tag in HTML
* We can create several panels and add them to specific
* positions in a JFrame. Inside panels we can add text
* fields, buttons and other components.
*/
JPanel panel = new JPanel();
// adding panel to frame
frame.add(panel);
/* calling user defined method for adding components
* to the panel.
*/
placeComponents(panel);
// Setting the frame visibility to
true frame.setVisible(true); }
private static void placeComponents(JPanel panel) {
/* We will discuss about layouts in the later sections * of this tutorial. For now we are setting the
layout * to null */
23
panel.setLayout(null);
// Creating JLabel
JLabel userLabel = new JLabel("User");
/* This method specifies the location and size
* of component. setBounds(x, y, width, height)
* here (x,y) are cordinates from the top left
* corner and remaining two arguments are the width
* and height of the component.
*/
userLabel.setBounds(10,20,80,25);
panel.add(userLabel);
/* Creating text field where user is supposed to
* enter user name.
*/
JTextField userText = new JTextField(20);
userText.setBounds(100,20,165,25);
panel.add(userText);
// Same process for password label and text field.
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10,50,80,25);
panel.add(passwordLabel);
/*This is similar to text field but it hides the user
* entered data and displays dots instead to protect
* the password like we normally see on login screens.
*/
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100,50,165,25);
panel.add(passwordText);
// Creating login button
JButton loginButton = new JButton("login");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
}}
24
Output:
Check Boxes
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits
JToggleButton class.
Example:
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
25
}}
Radio Buttons The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz. It should be added in ButtonGroup to
select one radio
button only.
import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame implements ActionListener{
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female.");
} }
26
public static void main(String args[])
{ new RadioButtonExample();
}}
Lists
The object of JList class represents a list of text items. The list of text items can be set up so that
the user can choose either one item or multiple items. It inherits JComponent
class. import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new
JList<>(l1); list.setBounds(100,100,
75,75); f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String
args[])
{
new ListExample();
27
Choices (JComboBox)
The object of Choice class is used to show popup menu of choices. Choice selected by user is shown
on the top of a menu. It inherits JComponent class.
import javax.swing.*;
public class ComboBoxExample
{
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args)
{ new ComboBoxExample();
28
Output:
Scrollbars
The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an implementation
of a scrollbar. It inherits JComponent class.
mport javax.swing.*;
class ScrollBarExample
{
ScrollBarExample(){
JFrame f= new JFrame("Scrollbar Example");
JScrollBar s=new JScrollBar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ScrollBarExample();
}}
29
Output:
Windows
The class JWindow is a container that can be displayed but does not have the title bar
Menus
The JMenuBar class is used to display menubar on the window or frame. It may have several
menus. The object of JMenu class is a pull down menu component which is displayed from the
menu bar. It
inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must
belong to the JMenuItem or any of its subclass.
import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
30
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}}
Output :
Dialog Boxes.
The JDialog control represents a top level window with a border and a title used to take some form
of input from the user. It inherits the Dialog class.Unlike JFrame, it doesn't have maximize and minimize
buttons.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample
{ private static JDialog d;
DialogExample() {
JFrame f= new JFrame();
31
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false); }}};
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample(); }}
Output:
32