0% found this document useful (0 votes)
13 views137 pages

Module 4

Uploaded by

Zaryab Ahmar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
13 views137 pages

Module 4

Uploaded by

Zaryab Ahmar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 137

OOPDP

Module IV
Exception Handling in
Java
• An exception is an unwanted or unexpected event,
which occurs during the execution of a program
i.e at run time, that disrupts the normal flow of
the program’s instructions.

• [Error: An Error indicates serious problem that a


Exception reasonable application should not try to catch.]

• Exception: Exception indicates conditions that a


reasonable application might try to catch.
• It is an object which is thrown at runtime.
• All exception and errors types are sub classes of
class Throwable, which is base class of hierarchy.

• One branch is headed by Exception.


• This class is used for exceptional conditions that
user programs should catch.
Exception • NullPointerException is an example of such an
Hierarchy exception.

• Another branch, Error are used by the Java run-


time system(JVM) to indicate errors having to do
with the run-time environment itself(JRE).
• StackOverflowError is an example of such an
error.
Exception Hierarchy
• Whenever inside a method, if an exception has
occurred, the method creates an Object known as
How JVM Exception Object and hands it off to the run-time
system(JVM).
handle an • The exception object contains name and description of
the exception, and current state of the program where
Exception? exception has occurred.
• Creating the Exception Object and handling it to the
run-time system is called throwing an Exception.
• There might be the list of the methods that had
been called to get to the method where exception
was occurred.
• This ordered list of the methods is called Call
Stack.
• Now the following procedure will happen.
• The run-time system searches the call stack to find
the method that contains block of code that can
handle the occurred exception. The block of the
code is called Exception handler.
• The run-time system starts searching from the
method in which exception occurred, proceeds
through call stack in the reverse order in which
methods were called.
• If it finds appropriate handler then it passes the
occurred exception to it.
• Appropriate handler means the type of the
exception object thrown matches the type of the
exception object it can handle.
• If run-time system searches all the methods on call
stack and couldn’t have found the appropriate
handler then run-time system handover the
Exception Object to default exception handler ,
which is part of run-time system.
• This handler prints the exception information in
the following format and terminates program
abnormally.
• There are mainly two types of exceptions:
Types of checked and unchecked.
Java 1. Checked Exception
2. Unchecked Exception
Exceptions
1. Checked Exception
• The classes which directly inherit Throwable class
except RuntimeException and Error are known as
checked exceptions e.g. IOException, SQLException
etc.
• Checked exceptions are checked at compile-time.

2. Unchecked Exception
• The classes which inherit RuntimeException are
known as unchecked exceptions e.g.
ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
• Unchecked exceptions are not checked at compile-
time, but they are checked at runtime.
• Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally.

• try
How
• Program statements that you think can raise
Programmer exceptions are contained within a try block.
handles an
exception? • catch
• If an exception occurs within the try block, it is
thrown. Your code can catch this exception (using
catch block) and handle it in some rational
manner.
• throw
• System-generated exceptions are automatically thrown
by the Java run-time system.
• To manually throw an exception, use the keyword
throw.

• throws
• Any exception that is thrown out of a method must be
specified as such by a throws clause.

• finally
• Any code that absolutely must be executed after a try
block completes is put in a finally block.
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
int[] arr = new int[4];
int i = arr[4];
Example // the following statement will never execute
System.out.println("Hi, I want to execute");

}
}
• Output
Hello World

Exception in thread "main" java.lang.ArrayIndex


OutOfBoundsException: 4
at Main.main(Main.java:16)
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
int[] arr = new int[4];
try {
Example: int i = arr[4];
Exception }

Handling catch(Exception e)
{
System.out.println("Exception Handled");
}
System.out.println("Hi, I want to execute");
}
}
• Output
Hello World

Exception Handled

Hi, I want to execute


1. int a=50/0;//ArithmeticException

2. String s=null;
Common System.out.println(s.length());//NullPointerException
Scenarios
of Java 3. String s="abc";
Exceptions int i=Integer.parseInt(s);//NumberFormatException
public class TryCatchExample{
public static void main(String[] args) {
int i=50;
int j=0;
int data;
try
{

Example data=i/j; //may throw exception


}
catch(Exception e)
{
System.out.println(i/(j+2));
}
}
}
• Output:
25
• A try block can be followed by one or more catch
blocks.
Java Multi- • Each catch block must contain a different
exception handler.
catch block • So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-
catch block.
• At a time only one exception occurs and at a time
only one catch block is executed.
• All catch blocks must be ordered from most specific
to most general, i.e. catch for ArithmeticException
must come before catch for Exception.
public class MultipleCatchBlock {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
Example System.out.println("Arithmetic Exception occurs");

}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exc
eption occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");

}
System.out.println("rest of the code");
}
}
• Output
Arithmetic Exception occurs
rest of the code
• If an exception occurs at the particular statement
of try block, the rest of the block code will not
execute.
• So, it is recommended not to keeping the code in
try block that will not throw an exception.
Points to • In a method, there can be more than one
Remember statements that might throw exception, So put all
these statements within its own try block and
provide separate exception handler within
own catch block for each of them.
• A try block must be followed by catch blocks or
finally block or both.
• If no exception occurs in try block then the catch
blocks are completely ignored.
• we cannot write any statements in between
try, catch and finally blocks and
these blocks form one unit.
• Sometimes a situation may arise where a part of a
block may cause one error and the entire block
itself may cause another error.
Nested try • In such cases, exception handlers have to be
nested.
class Main{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;

Example }catch(ArithmeticException e){System.out.println(e);}

try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException
e){System.out.println(e);}
System.out.println("other statement");
}catch(Exception
e){System.out.println("handeled");}

System.out.println("normal flow..");
}
}
• Output
going to divide

java.lang.ArithmeticException: / by zero

java.lang.ArrayIndexOutOfBoundsException: 5

other statement

normal flow..
• Java finally block is a block that is used to execute
important code such as closing connection, stream
etc.
Java finally • Java finally block is always executed whether
block exception is handled or not.
• Java finally block follows try or catch block.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
Example {System.out.println(e);}
Finally
{System.out.println("finally block is always executed");}

System.out.println("rest of the code...");


}
}
• Output
5
finally block is always executed
rest of the code...
class TestExceptionPropagation{
void m(){
int data=50/0;
}
void n(){

Example:Excep m();
}
tion
void p(){
Propagation
try{
n();
}catch(Exception e){System.out.println("exceptio
n handled");}
}
public static void main(String args[]){
TestExceptionPropagation1 obj=new TestExc
eptionPropagation1();
obj.p();
System.out.println("normal flow...");
}
}
• Output:
exception handled
normal flow...
• The Java throw keyword is used to explicitly
throw an exception.

Java throw • We can throw either checked or uncheked


exception in java by throw keyword.
keyword • The throw keyword is mainly used to throw
custom exception.
public class TestThrow{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
Example public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
• Output:
• Exception in thread main
java.lang.ArithmeticException:not
valid
• The Java throws keyword is used to declare an
exception.
Java throws • It gives an information to the programmer that there
keyword may occur an exception so it is better for the
programmer to provide the exception handling code
so that normal flow can be maintained.
• Syntax of java throws
return_type method_name() throws exception_class_name
{
//method code
}
import java.io.IOException;
class Main{
void m(){
throw new IOException("device error");//checked exception
}
void n(){
m();
}
void p(){

Example1 try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Main obj=new Main();
obj.p();
System.out.println("normal flow...");
}
}
• Output
• Main.java:4: error: unreported exception IOException; must be
caught or declared to be thrown
• throw new IOException("device error");//checked exception
• ^
• 1 error
import java.io.IOException;
class Main{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){

Example2 try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Main obj=new Main();
obj.p();
System.out.println("normal flow...");
}
}
• Output
exception handled

normal flow...
• Rule: If you are calling a method that declares an
exception, you must either caught or declare the
exception.
• There are two cases:
• Case1:You caught the exception i.e. handle the exception
using try/catch.
• Case2:You declare the exception i.e. specifying throws
with the method.
• If you are creating your own Exception that is
known as custom exception or user-defined
Java exception.
• Java custom exceptions are used to customize the
Custom exception according to user need.
Exception • By the help of custom exception, you can have your
own exception and message.
class MyException extends Exception
{
public MyException(String s)
{
super(s);
}
}
public class Main
{
public static void main(String args[])
{

Example1
try
{
throw new MyException("Exception Message");
}
catch (MyException ex)
{
System.out.println("Caught");

System.out.println(ex.getMessage());
}
}
}
• Output:
Caught
Exception Message
class MyException extends Exception
{

}
public class Main
{
public static void main(String args[])
{

Example2
try
{ throw new MyException();
}
catch (MyException ex)
{
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}
• Output
Caught
null
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}

class TestCustomException{

Example3 static void validate(int age)throws InvalidAgeException{


if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exc
eption occured: "+m);}

System.out.println("rest of the code...");


}
}
• Output
Exception occured:
InvalidAgeException:not valid
rest of the code...
• Chained Exceptions allows to relate one exception
with another exception,
• i.e one exception describes cause of another
exception.
• For example, consider a situation in which a method
throws an ArithmeticException because of an attempt
Chained to divide by zero but the actual cause of exception was
Exceptions in an I/O error which caused the divisor to be zero.

Java • The method will throw only ArithmeticException to


the caller.
• So the caller would not come to know about the actual
cause of exception.
• Chained Exception is used in such type of situations.
• Constructors Of Throwable class Which support
chained exceptions in java :

1.Throwable(Throwable cause) :-
• Where cause is the exception that causes the
current exception.
2.Throwable(String msg, Throwable cause) :-
• Where msg is the exception message and cause is
the exception that causes the current exception.
• Methods Of Throwable class Which
support chained exceptions in java :

1.getCause() method :-
• This method returns actual cause of an exception.
2.initCause(Throwable cause) method :-
• This method sets the cause for the calling
exception.
public class ExceptionHandling
{
public static void main(String[] args)
{
try
{
NumberFormatException ex =
new
NumberFormatException("Exception");
ex.initCause(new NullPointerException(

Example exception"));
"This is actual cause of the

throw ex;
}
catch(NumberFormatException ex)
{
System.out.println(ex);
System.out.println(ex.getCause());
}
}
}
• Output
java.lang.NumberFormatException: Exception
java.lang.NullPointerException: This is
actual cause of the exception
• In Java, the try-with-resources statement is a
try statement that declares one or more
resources.
• The resource is as an object that must be
The try-with- closed after finishing the program.
resources • The try-with-resources statement ensures that
each resource is closed at the end of the
statement statement execution.
• You can pass any object that implements
java.lang.AutoCloseable
• The following example writes a string into a
file.
• It uses an instance of FileOutputStream to
write data into the file.
• FileOutputStream is a resource that must be
closed after the program is finished with it.
• So, in this example, closing of resource is
done by itself try.
import java.io.FileOutputStream;
public class TryWithResources {
public static void main(String args[]){
// Using try-with-resources
try(FileOutputStream fileOutputStream =newFileOutputStream("/java7-
new-features/src/abc.txt"))
{
String msg = "Welcome to javaTpoint!";
byte byteArray[] = msg.getBytes(); //converting string into byte array
Example fileOutputStream.write(byteArray);
System.out.println("Message written to file successfuly!");
}
catch(Exception exception){
System.out.println(exception);
}
}
}
• Output:
• Message written to file successfuly!
• An assertion allows testing the correctness of any
assumptions that have been made in the program.
• Assertion is achieved using the assert statement in
Java.
• While executing assertion, it is believed to be true.
Java Assertion • If it fails, JVM throws an error
named AssertionError.
• It is mainly used for testing purposes during
development.
import java.util.Scanner;

class Test
{
public static void main( String args[]
)
{
Example int value = 15;
assert value >= 20 : "
Underweight";
System.out.println("value is
"+value);
}
}
• Output:
value is 15

• After enabling assertions( java –ea Test)


Output:
Exception in thread "main"
java.lang.AssertionError: Underweight
JAVA 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.
Java AWT
Hierarchy
• All the elements like buttons, text fields, scrollbars
etc are known as components.
• In AWT we have classes for each component
• To have everything placed on a screen to a particular
position, we have to add them to a container.
Component
• A container is like a screen wherein we are placing
and Container components like buttons, text fields, checkbox etc.
• In short a container contains and controls the layout
of components.
• A container itself is a component thus we can add
a container inside container.
• The classes that extends Container class are
known as container such as Frame, Dialog and Panel.
• Window
• The window is the container that have 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.
Useful Methods of Componenet Class

Method Description

public void add(Component c) inserts a component on this component.


public void setSize(int width,int height) sets the size (width and height) of the component.

public void setLayout(LayoutManager m) defines the layout manager for the component.

public void setVisible(boolean status) changes the visibility of the component, by default
false.
• To create simple awt example, you need a
frame.
Java • There are two ways to create a frame in AWT.
AWT Example • By extending Frame class (inheritance)
• By creating the object of Frame class (association)
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
AWT Example
setSize(300,300);//frame size 300 width and 300 height
by Inheritance
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible

}
public static void main(String args[]){
First f=new First();
}}
Output
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
AWT Example f.add(b);
by Association f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}}
Output
• The object of Label class is a component for
placing text in a container.
Java AWT • It is used to display a single line of read only text.
Label • The text can be changed by an application but a
user cannot edit it directly.
import java.awt.*;
class First{
public static void main(String args[]){
Frame f= new Frame("Label Example");
Label l1,l2;
l1=new Label("First Label.");
l1.setBounds(50,100, 100,30);
l2=new Label("Second Label.");
Example l2.setBounds(50,150, 100,30);
f.add(l1); f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output
• The object of a TextField class is a text component
Java that allows the editing of a single line text.
AWT TextField • It inherits TextComponent class
import java.awt.*;
class TextFieldExample{
public static void main(String args[]){
Frame f= new Frame("TextField Example");
TextField t1,t2;
t1=new TextField("Welcome.");
t1.setBounds(50,100, 200,30);
t2=new TextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output
• The object of a TextArea class is a multi line
region that displays text.
Java • It allows the editing of multiple line text.
AWT TextArea • It inherits TextComponent class.
import java.awt.*;
public class First
{
First(){
Frame f= new Frame();
TextArea area=new TextArea("Welcome to AWT
Tutorial");
area.setBounds(10,30, 300,300);

Example f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new First();
}
}
Output
• The Checkbox class is used to create a
checkbox.
Java AWT • It is used to turn an option on (true) or off
Checkbox (false).
• Clicking on a Checkbox changes its state from
"on" to "off" or from "off" to "on".
import java.awt.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java", true);
checkbox2.setBounds(100,150, 50,50);

Example f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxExample();
}
}
Output
• The object of Choice class is used to show popup
menu of choices.
Java AWT • Choice selected by user is shown on the top of a
menu.
Choice
• It inherits Component class.
import java.awt.*;
public class ChoiceExample
{
ChoiceExample(){
Frame f= new Frame();
Choice c=new Choice();
c.setBounds(100,100, 75,75);
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");

Example c.add("Item 5");


f.add(c);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ChoiceExample();
}
}
Output
• The object of List class represents a list of text
items.
• By the help of list, user can choose either one item
Java AWT List or multiple items.
• It inherits Component class.
import java.awt.*;
public class ListExample
{
ListExample(){
Frame f= new Frame();
List l1=new List(5);
l1.setBounds(100,100, 75,75);
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");

Example l1.add("Item 4");


l1.add("Item 5");
f.add(l1);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}
Output
• Changing the state of an object is known as an
event.
Java Event
• For example, click on button, dragging mouse etc.
Handling
• The java.awt.event package provides many event
classes and Listener interfaces for event handling.
• The events can be broadly classified into two
categories:
• Foreground Events -
• Those events which require the direct interaction of user.
• They are generated as consequences of a person interacting
with the graphical components in Graphical User Interface.

Types of • For example, clicking on a button, moving the mouse,


entering a character through keyboard,selecting an item
Events from list, scrolling the page etc.

• Background Events -
• Those events that do not require the interaction of end user
are known as background events.
• Operating system interrupts, hardware or software failure,
timer expires, an operation completion are the example of
background events.
• Event Handling is the mechanism that controls the
event and decides what should happen if an event
occurs.
• The Delegation Event Model has the following key
participants namely:
• Source -
Event • The source is an object on which event occurs.
• Source is responsible for providing information of the
Handling occurred event to it's handler.
• Java provide as with classes for source object.
• Listener -
• It is also known as event handler.
• Listener is responsible for generating response to an event.
• Once the event is received , the listener process the event an
then returns.
Event Classes
Description Listener Interface
ActionEvent generated when button is pressed, menu- ActionListener
item is selected, list-item is double clicked

MouseEvent generated when mouse is dragged, MouseListener


moved,clicked,pressed or released and
also when it enters or exit a component

Important KeyEvent generated when input is received from KeyListener


Event Classes keyboard

and Interface ItemEvent generated when check-box or list item is ItemListener


clicked
TextEvent generated when value of textarea or TextListener
textfield is changed

MouseWheelEve generated when mouse wheel is moved MouseWheelListener


nt
WindowEvent generated when window is activated, WindowListener
deactivated, deiconified, iconified, opened
or closed
• Java ActionListener Interface
• The Java ActionListener is notified whenever you
click on the button or menu item.
• It is notified against ActionEvent.
• The ActionListener interface is found in
java.awt.event package.
• It has only one method: actionPerformed().
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener
{
TextField tf;
AEvent(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Example Button b=new Button("click me");
b.setBounds(100,120,80,30);
b.addActionListener(this);//passing current instance
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
Output
• Java MouseListener Interface
• The Java MouseListener is notified whenever you
change the state of mouse.
• It is notified against MouseEvent. The
MouseListener interface is found in java.awt.event
package.
• It has five methods.
• public abstract void mouseClicked(MouseEvent e);
• public abstract void mouseEntered(MouseEvent e);
• public abstract void mouseExited(MouseEvent e);
• public abstract void mousePressed(MouseEvent e);
• public abstract void mouseReleased(MouseEvent e);
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements
MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);

Example l=new Label();


l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
Output
• Java KeyListener Interface
• The Java KeyListener is notified whenever you
change the state of key.
• It is notified against KeyEvent.
• The KeyListener interface is found in
java.awt.event package.
• It has three methods.
• public abstract void keyPressed(KeyEvent e);
• public abstract void keyReleased(KeyEvent e);
• public abstract void keyTyped(KeyEvent e);
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame imple
ments KeyListener{
Label l;
TextArea area;
KeyListenerExample(){
l=new Label();

Example l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e) {
l.setText("Key Released");
}
public void keyTyped(KeyEvent e) {
l.setText("Key Typed");
}

public static void main(String[] args) {


new KeyListenerExample();
}
}
Output
• Java adapter classes provide the default implementation of
listener interfaces.
• If you inherit the adapter class, you will not be
Java Adapter forced to provide the implementation of all the
Classes methods of listener interfaces.
• So it saves code.
java.awt.event Adapter classes

Adapter class Listener interface


WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
Frame f, Label l;
MouseAdapterExample(){
f=new Frame("Mouse Adapter");
l=new Label();
l.setBounds(20,50,100,20);
f.add(l);
f.addMouseListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public static void main(String[] args) {
new MouseAdapterExample();
}
}
• The LayoutManagers are used to arrange
Java components in a particular manner.
LayoutManagers • LayoutManager is an interface that is implemented
by all the classes of layout managers.
• There are following classes that represents the
layout managers:
• java.awt.BorderLayout
• java.awt.FlowLayout
• java.awt.GridLayout
• java.awt.CardLayout
• java.awt.GridBagLayout
• Java BorderLayout
• The BorderLayout is used to arrange the
components in five regions: north, south, east, west
and center.
• Each region (area) may contain one component
only.
• It is the default layout of frame or window.
• The BorderLayout provides five constants for each
region:
• public static final int NORTH
• public static final int SOUTH
• public static final int EAST
• public static final int WEST
• public static final int CENTER
• Constructors of BorderLayout class:
1.BorderLayout():
• creates a border layout but with no gaps between
the components.
2.BorderLayout(int hgap, int vgap):
• creates a border layout with the given horizontal
and vertical gaps between the components.
import java.awt.*;
public class Border {
Frame f;
Border(){
f=new Frame();
Button b1=new Button("ONE");;
Button b2=new Button("TWO");;
Button b3=new Button("THREE");;
Button b4=new Button("FOUR");;
Button b5=new Button("FIVE");;

Example 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();
}
}
Output
• You can also add gap between components by
using the following line of code
• f.setLayout(new BorderLayout(10,10));
• Then the output will be as follows
• Java GridLayout
• The GridLayout is used to arrange the components
in rectangular grid.
• One component is displayed in each rectangle.
• Constructors of GridLayout class

1.GridLayout(): creates a grid layout with one


column per component in a row.
2.GridLayout(int rows, int columns): creates a
grid layout with the given rows and columns but no
gaps between the components.
3.GridLayout(int rows, int columns, int hgap,
int vgap): creates a grid layout with the given rows
and columns alongwith given horizontal and vertical
gaps.
import java.awt.*;
public class MyGridLayout{
Frame f;
MyGridLayout(){
f=new Frame();

Button b1=new Button("1");


Button b2=new Button("2");
Example Button b3=new Button("3");
Button b4=new Button("4");
Button b5=new Button("5");
Button b6=new Button("6");
Button b7=new Button("7");
Button b8=new Button("8");
Button b9=new Button("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);

f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Output
• Java FlowLayout
• The FlowLayout is used to arrange the
components in a line, one after another (in a
flow).
• It is the default layout of applet or panel.
• Fields of FlowLayout class
• public static final int LEFT
• public static final int RIGHT
• public static final int CENTER
• public static final int LEADING
• public static final int TRAILING
• Constructors of FlowLayout class

1.FlowLayout(): creates a flow layout with centered


alignment and a default 5 unit horizontal and vertical
gap.
2.FlowLayout(int align): creates a flow layout with
the given alignment and a default 5 unit horizontal
and vertical gap.
3.FlowLayout(int align, int hgap, int
vgap): creates a flow layout with the given alignment
and the given horizontal and vertical gap.
import java.awt.*;
public class MyFlowLayout{
Frame f;
MyFlowLayout(){
f=new Frame();
Button b1=new Button("1");
Button b2=new Button("2");
Button b3=new Button("3");

Example
Button b4=new Button("4");
Button b5=new Button("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
Output
• The Panel is a simplest container class.
• It provides space in which an application can attach
any other component.
Java AWT Panel • It inherits the Container class.
• It doesn't have title bar.
import java.awt.*;
public class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);

Example panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Output
Module IV-Syllabus
• Exception Handling & GUI Design
• When to use exception handling, Java exception hierarchy, finally block, Stack
unwinding, Chained exceptions, Declaring new exception types, Assertions,
try with resources. Simple I/O with GUI, Basic GUI Components, GUI
Event handling, Adapter classes, Layout managers

You might also like