0% found this document useful (0 votes)
4 views34 pages

Chapter3_Notes java

Uploaded by

sakibmujawar108
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)
4 views34 pages

Chapter3_Notes java

Uploaded by

sakibmujawar108
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/ 34

CHAPTER - 3

Managing Exceptions
Error
As a human being we do mistakes that lead to incorrect result. Software engineer may also
commit several errors while developing the code. These errors also called as bug and the process
of removing them is called as debugging.
There are basically three types of errors
Compile-time errors: These are syntactical errors found in the code, due to which program fails
to compile. For example, forgetting a semicolon at the end of a Java statement, or writing a
statement without proper syntax will result in compile time error.
Detecting and correcting compile-time errors is easy as the Java compiler displays the list of
errors with the line numbers along with their description. The programmer can go to the
statement check them word by word and line by line to understand where he has committed the
errors.
Run-time errors: These errors represent inefficiency of the computer system to execute
particular statement. For example, insufficient memory to store something or inability
microprocessor to execute some statement come under run-time errors.
Logical errors: These errors depict flaws in the logic of the program. The programmer is using a
wrong formula or the design of the program itself is wrong.
Exception
An exception is abnormal condition 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. Basically, an exception is a runtime error
The Exception Handling is one of the powerful mechanism to handle the runtime errors so that
the normal flow of the application can be maintained.
Common Java Exceptions

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 1


CHAPTER - 3

Types of Java Exceptions


There are mainly two types of exceptions:
1. Checked Exception (Compile time Exception)
A checked exception is an exception that is checked (notified) by the compiler at
compilation time; these are also called as compile time exceptions. For example,
IOException, SQLException, etc
2. Unchecked Exception (Run time Exception)
An unchecked exception is an exception that occurs at the time of execution (run time).
These are also called as Runtime Exceptions.
For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table describes
each.
Keyword Description
The "try" keyword is used to specify a block where we should place a code that
try might rise an exception. It means we can't use try block alone. The try block must be
followed by either catch or finally.
The "catch" block is used to handle the exception. It must be preceded by try block
catch which means we can't use catch block alone. It can be followed by finally block
later.
The "finally" block is used to execute the necessary code of the program. It is
finally
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an user defined exception.
The "throws" keyword is used to declare exceptions. It specifies that there may
throws occur an exception in the method. It doesn't throw an exception. It is always used
with method signature.

Syntax of Java try-catch


try
{
//code that may throw an exception
//Statements
}
catch(Exception_type e)
{
//Statements
}

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 2


CHAPTER - 3

Java try block is used to enclose the code that might throw an exception. It must be used
within the method. If an exception occurs at the particular statement in the try block, the
rest of the block code will not execute and control is transferred to catch block
Java catch block is used to handle the Exception by declaring the type of exception
within the parameter.
Example of Arithmetic Exception
public class Demo
{

public static void main(String[] args)


{
try
{
int a=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println("Devide by Zero"+e.getMessage());
}
System.out.println("rest of the code");
}

}
Example of ArrayIndexOutOfBoundsException
public class Demo
{

public static void main(String[] args)


{
try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Invalid Index"+e.getMessage());
}
System.out.println("rest of the code");
}

}
Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 3
CHAPTER - 3

Multiple Catch Blocks


A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler.
Points to remember
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
Syntax:
try
{
// Statement
}
catch (ExceptionType1 e1)
{
// Statement
}
catch (ExceptionType2 e2)
{
// Statement
}
catch (ExceptionType3 e3)
{
// Statement
}
Example
public class Demo
{

public static void main(String[] args)


{

try
{
int a[]=new int[5];

System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 4


CHAPTER - 3

System.out.println("ArrayIndexOutOfBounds
Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

Finally block
Java finally block is always executed whether an exception is handled or not. Therefore,
it contains all the necessary statements that need to be printed regardless of the exception
occurs or not.
Java finally block is a block used to execute important code such as closing the
connection, etc.
Syntax:
try
{
// Statement
}
catch (ExceptionType1 e1)
{
// Statement
}
finally
{
// Statement
}
OR
try
{
// Statement
}

finally
{
// Statement
}

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 5


CHAPTER - 3

Example
public class Test
{
public static void main(String args[])
{

try
{

System.out.println("Inside the try block");

//below code throws divide by zero exception


int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
finally
{
System.out.println("finally block is always executed");
}

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


}
}

User-defined Exceptions (Throwing our own exception)


You can create your own exceptions in Java and can be thrown using keyword “throw”.
Make your class to extend Exception class
public class TestThrow extends Exception
{
TestThrow(String msg)
{
super(msg);
}
//function to check if person is eligible to vote or not
public void validate(int age)
{
try
{
if(age<18)
{

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 6


CHAPTER - 3

throw new TestThrow("Person is not eligible to


vote");
}
else
{
System.out.println("Person is eligible to vote!!");
}
}
catch(TestThrow e)
{
System.out.println(e.getMessage());
}
}

public static void main(String args[]){


TestThrow t=new TestThrow();
t.validate(13);
System.out.println("rest of the code...");
}
}

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 7


CHAPTER - 3

GUI Basics
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavy weight i.e. its components are using the resources of
underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Java AWT Hierarchy

Components: All the elements like the button, text fields, scroll bars, etc. are called
components. In Java AWT, there are classes for each component as shown in above diagram. In
order to place every component in a particular position on a screen, we need to add them to a
container
Container: The Container is a component in AWT that can contain another components
like buttons, textfields, labels etc. 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.

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 8


CHAPTER - 3

GUI components
Buttons
A button is basically a control component with a label that generates an event when pushed. The
Button class is used to create a labeled button. The application result in some action when the
button is pushed.
Button Class Constructors
Following table shows the types of Button class constructors
Sr. no. Constructor Description
1. Button( ) It constructs a new button with an empty string i.e. it has no label.
2. Button(String text) It constructs a new button with given string as its label.

Example:
import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {
// create instance of frame with the label
Frame f = new Frame("Button Example");
// create instance of button with label
Button b = new Button("Click Here");
// set the position for the button in frame
b.setBounds(50,100,80,30);
// add button to the frame
f.add(b);
// set size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 9


CHAPTER - 3

Check Boxes
The Checkbox 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".
Checkbox Class Constructors
Sr. Constructor Description
no.
1. Checkbox() It constructs a checkbox with no string as the label.
2. Checkbox(String label) It constructs a checkbox with the given label.
3. Checkbox(String label, It constructs a checkbox with the given label and sets
boolean state) the given state.
Example:
import java.awt.*;
public class CheckboxExample1
{
// constructor to initialize
CheckboxExample1() {
// creating the frame with the title
Frame f = new Frame("Checkbox Example");
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
// setting location of checkbox in frame
checkbox2.setBounds(100, 150, 50, 50);
// adding checkboxes to frame
f.add(checkbox1);
Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 10
CHAPTER - 3

f.add(checkbox2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main (String args[])
{
CheckboxExample1 ck= new CheckboxExample1();
}
}
Output

Labels
The object of the Label class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by a programmer but a user cannot edit it
directly.
It is called a passive control as it does not create any event when it is accessed. To create a label,
we need to create the object of Label class.
Label class Constructors
Sr. Constructor Description
no.
1. Label() It constructs an empty label.
2. Label(String text) It constructs a label with the given string (left justified by
default).
3. Label(String text, int It constructs a label with the specified string and the
alignement) specified alignment.

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 11


CHAPTER - 3

Example:
import java.awt.*;

public class LabelExample {


public static void main(String args[]){
// creating the object of Frame class and Label class
Frame f = new Frame ("Label example");
Label l1, l2;
// initializing the labels
l1 = new Label ("First Label.");
l2 = new Label ("Second Label.");
// set the location of label
l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);
// adding labels to the frame
f.add(l1);
f.add(l2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 12


CHAPTER - 3

Text Fields
The object of a TextField class is a text component that allows a user to enter a single line text
and edit it. It inherits TextComponent class, which further inherits Component class.
TextField Class constructors
Sr. Constructor Description
no.
1. TextField() It constructs a new text field component.
2. TextField(String text) It constructs a new text field initialized with the given
string text to be displayed.
3. TextField(int columns) It constructs a new textfield (empty) with given number of
columns.
4. TextField(String text, int It constructs a new text field with the given text and given
columns) number of columns (width).
Example:
import java.awt.*;
public class TextFieldExample1 {
public static void main(String args[]) {
Frame f = new Frame("TextField Example");
TextField t1, t2;
t1 = new TextField("Welcome to KLE.");
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);
}
}

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 13


CHAPTER - 3

Text Areas
The object of a TextArea class is a multiline region that displays text. It allows the editing of
multiple line text. It inherits TextComponent class.
The text area allows us to type as much text as we want. When the text in the text area becomes
larger than the viewable area, the scroll bar appears automatically which helps us to scroll the
text up and down, or right and left.

TextArea Class constructors:


Sr. Constructor Description
no.
1. TextArea() It constructs a new and empty text area with no text in it.
2. TextArea (int row, int It constructs a new text area with specified number of
column) rows and columns and empty string as text.
3. TextArea (String text) It constructs a new text area and displays the specified
text in it.
4. TextArea (String text, int It constructs a new text area with the specified text in the
row, int column) text area and specified number of rows and columns.
5. TextArea (String text, int It construcst a new text area with specified text in text
row, int column, int area and specified number of rows and columns and
scrollbars) visibility.
Example:
//importing AWT class
import java.awt.*;
public class TextAreaExample
{
TextAreaExample() {
Frame f = new Frame();
TextArea area = new TextArea("Welcome to KLE");
area.setBounds(10, 30, 300, 300);
f.add(area);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 14


CHAPTER - 3

{
TextAreaExample t= new TextAreaExample();
}
}
List
The object of List class represents a list of text items. With the help of the List class, user can
choose either one item or multiple items. It inherits the Component class.
List Class Constructors
Sr. Constructor Description
no.
1. List() It constructs a new scrolling list.
2. List(int row_num) It constructs a new scrolling list initialized with the
given number of rows visible.
3. List(int row_num, Boolean It constructs a new scrolling list initialized which
multipleMode) displays the given number of rows.

import java.awt.*;

public class ListExample1


{
ListExample1() {
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");
l1.add("Item 4");
l1.add("Item 5");
f.add(l1);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 15


CHAPTER - 3

}
public static void main(String args[])
{
ListExample1 l= new ListExample1();
}
}

Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a GUI
component allows us to see invisible number of rows and columns.
It can be added to top-level container like Frame or a component like Panel. The Scrollbar class
extends the Component class.
Scrollbar Class Constructors
Sr. Constructor Description
no.
1 Scrollbar() Constructs a new vertical scroll bar.
2 Scrollbar(int orientation) Constructs a new scroll bar with the specified
orientation.
3 Scrollbar(int orientation, int Constructs a new scroll bar with the specified
value, int visible, int minimum, orientation, initial value, visible amount, and
int maximum) minimum and maximum values.

import java.awt.*;
public class ScrollbarExample1 {
ScrollbarExample1() {
Frame f = new Frame("Scrollbar Example");
Scrollbar s = new Scrollbar();
s.setBounds (100, 100, 50, 100);

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 16


CHAPTER - 3

f.add(s);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]) {
new ScrollbarExample1();
}
}

Layout Managers
The LayoutManagers are used to arrange components in a particular manner.
The Java LayoutManagers facilitates us to control the positioning and size of the
components in GUI forms. LayoutManager is an interface that is implemented by all the
classes of layout managers. There are the following classes that represent the layout
managers:
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
javax.swing.BoxLayout
javax.swing.GroupLayout
javax.swing.ScrollPaneLayout

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 17


CHAPTER - 3

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 a frame or
window.

The BorderLayout provides five constants for each region:


1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
BorderLayout(): creates a border layout but with no gaps between the components.
BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
import java.awt.*;
import javax.swing.*;
public class BorderLayoutExample
{
Frame frame;
// constructor
BorderLayoutExample()
{

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 18


CHAPTER - 3

frame = new Frame(); // creating a Frame


// create buttons
Button btn1 = new Button("NORTH");
Button btn2 = new Button("SOUTH");
Button btn3 = new Button("EAST");
Button btn4 = new Button("WEST");
Button btn5 = new Button("CENTER");
// creating an object of the BorderLayout class using the parameterized constructor where the
horizontal gap is 20 and vertical gap is 15. The gap will be evident when buttons are placed in
the frame
frame.setLayout(new BorderLayout(20, 15));
frame.add(btn1, BorderLayout.NORTH);
frame.add(btn2, BorderLayout.SOUTH);
frame.add(btn3, BorderLayout.EAST);
frame.add(btn4, BorderLayout.WEST);
frame.add(btn5, BorderLayout.CENTER);
frame.setSize(300,300);
frame.setVisible(true);
}
// main method
public static void main(String argvs[])
{
BorderLayoutExample bl= new BorderLayoutExample();
}
}
Output

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 19


CHAPTER - 3

Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.
Constructors of GridLayout class
GridLayout(): creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with the given rows and columns
but no gaps between the components.
GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given
rows and columns along with given horizontal and vertical gaps.
Example
import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
Frame f;
MyGridLayout(){
f=new Frame();
Button b1=new Button("1");
Button b2=new Button("2");
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");
// adding buttons to the frame
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);
// setting grid layout of 3 rows and 3 columns
f.setLayout(new GridLayout(3,3));

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 20


CHAPTER - 3

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
MyGridLayout m= new MyGridLayout();
}
}
Output

Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after another (in a
flow). It is the default layout of the 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
FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment
and the given horizontal and vertical gap.

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 21


CHAPTER - 3

import java.awt.*;
import javax.swing.*;
public class FlowLayoutExample
{
Frame frameObj;
// constructor
FlowLayoutExample()
{
// creating a frame object
frameObj = new Frame();
// creating the buttons
Button b1 = new Button("1");
Button b2 = new Button("2");
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");
Button b10 = new Button("10");
// adding the buttons to frame
frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b4);
frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.add(b8);
frameObj.add(b9); frameObj.add(b10);
frameObj.setLayout(new FlowLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 22


CHAPTER - 3

{
FlowLayoutExample fl=new FlowLayoutExample();
}
}

Event handling
What is an Event?
Change in the state of an object is known as event i.e. event describes the change in state of
source. Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page are the activities that causes an event to
happen.
Types of Event
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. For example, clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page etc.
Background Events - Those events that 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
It is a mechanism to control the events and to decide what should happen after an event occur.
To handle the events, Java follows the Delegation Event model.

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 23


CHAPTER - 3

+
Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to generate
events.
Listeners: Listeners are used for handling the events generated from the source. Each of these
listeners represents interfaces that are responsible for handling events.
The java.awt.event package provides many event classes and Listener interfaces for event
handling.

Event Classes Listener Interfaces

ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener

Following steps are required to perform event handling:


 Register the component with the Listener

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 24


CHAPTER - 3

Registration Methods
 Button
public void addActionListener(ActionListener a){}
 MenuItem
public void addActionListener(ActionListener a){}
 TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
 TextArea
public void addTextListener(TextListener a){}
 Checkbox
public void addItemListener(ItemListener a){}
 Choice
public void addItemListener(ItemListener a){}
 List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}

Mouse and key events


A user interacts with the application by pressing either keys on the keyboard or by using mouse.
A programmer should know which key the user has pressed on the keyboard or whether the
mouse is moved, pressed, or released. These are also called „events‟. Knowing these events will
enable the programmer to write his code according to the key pressed or mouse event.
Key Event
KeyListener interface of java.awt.event package helps to know which key is pressed or released
by the user. It has 3 methods
1. public void keyPressed(KeyEvent ke): This method is called when a key is pressed on the
keyboard. This include any key on the keyboard along with special keys like function keys, shift,
alter, caps lock, home, end etc.
2. public void keyTyped(keyEvent ke) : This method is called when a key is typed on the
keyboard. This is same as keyPressed() method but this method is called when general keys like
A to Z or 1 to 9 etc are typed. It cannot work with special keys.

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 25


CHAPTER - 3

3. public void keyReleased(KeyEvent ke): this method is called when a key is release.
KeyEvent class has the following methods to know which key is typed by the user.
1. char getKeyChar(): this method returns the key name (or character) related to the key pressed
or released.
2. int getKeyCode(): this method returns an integer number which is the value of the key presed
by the user.
Example:: Write the Keyboard Event Lab Program
MouseEvent
The user may click, release, drag, or move a mouse while interacting with the application. If the
programmer knows what the user has done, he can write the code according to the mouse events.
To trap the mouse events, MouseListener and MouseMotionListener interfaces of java.awt.event
package are use.
MouseListener interface has the following methods.
1. void mouseClicked(MouseEvent e); void MouseClicked this method is invoked when the
mouse button has been clicked(pressed and released) on a component.
2. void mouseEntered(MouseEvent e): this method is invoked when the mouse enters a
component.
3. void mouseExited(MouseEvent e): this method is invoked when the mouse exits a component
4. void mousePressed(MouseEvent e): this method is invoked when a mouse button has been
pressed on a component.
5. void mouseRelease(MouseEvent e): this method is invoked when a mouse button has been
released on component.
Example:: Write the Mouse Event Lab Program

Applet Programming
Applet is a small java program that is embedded in the webpage to generate the dynamic content.
It runs inside the browser and works at client side.
How Applets Differ from Applications?
Applets don‟t use the main() method, but when they are loaded, automatically call certain
methods (init, start, paint, stop, destroy).
Applet cannot be executed independently

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 26


CHAPTER - 3

They are embedded inside a web page and executed in browsers. They cannot read from
or write to the files on local computer.
They cannot communicate with other servers on the network.
They cannot run any programs from the local computer.
They are restricted from using libraries from other languages.
When to use applets ?
When we need something dynamic to be included in the display of a Web page.
When we require some “flash” outputs.
When we want to create a program and make it available on the Internet for us by others
on their computers.
Steps involved in developing and testing applet are :
Building an applet code (.java file)
Creating an executable applet (.class file)
Designing a Web page using HTML tags.
Preparing <APPLET> tag.
Incorporating <APPLET> tag into the Web page.
Creating HTML file.
Testing the applet code.

Applet Life Cycle


Every Java applet inherits a set of default behaviors from the Applet class. As a result when an
applet is loaded, it undergoes a series of changes in its state.
The applet states include:
Born or initialization state
Running state
Idle state
Dead or destroyed state

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 27


CHAPTER - 3

Initialization State:
Applet enters the initialization state when it is first loaded. This is achieved by calling the init()
method of Applet class. Applet is born.
At this stage, we can
Create objects needed by the applet
set up initial values
load images or fonts
set up colors
Called only once in the applet‟s life cycle.
To provide any of the above behavior, we must override the init() method:
public void init()
{
------Action-------
}

Running State:
Applet enters the running state when the system calls the start() method of Applet class.
This occurs automatically after the applet is initialized.

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 28


CHAPTER - 3

Unlike init() method, the start method may be called more than once.
We may override the start() method to control the applet.
public void start()
{
-------------
------------- (Action) •
}

Idle or Stopped State:


An applet becomes idle when it is stopped from running
Occurs automatically when we leave the page containing the currently running applet
We can achieve this by overriding the stop() method as:
public void stop()
{
-------------
------------- (Action)
}

Dead State:
An applet is said to be dead when it is removed from memory
Occurs automatically by invoking the destroy() method when we quit the browser.
Like initialization, destroying stage occurs only once in the applet‟s life cycle.
We may override the destroy() method as :
public void destroy()
{
-------------
------------- (Action)
}
Display State:
Applet moves to the display state whenever it has to perform some output operations on
the screen.
Happens immediately after the applet enters into the running state.
The paint() method is called to accomplish this task.
Almost every applet will have a paint() method.
We must override this method if we want anything to be displayed on the screen.
public void paint(Graphics g)
{

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 29


CHAPTER - 3

-------------
------------- (Action)
}
Java Applet Template
import java.awt.*;
import java.applet.*;
public class AppletName extends Applet
{
public void paint(Graphics graphics)
{
/* applet display statements go here. put display statements
here */
}
}
Example:
Applet Code
import java.applet.Applet;
import java.awt.Graphics;
public class HelloApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello world!", 50, 25);
}
}
javac HelloApplet.java
Adding Applet to HTML File with <applet> tag
<html>
<head>
<title>Passing Parameter</title>
</head>
<body>
<applet code="HelloApplet.class" width=400 height=300>
</applet>

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 30


CHAPTER - 3

</body>
</html>

To run an applet,
To run an applet we must define an <applet> tag inside the <body> tag of html, within our applet
program file. An applet program doesn't need a main() method to run, hence we run an applet
either in :
A browser, but remember, most of the modern versions of browsers are no longer
supporting applets. So, running an applet in a browser is not advisable, or
By using appletviewer utility which is provided with JDK. Due to inconsistency in the
execution of applets with some browsers, running an applet using appletviewer is the
most common approach these days and we will follow this approach throughout our
applets.
We can use it to run our applet as follows: appletviewer HelloApplet.html

Applet Tag with all attributes


< APPLET

CODE = appletFileName.class
WIDTH = pixels
HEIGHT = pixels
ALIGN = alignment (optional)
>
< PARAM NAME = AttributeName VALUE = AttributeValue>
</APPLET>
CODE: CODE is a required attribute that gives the name of the file containing your
applet‟s compiled .class file.
WIDTH AND HEIGHT: WIDTH and HEIGHT are required attributes that give the size
(in pixels) of the applet display area.
ALIGN: ALIGN is an optional attribute that specifies the alignment of the applet. This
attribute is treated the same as the HTML IMG tag with these possible values: LEFT,
RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and
ABSBOTTOM.

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 31


CHAPTER - 3

PARAM NAME AND VALUE: The PARAM tag allows you to specify applet specific
arguments in an HTML page. Applets access their attributes with the getParameter( )
method.
Passing parameters to Applets:
We can supply user-defined parameters to an applet using <PARAM…> tags.
Each <PARAM> tag has a name attribute such as color, and a value attribute such as red.
You can read the values passed through the PARAM tags with the getParameter() method
of the java.applet.Applet class.
Example:
import java.applet.*;
import java.awt.*;
public class Parameter extends Applet
{
String str="";
public void init()
{
str=getParameter("abc");

}
public void paint(Graphics g)
{
g.drawString(str,100,50);

}
}

<html>
<head>
<title>Passing Parameter</title>
</head>
<body>
<applet code="Parameter.class" width=400 height=300>
<param name="abc" value="Java">
</applet>

</body>
</html>

More About HTML tags


Important hrml tags and their functions shown below

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 32


CHAPTER - 3

Graphics in Applet
java.awt.Graphics class provides many methods for drawing different types of shapes.
Commonly used methods of Graphics class:

1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 33


CHAPTER - 3

7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver


observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.

Example of Graphics
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>

Prepared by: Chandrashekhar K, Asst. Prof, Dept. of BCA Page 34

You might also like