JAVA_UNIT_3

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

UNIT 3

1. Event and GUI programming


1.1. Event handling in Java
1.2. Event types
1.3. Mouse and key event
1.4. GUI basics
1.5. Panels
1.6. Frames
2. Layout managers
2.1. Flow layout
2.2. Border layout
2.3. Grid layout
2.4. GUI components like buttons
2.5. Check boxes
2.6. Radio buttons
2.7. Labels
2.8. Text fields
2.9. Text areas
2.10. Combo boxes
2.11. Lists
2.12. Scroll bars
2.13. Sliders
2.14. Windows
2.15. Menus
2.16. Dialog box
2.17. Applet and its life cycle
2.18. Introduction to swing
3. Exceptional handling mechanism. I/O programming
3.1. Text and binary I/O
3.2. Binary I/O classes
3.3. Object I/O
3.4. Random Access Files
UNIT 01. EVENT AND GUI PROGRAMMING
3

Event handling and GUI programming


Introduction
Graphical User Interface or simply called “GUI” is a general term used in the
software world. The user interact with application by clicking on some images
or graphics. For example, if the user wants to print a file, he can click on the
printer images and the rest of the things will be taken care of by the application.
▷ GUI is user friendly.
▷ A GUI represents an application that has a visual display for the user with
easy to use controls.
▷ A GUI generally consists of graphical components like windows, frames,
buttons, labels, etc..,
▷ It gives attraction and beauty to any application by adding pictures, colors,
menus, animation, etc..,
▷ It is possible to simulate a real life objects using GUI.

In java, all programming’s can be broadly classified into three categories;


a. the Core programming,
b. Applet Programming and
c. AWT Programming.

ABSTRACT WINDOW TOOLKIT (AWT)


Java AWT (Abstract Window Toolkit) is an API (Application Programming
Interface) to develop GUI or window-based application in java. Java AWT
components are platform-dependent i.e. components are displaying according to
the view of operating system.
AWT is heavyweight i.e. its components uses the resources of operating
system. The Abstract Window Toolkit (AWT) support for applets. The AWT
contains numerous classes and methods that allow us to create and manage
windows. The java.awt package provides classes for AWT API such as Text Field,
Button, Label, Text Area, Radio Button, Check Box, Choice, List etc…,
Features of AWT
AWT has a set of native user interface components.
It provides various classes for graphical representations of components.
It provides a robust event-handling model.
It has layout managers which provide a well-organized look to the
application.
It provides a large range of libraries that can be used for designing GUI
applications.

AWT User Interface Aspects


The AWT UI is designed using the following aspects:
1. Elements of UI
These are the elements that are visible to the user and using those elements
the user can communicate with the application. AWT provides a wide range
of UI elements.

2. Layouts
Layouts are useful for managing the different UI elements on the screen and
provide a well-organized look to the application.

3. Behavior
It explains how the UI elements act on triggering events performed by the
user.

Java AWT Hierarchy


As shown in the above figure the root AWT component ‘Component’
extends from the ‘Object’ class. The component class is the parent of the other
components including Label, Button, List, Checkbox, Choice, Container, etc..,

1. Component
In the AWT class hierarchy, the component class is derived from the
Object class. Component class is an abstract class. It is superclass of all the
GUI element classes like container, button, label, checkbox, choice and list.
Therefore, component class is responsible for an overall graphical interface.
The component class encapsulates the visual component properties and
attributes.

A component represents an object which is displayed pictorially on the


screen. For example, we create an object of button class as:

Button b = new Button;

2. Container
A container in AWT is a component, which holds all the other components
used for building the interface. Container can contain other components like
text, labels, buttons, tables, lists, etc. The container keeps a tab on other
components that are added to the GUI. We can insert another container inside
the main container.

There are four types of container available in AWT:


2.1. Window
A window is a rectangular box shaped area displayed on the screen. It is
an instance of window class. It does not have any menu bar, toolbar, or
border. It should always be placed inside another window, frame, or
dialog.

2.2. Frame
A frame is a subclass of window. It has a border, menu bar, title bar. The
size of the frame can also be changed. It can hold all other AWT
components like buttons, checkboxes, etc. frames are the most widely
used type of AWT container.
2.3. Dialog
Dialog is a subclass of window. It contains a border and title bar. To
create a dialog object, an instance of the associated frame class is
always needed.

2.4. Panel
A panel is a subclass of container. The panel does not have border, title
bar, or menu bar. It is a generic container that holds other GUI
components. An instance of panel class is necessary in order to insert
the components.

3. Button
The button class allows the developer to create a button with an appropriate
label on it. It also provides a way to define functionality after clicking the
button. An event is generated when button is clicked.

4. List
A list class is used to display a list of required items. Using a list, the user can
select one or multiple items in it.

5. Checkbox
A checkbox can be used when an application wants the user to choose from
either true or false. It is used to provide options. When clicked, it changes the
state of the checkbox from ‘on’ to ‘off’ or vice-versa.

6. Label
As the name suggests, it is used as a label, or a method to display text on the
screen. The user cannot change the content of a label. It represents a read-
only text. A label provides descriptive text information on the application
window. It is placed inside a container.

7. Choice
A choice class is used to display a drop- down menu. The selected choice can
be seen on the head.

8. TextField
It is used to take single-line text input from the user. It can also be used to
display editable text. Unlike a label, which provides read- only text, the text
in the text field can be edited by the user.
9. TextArea
It allows the display of multiple lines of text. It provides ‘an area’ where text
can be displayed and also edited by the user.

The component class is an abstract class and hence we cannot use new
component() to create an instance of component. However, we can use the
constructors of concrete subclasses of component to create component
instances.

Example:

i) To create a button, we can use


Button b=new Button();
ii) To create a label, we can use
Label l=new Label();

USEFUL METHODS OF COMPONENT CLASS:


METHOD DESCRIPTION
public void add(component c) It adds a component to the container
public void setSize(int width, It sets the size(width and height) of the
int height) component
public void it sets the layout manager for the
setLayout(LayoutManagerm) component
public void setVisible(boolean It changes the visibility of the
status) component, by default false.

Containers are integral part of AWT GUI components. A container provides a


space where a component can be located. A container in AWT is a component
itself and it adds the capability to dd component to itself. Following are
noticeable points to be considered.

• An instance of container can hold instances of component.


• Container classes are GUI components that are used to contain other GUI
components.
• Window, panel, applet, frame, and dialog are the container classes for AWT
components.
• To work with components, we use container.
• Container can add only component to itself.
• A default layout is present in each container which can be overridden using
setLayout method.

Container class Description


java.awt.container It is used to group components. Frames, panels, and
applets are its subclasses.
java.awt.frame The frame is the container that contain title bar and
border and can have menu bars.it can have other
components like button, text field, scrollbar etc.
frame is most widely used container while
developing an AWT application.
java.awt.panel The panel is a simplest container class. It provides
space in which an application can attach any other
component. It inherits the container class. It doesn’t
have title bar. It is an invisible container that holds
user-interface components. Panels can be nested.
We can place panels inside a container that includes
a panel. Panel is also often used as a canvas to draw
graphics.
java.awt.dialog It is a popup window or message box generally used
as a temporary window to receive additional
information from the user or to provide notification
that an event has occurred.
java.awt.window A window object is a top-level window with no
borders and no menu bar. The default layout for a
window is BorderLayout.A window must have either
a frame, dialog, or another window defined as its
owner when it’s constructed.

The helper classes, such as Graphics, color, font, fontMetrics, dimension, and
LayoutManager, are not subclasses of component. They are used to describe the
properties of GUI components, such as graphics context, colors, fonts, and
dimension, as described in below table:
Helper class Description
java.awt.Graphics It is an abstract class that provides the methods
for drawing strings, lines, and simple shapes.
java.awt.Color It deals with the colors of GUI components. For
example, we can specify background or
foreground colors in components like frame and
panel, or we can specify colors of lines, shapes,
and strings in drawings.
java.awt.Font It specifies fonts for the text and drawings on GUI
components. For example, we can specify the
font type (e.g., SansSerif), style (e.g., bold), and
size (e.g., 24 points) for the text on a button.
java.awt.FontMetrics It is an abstract class used to get the properties
of the fonts.
java.awt.Dimension It encapsulates the width and height of a
component (in integer precision) in a single
object.
java.awt.LayoutManager It specifies how components are arranged in a
container.

The frame is a subclass of window. It has a border, title bar, and menu bar.
Frame is a container which is used to hold components in it. Components such
as a button, checkbox, radio button, menu, list, table, etc.

Constructors of the frame class:

Constructor Description
Frame() Creates a new frame object.
Frame(String name) Creates a new frame with a name passes as a title of
the frame.

Methods of frame class:

Method Description
void setTitle(String t) Changes the title of the frame with the
new title specified.
public void add(component comp) This method adds the component, comp,
to the container frame.
public void setLayout(LayoutManager This method sets the layout of the
object)
components in a container, frame.
public void remove(component comp) This method removes a component,
comp, from the container, frame.
public void setSize(int widthPixel, This method sets the sizeof a frame in
int heightPixel)
terms of pixels.

When working with frame objects, the following steps are basically followed
to get a window to appear on the screen.

1. Create an object of type frame.


2. Give the frame object a size using setSize() method.
3. Make the frame object appear on the screen by calling setVisible() method.

There are two ways to create a frame. They are,


1. By instantiating frame class.
2. By extending frame class.

//program to creating a frame by By instantiating

frame class.
import java.awt.*;
public class FrameDemo
{
FrameDemo()
{
Frame fm = new Frame();
fm.setTitle(“My First Frame”);
Label lb=new Label (“welcome to GUI Programming”);
fm.add(lb);
fm.setSize(300,300);
fm.setVisible(true);
}
public static void main(String args[])
{
FrameDemo ta= new FRameDemo();
}
}
//program to creating a frame by extending the frame class

import java.awt.*;
public class FrameDemo extends Frame
{
public FrameDemo()
{
Button btn= new Button(“submit”);
add(btn);
setSize(250,250);
setTitle(“my frame”);
setVisible(true);
}
public static void main(String args[])
{
FrameDemo ta=new FrameDemo();
}
}

An AWT panel in java can act as a container and a component. A container can
hold components like Buttons. For example, a frame window in AWT is a
container which can accommodate or add components. Unlike frame window,
the panel does not have the title and borders. However, one can assign a layout
manager to a panel.

Constructors of panel class:


Constructor Description
Panel() Constructs a new panel using FlowLayout.
Panel(LayoutManager lm) Constructs a new panel with the mentioned
layout.

Methods of panel class:


Method Description
public void add (component comp) This method adds the component,
comp, to the container panel.
public voidsetLayout(LayoutManager This method sets the layout of the
object) components in a container, panel.
public void remove(component comp) This method removes a
component, comp, from the
container, panel.
public void removeAll() This method removes all the
components of the container.
Public void add(component comp, This method adds the specified
int n) component to the container in
position indicated.

//program to creating a panel inside a frame.


import java.awt.*;
class SamplePanel extends Frame
{
SamplePanel()
{
setLayout(new FlowLayout());
Panel p1=new Panel();
Label lb1=new Label(“panel 1 red”);
p1.add(lb1);
Button bt1=new Button(“button 1”);
p1.add(bt1);
p1.setBackground(color.red);
add(p1);
Panel p2=new Panel();
Label lb2-=new Label(“panel 2 blue”);
p2.add(lb2);
Button bt2=new Button(“button 2”);
p2.add(bt2);
p2.setBackground(color. blue);
add(p2);
}
}
public class PanelDemo
{
public static void main(String args[])
SamplePanel fr=new SamplePanel();
fr.setTitle(“panel example”);
fr.setSize(300,250);
fr.setVisible(true);
}
UNIT 02. Layout managers
3

Layout Managers
In many other window systems, the user- interface components are arranged by
using hardcoded pixel measurements. For example, put a button at location
(10, 10) in the window. Using hard-coded pixel measurements, the user interface
might look fine on one system but be unusable on another.

A layout is a way in which parts of components are arranged; components can


be anything from text to images, etc. the arrangement of components in a
particular position within the container is called Layout

Flow layout
Flow layout is the simplest layout manager. The components are arranged in the
container from left to right in the order in which they were added. When one
row is filled, a new row is started.

According to this layout, the container will be divided int rows and columns
depending upon the components and their size. The components would be added
row- wise i.e., first row column-1, column-2, etc., if the row is filled, then the
next component would be added to first column of second row and so on.

The constructors for flowlayout:


Constructor Description
FlowLayout() The first creates the default layout, which
centers components and leaves five pixels of
space between each component.
FlowLayout(int align) It specify how each line should be aligned. Valid
values for align are as follows:
FlowLayout. RIGHT,
FlowLayout. CENTER,
FlowLayout. LEFT,
FlowLayout. LEADING and FLOWLAYOUT.
TRAILING
These values specify left, center, right, leading
edge, and trailing edge alignment, respectively.
FlowLayout(int align, This allows to specify the horizontal and
int hgap, int vgap) vertical space left between components in hgap
and vgap, respectively.

//program to flow layout demonstration.

import java.awt.*;
public class FlowLayoutDemo()
{
FlowLayoutDemo()
{
Frame f=new Frame();
Label l1=new Label(“enter name:”);
TextField t1=new TextField(10);
Label l2=new Label(“enter age:”);
TextField t2=new TextField(10);
Button b1=new Button(“submit”);
f.add(l1);
f.add(t1);
f.add(12);
f.add(t2);
f.add(b1);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
f.setSize(250,250);
f.setVisible(true);
}
public static void main(String[] args)
{
FlowLayoutDemo fl=new FlowLayoutDemo();
}
}
Output:

• The BorderLayout manager divides the window container in five regions i.e.
east, west, north, south and center.
• It is used to add the component at specified region.
• Components of the BorderLayout Manager
BorderLayout.NORTH
BorderLayout.EAST
BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.WEST

Constructor Description
BorderLayout() It is used to create a new border layout with no
gaps between components.
BorderLayout(int hgap, It is used to construct a border layout with the
int vgap) specified gaps between components.
//program BorderLayout Demonstration
import java.awt.*;
public class BorderLayoutDemo
{
BorderLayoutDemo()
{
Frame frame= new Frame(“Border Layout”);
Button b1=new Button(“north”);
Button b2=new Button(“south”);Button b3=new
Button(“east”);
Button b4=new Button(“west”);
Button b5=new Button(“middle”);
frame.add(b1, BorderLayout.NORTH);
frame.add(b2, BorderLayout.SOUTH);
frame.add(b3, BorderLayout.EAST);
frame.add(b4, BorderLayout.WEST);
frame.add(b5, BorderLayout.CENTER);
frame.setSize(250.250);
frame.setVisible(true);
}
public static void main(String args[])
{
BorderLayoutDemo bl=new BorderLayoutDemo();
}
}

GridLayout
• The container will be divided into specific number of rows and columns of
equal size. Each division is called a cell or a grid.
• In the Grid Layout, only one component can be added to a grid and the
component occupies the entire grid.
Constructor Description
GridLayout() Creates a grid layout with a default of one
column per component in a single row.
GridLayout(int rows, Creates a grid layout with the specified number
int cols) of row and column.
GridLayout(int rows, Constructed a grid layout with the specified
int cols, int hgap, int number of rows and columns along with given
vgap) horizontal and vertical gaps.

//program to Grid Layout demonstration.

import java.awt.*;
public class GridDemo
{
Frame frame=new Frame(“GridLayoutDemo”);
Button b1=new Button(“A”);Button b2=new Button(“B”);
Button b3=new Button(“C”);
Button b4=new Button(“D”);
Button b5=new Button(“E”);
Button b6=new Button(“F”);
frame.add(b1);
frame.add(b2);
frame.add(b3);
frame.add(b4);
frame.add(b5);
frame.add(b6);
frame.setLayout(new GridLayout(2,3));
frame.setSize(200,200);
frame.setVisible(true);
}
public static void main(String args[])
{
GridDemo gd=new GridDemo();
}
}

EVENT HANDLING

Events are divided into two major categories:


o Foreground events
These events necessitate the user’s direct participation. They are produced as
a result of a user interacting with graphical components in a graphical user
interface. For example, clicking a button, moving the mouse, typing q
character, closing a frame etc.,

o Background events
Background events are those that require end-user interaction. Operating
system interrupts and hardware or software failure are examples of
background events.

Event handling in java is the process of controlling an event and taking


appropriate action if one occurs.
COMPONENTS OF EVENT HANDLING
Event handling has three main components,
o Events
An event is a change in state of an object. When we press a button, the state
of the button changes from ‘unclicked’ and ‘clicked’. This change in the state
of a button is called an event.

o Events source
Event source is an object that generates an event. In java, nearly everything
is an object. The button is an object too. Source is the object generates an
event.

o Event listeners
A listener is an object that listens to the event. A listener gets notified when
an event occurs. Listener are also called as event handlers as they are the ones
responsible to handle events occurring at the source.

E VENT DELEGATION MODEL


The specialty of delegation event model is that the GUI component passes the
event processing part to a completely separate set of code.

The image below shows the flow chart of the event delegation model.
Steps involved in the event delegation model are:
Step 1: We should attach an appropriate listener to a component. This is done
using addxxxListener() method. Similarly, to remove a listener from a
component, we can use removexxxListener () method.

Step 2: Implement the methods of the listener, especially the method which
handles the event.

Step 3: When an event is generated on the component, then the method in step2
will be executed and the event is handled.

IMPORTANT EVENT CLASSES AND INTERFACE


Event classes Description Listener interface
ActionEvent When a button is clicked or ActionListener
a list item is double-clicked,
an ActionEvent is triggered.
MouseEvent This event indicates a MouseListener
mouse action occurred in a
component
KeyEvent The key event is triggered KeyListener
when the character is
entered using the keyboard
ItemEvent When the value of a text TextListener
area or text field is changed
MouseWheelEvent Generated when the mouse MouseWheelListener
wheel is rotated
WindowEvent When a component is ComponentEventListener
hidden, moved, resized, or
made visible
ContainerEvent When the scroll bar is AdjustmentListener
manipulated
FocusEvent When a component gains or FocusListener
loses keyboard focus
//program to demonstrate window closing event

import java.awt.*;
import java.awt.event.*;
public class MyFrame extends Frame
{
public static void main(String args[])
{
MyFrame f=new MyFrame();
f.setTitle (“My Frame”);
f.setSize (400,250);
f.setVisible (true);
f.addWindowListener (new MyClass());
}
}
class MyClass implements WindowListener
{
public void windowActivated (WindowEvent e)
{
}
public void windowClosed (WindowEvent e)
{
}
public void windowClosing(WindowEvent e)
{
}
System.exit (0);
}

public void windowDeactivated (WindowEvent e)


{
}
public void windowIconified (WindowEvent e)
{
}
public void windowDeiconfied (WindowEvent e)
{
}
public void windowOpened (WindowEvent e)
{
}
}

Mouse events
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 used.

MouseListener interface has the following methods.


• Void mouseClicked (MouseEvent e)
This method is invoked when the mouse button has been clicked (pressed and
released) on a component.

• Void mouseEntered (MouseEvent e)


This method is invoked when the mouse enters a component.

• Void mouseExited (MouseEvent e)


This method is invoked when the mouse exits a component.

• Void mousePressed (MouseEvent e)


This method is invoked when a mouse button has been pressed on a
component.

• Void mouseRelease (MouseEvent e)


This method is invoked when a mouse button has been released on a
component.

MouseMotionListener interface has the following methods.


1. void mouseDragged (MouseEvent e)
This method is invoked when a mouse button is pressed on a component and
then dragged.
2. void mouseMoved (MouseEvent e)
This method is invoked when a mouse cursor has been moved onto a
component and then dragged.

The MouseEvent class has the following methods

1. int getButton ()
This method returns a value representing a mouse button, when it is clicked
it return 1 if left button is clicked, 2 if middle button, and 3 if right button is
clicked.
2. int getX ()
This method returns the horizontal x position of the event relative to the
source component.
3. int getY ()
This method returns the vertical y position of the event relative to the source
component.

//program to show the use of Mouse Events Demo

import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MouseListenerExample implements MouseListener
{
Label lbl1, lbl2;
Frame fr;
String s;
MouseListenerExample()
{
fr=new Frame (“java mouse listener example”);
lbl1=new Label (“demo for the mouse event”,
Label.CENTER);
lbl2= new Label ();
fr.setLayout (new FlowLayout ());
fr.add (lbl1);
fr.add(lbl2);
fr.addMouseListener (this);
fr.setSize (250,250);
fr.setVisibile (true);
}
public void mouseClicked(MouseEvent ev)
{
lbl2.setText(“Mouse button Clicked”);
fr.setVisible (true);
}
public void mouseEntered(MouseEvent ev)
{
lbl2.setText(“mouse has entered the area of window”);
fr.setVisible(true);
}
public void mouseExited( MouseEvent ev)
{
1b12.setText("Mouse has left the area of window");
fr.setVisible(true);
}
public void mousePressed (MouseEvent ev)
{
1b12.setText("Mouse button is being pressed");
fr.setVisible(true);
}
public void mouseReleased (MouseEvent ev)
{
1b12.setText (" Mouse Released");
fr.setVisible(true);
}
public static void main(String args[])
{
MouseListenerExample ml= new MouseListenerExample();
}
}

Key Events
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.

3. public void keyReleased(keyEvent ke)


This method is called when a key is released.

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 pressed
by the user
//Program Key Events Demo

import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements
KeyListener
{
Label lbl;
TextArea ta;KeyListenerExample()
{
1b1 = new Label();
Lbl.setBounds (20, 50, 100, 20);
ta= new TextArea();
ta setBounds (20, 80, 300, 300);
ta addkeyListener(this);
add(lbl);
add(ta);
setSize (350, 350);
setLayout (null);
setVisible (true);
}
public void keyPressed(KeyEvent e)
{
lbl.setText (“key Pressed");
}
public void keyReleased (KeyEvent e)
{
lbl.setText("Key Released");
}
public void keyTyped (KeyEvent e)
{
lbl.setText("Key Typed");
}
public static void main(String[] args)
{
new KeyListenerExample();
}
}

GUI Components or AWT Controls

The various AWT components are Label, Button, CheckBox, CheckBox Group,
List, Text Field, Text Area, Choice, Canvas, Image, Scrollbar, Dialog. File Dialog,
etc that creates or draw various components on web and manage the GUI based
application.

Label
• A label is a GUI control which can be used to display static text. Label can be
created using the Label class.
• The easiest control to use is a label. A label contains a string and is an object
of type Label. Labels are passive controls that do not support any interaction
with the user.
• Only single line text is allowed and the text can not be changed directly.
• Example:
Label n-new Label("Name:");
Label n=new Label("Age:", Label CENTER);
The second parameter specifies the text alignment. Valid values are Label.LEFT,
Label.CENTER or Label.RIGHT

//Program Labels Demo

import java.awt.*;
public class LabelDemo
{
public static void main(String args[])
{
Frame fr = new Frame("Label Demo");
Label lab1, lab2, lab3;
lab1 = new Label("Java Programming", Label.CENTER);
lab1.setBounds(50, 50, 200, 30);
lab2 = new Label("Database Management Systems");
lab2.setBounds(50, 100, 200, 30);
lab3 = new Label("Computer Architecture", Label.RIGHT);
lab3.setBounds(50, 150, 200, 30);
fr.add(lab1);
fr.add(lab2);
fr.add(lab3);
fr.setSize(300, 300);
fr.setLayout(null);fr.setVisible(true);
}
}

Output:
Button
• The button class is used to create a labeled button that has platform
independent implementation. The application result in some action when the
button is pushed.
• A push button or a button can be created by using the

Button class and its constructors which are given below:


Button()
Button(String str)

Example of Creating Button:


Button b = new Button(String label);

// Program Create a button and add it to the frame by providing


coordinates

import java.awt.";
public class ButtonDemo1
{
public static void main(String[] args)
{
Frame f1 = new Frame("Button Demo");
Button b1 = new Button("Press Here");
b1.setBounds(50, 100, 80, 50);
f1.add(b1);
f1.setSize(200, 200);
f1.setLayout(null);
f1.setVisible(true);
}
}
Text Field
A text field or text box is a single line text entry control which allows the
user to enter a single line of text. It inherits TextComponent class.

A text field can be created using the TextField class along with its
following constructors:
TextField ()
TextField (int numChars)
TextField (String str)
TextField (String str, int numChars)

Example of Creating TextField:


TextField tf =new TextField(size);

//Program that we are creating two textfields to display single line text
string. This text is editable in nature. See the below example

import java.awt.*;
public class TextFieldDemo
{
public static void main(String args[])
{
Frame fr = new Frame("TextField Demo");
TextField text1, text2;
text1 = new TextField("Enter Your Name...");
text1.setBounds(60, 100, 150, 40);
text2 =new TextField("Enter Your Age...");
text2.setBounds(60, 150, 150, 40);
fr.add(text1);fr.add(text2);
fr.setSize(250, 250);
fr.setLayout(null);
fr.setVisible(true);
}
}
Text Area
• A TextArea class is used for displaying multiple line text. It is a multiline
region that displays text. It allows the editing of multiple line text. It inherits
TextComponent class.
• example of Creating TextArea:
TextArea ta = new TextArea("Type Here", 5, 50, 3);

//program we are creating a TextArea that is used to display multiple-


line text string and allows text editing as well.

import java.awt.*;
public class TextAreaDemo
{
TextAreaDemo()
{
Frame fr= new Frame();
TextArea ta = new TextArea("Type Here");ta.setBounds
(30, 40, 100, 100);
fr.add(ta);
fr.setSize(250, 250);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
TextAreaDemo td=new TextAreaDemo();
}
}

Check Box
• The Checkbox class is used to create a checkbox. It is used to turn an option
on (true) or off (false). When the checkbox is checked then its state is "on"
(true) else it is "off" (false).
• It is used when we want to select only one option Le true or false.)
• Example of Creating Checkbox:
Checkbox cb= new Checkbox (Label);

//Program we are creating checkbox that are used to get user input.
If checkbox is checked it returns true else returns false.

import java.awt.*;
public class CheckboxDemo
{
CheckboxDemo ()
{
Frame checkB_f = new Frame ("Checkbox Demo");
Checkbox ckbox1 = new Checkbox ("Yes", true);
ckbox1.setBounds(100, 180, 60, 60);
Checkbox ckbox2 = new Checkbox("No");
ckbox2.setBounds (100, 150, 60, 60);
checkB_f.add(ckbox1);
checkB_f.add(ckbox2);
checkB_f.setSize (300, 300);
checkB_f.setLayout (null);
checkB_f.setVisible (true);
}
public static void main(String args[])
{
CheckboxDemo cd= new CheckboxDemo();
}
}
Radio Button
• A CheckboxGroup Class is used to group a set of Checkboxes. When
Checkboxes are grouped then only one box can be checked at a time. At a time
only one check box button is allowed to be in "on" state and remaining check
box button in "off" state. It inherits the object class.
• Example of Creating Radio Button:
CheckboxGroup cbg= new CheckboxGroup ();
Checkbox rb = new Checkbox (Label, cbg, boolean);

//Program this example creates a checkboxgroup that is used to group


multiple checkbox in single unit. It is helpful when we have to select
single choice among the multiples.

import java.awt.*;
public class CheckboxGroupDemo
{
CheckboxGroupDemo ()
{
Frame fr= new Frame("CheckboxGroup Demo");
CheckboxGroup cbg= new CheckboxGroup();
Checkbox ckBox1 = new Checkbox("Java", cbg, true);
ckBox1.setBounds (100, 100, 50, 50);
Checkbox ckBox2 = new Checkbox("C", cbg,
false);ckBox2.setBounds (100, 150, 50, 50);
fr.add(ckBox1);
fr.add(ckBox2);
fr.setSize(300, 300);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
CheckboxGroupDemo cg=new CheckboxGroupDemo();
}
}
Output

Combo Box
• A drop down box or a combo box contains a list of items (strings). When a
user clicks on a drop down box, it pops up a list of items from which user can
select a single item. When a user selects a particular item from the drop-down
then it is shown on the top of the menu.
• Example of Creating Choice:
Choice ch = new Choice();

//Program in this example, we are creating drop-down menu that is used


to get user choice from multiple choices.

import java.awt.*;
public class ChoiceDemo
{
ChoiceDemo()
{
Frame fr = new Frame();
Choice ch= new Choice();
ch.setBounds (80, 80, 100, 100);
ch.add("BCA");
ch.add("BCom");
ch.add("BBA");ch.add("BA");
ch.add("BHM");
ch.add("BSc");
fr.add(ch);
fr.setSize(300, 100);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
ChoiceDemo cd=new ChoiceDemo();
}
}

Lists
• A List Class is used to represent a list of items together. One or more than one
item can be selected from the list. More than one items in the list box are
visible to the user.
• Example of Creating List:
List l=new List(int, Boolean);

//Program in this example, we are creating a list that is used to list


out the items

import java.awt.*;
public class ListDemo;
{
ListDemo()
{
Frame fr new Frame("List Demo");
List 1st =new List (6, true);
1st.setBounds(80, 80, 100, 100);
1st.add("C");
1st.add("C++");
1st.add("Java");
1st.add("Python");
1st.add("C#");
1st.add("PHP");
fr.add(1st);
fr.setSize(300, 300);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
ListDemo ld=new ListDemo();
}
}

Scroll Bars
• The Scrollbar is a GUI component that allows us to see an invisible number of
rows and columns. The object of the Scrollbar class can add a horizontal
scrollbar and a vertical Scrollbar.
• A Scrollbar can be added to a top-level container like Frame or a component
like Panel. It is used to create a horizontal and vertical Scrollbar.
• Example of Creating Scrollbar:
Scrollbar sb = new Scrollbar();

//Program we create a scrollbar using the Scrollbar () and add it to the


Frame

import java.awt.*;
public class ScrollbarExample
{
ScrollbarExample()
{
Frame f = new Frame("Scrollbar Example");
Scrollbar s= new Scrollbar();
s.setBounds(100, 100, 50, 100);
f.add(s);
f.setSize(300, 300);
f.setLayout(null);f.setVisible(true);
}
public static void main(String args
{
ScrollbarExample se= new ScrollbarExample();
}
}

Menus
• The MenuItem class adds a simple labeled menu item on menu. The items
used in a menu must belong to the MenuItem or any of its subclass. The Menu
class is a pull down menu. Component which is displayed on the menu bar. It
inherits the MenuItem class.
• The following statements create a menu bar and add it to the top of the frame.
Menubar menuBar = new MenuBar();
setMenubar (menuBar);
These statements are part of the class that extends Frame.

//Program in this example, we are creating a menu item that contains


sub menu as well. We use MenuItem and Menu class for creating menu

import java.awt.*;
public class MenuDemo
{
MenuDemo()
{
Frame fr= new Frame("Menu Demo");
MenuBar mb= new MenuBar();
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
Menu viewMenu = new Menu(“view”);
mb.add(fileMenu);
mb.add(editMenu);
mb.add(viewMenu);
MenuItem a1= new MenuItem("New");
MenuItem a2 = new MenuItem("Open");
MenuItem a3 = new MenuItem("Save");
MenuItem b1= new MenuItem("Copy");
MenuItem b2 = new MenuItem("Find");
MenuItem c1 = new MenuItem("Show");
fileMenu.add(a1);
fileMenu.add(a2);
fileMenu.add(a3);
editMenu.add(b1);
editMenu.add(b2);
viewMenu.add(c1);fr.setMenuBar (mb);
fr.setSize(300, 300);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
MenuDemo md= new MenuDemo();
}
}

Dialog Box
• In Java, AWT contains a Dialog. It is a type of window which is having a border
and a title. But it does not have any maximize and minimize button.
• There are two kinds of Dialog Window.
Modal Dialog window: When a modal dialog window is active, all the user
inputs are directed to it and all the other parts of application are
inaccessible until this Modal dialog is closed.
Modeless Dialog window: When a modeless dialog window is active, the
other parts of application are still accessible as normal and inputs can be
directed to them, without needing to close this modeless dialog window.
//Program in this example, we are creating a dialogue box. The dialogue
box is used to provide information to the user.

import java.awt.*;
import java.awt.event.*;
public class DialogDemo extends WindowAdapter implements
ActionListener
{
Frame frame;
Label label1;
TextField field1;
Button button1, button2, button3;
Dialog d1, d2, d3;
DialogDemo()
{
frame = new Frame("Frame");
button1 = new Button("Open Modal Dialog");
label1 =new Label("Click on the button to open a Modal
Dialog");
frame.add(label1);
frame.add(button1);
button1.addActionListener(this);
frame.pack();
frame.setLayout(new FlowLayout());
frame.setSize(350,350);
frame.setVisible(true);
}
public void actionPerformed (ActionEvent ae)
{
if (ae.getActionCommand().equals("Open Modal Dialog"))
{
d1 = new Dialog (frame, "Modal Dialog", true);
Label label = new Label("You must close this
dialog window to use Frame window", Label.CENTER);
d1.add(label);
d1.addWindowListener(this);
d1.pack();
d1.setLocationRelativeTo(frame);
d1.setLocation(new Point (100, 100));
d1.setSize(400, 200);
d1.setVisible(true);
}
public void windowClosing (WindowEvent we)
{
d1.setVisible(false);
}
public static void main(String args[])
{
DialogDemo d= new DialogDemo();
}
}

APPLET PROGRAMMING
APPLET
It is a small that is embedded with html program, which is accessed
and transported over the internet, automatically installed into client
machines and run as apart of webpage.

Applet life cycle

The applet life cycle is basically used 4 important methods: -


• init() • stop()
• start () • destroy()
1. init() method
This is a first method of applet program. It is used to initialize the tasks of
an applet such as images, fonts and other setting parameters.

Syntax:
public void init ()
{
………………
………………
}

2. start() method
After init() it should be declared start () method because this method
is automatically called to begin the execution of the applet like any
calculation and processing of the data should be done in this method.

Syntax:
public void start()
{
………………
………………
}

3. stop() method
This method is called by the browser when an applet is to be stopped and
also implement the method to stop any operations which started in stop().

Syntax:
public void stop ()
{
………………
………………
}
4. destroy() method
This method is called when an applet is being terminated from memory. The
stop() method will always call before destroy(). It is completely dead
whatever it is started of the applet and takes care of garbage and memory
allocation.

Syntax:
public void destroy()
{
………………
………………
}

5. paint() method
It is not a part of applet life cycle but it is used to display the output
operations on the screen and also is the graphics tools such as buttons,
textboxes, text shapes and images etc.

Syntax:
public void paint(Graphics g)
{
………………
………………
}

//Program to show the use of Applet

import java.applet.Applet;
import java.awt.Graphics;
public class Myapplet extends Applet
{
public void paint(Graphics g)
{
g. drawString("Welcome to Applet programming",20,20);
}
}
<html>
<head>
<title>Applet programming</title>
<body>
<applet code="Myapplet.class" width=200 height=200>
</applet>
</body
</head>
</html>

DIFFERENCE BETWEEN APPLETS AND APPLICATIONS:


APPLETS APPLICATIONS
1. Applet do not have main() method 1. Applications can have main() method
2. Applet runs under the java 2. Applications independently executed
compatible containers such as web
browsers
3. Applet program executed and run by 3. The program is executed from java
applet viewer interpreters
4. Applet is restricted not to utilize 4. Applications can use network
network resources resources very easily
5. Applet can be embedded into HTML 5. Applications cannot be embedded
pages. into HTML pages
6. Applet cannot run in local computers 6. Applications can run in local
computers
7. The library methods cannot use from 7. Applications can use libraries from
other languages other languages

Applet Tag
Applet is an html tag. This tag is helpful for the applet programs embedded with
html programming.

Syntax:
<applet code =”Filename.class ALT =” alternate text” WIDTH =”
pixels” HEIGHT =”pixels” ALIGN =”alignment” VSPACE =”pixels”
HSPACE =”pixels”>
Example for Applet Tag
<html>
<head>
<title>Applet programming</title>
<body>
<applet code="Myfont.class" width=200 height=200>
</applet>
</body
</head>
</html>

 CODE: It is used to assign to byte code of java.


 ALT: It is an alternate text or short text messages.
 WIDTH: It is the width of the browser in pixels.
 HEIGHT: It is the height of the browser in pixels.
 ALIGN: The alignment of the text such as left, right, middle, top, bottom and
so on.
 VSPACE: It is a vertical space in pixels.
 HSPACE: It is a vertical space in pixels.

PASSING PARAMETERS TO APPLET


The parameters are used to pass in html after calling applet program name, we
should use <PARAM> and assign the attributes and its values such as name of the
font, size of the font, style of the font and colour of the font etc.
Example:
<PARAM NAME = font” VALUE =” TimesRoman”>

//Program to show the use of PARAM Tagimport java.applet.Applet;


import java.awt.Font;
import java.awt.Graphics;
public class MyFontapplet extends Applet
{
String fontName;
int fontSize;
public void init()
{
fontName=getParameter("font");
fontSize=Integer.parseInt(getParameter("size"));
}
public void paint(Graphics g)
{
Font f=new Font(fontName, Font.BOLD, fontSize);
g.setFont(f);
g.drawString("Skyward Publishers",50,50);
}
}
<html>
<head>
<title>Parameter Passing to an Applet</title>
<body>
<applet code=”MyFontapplet.class” width=400
height=500>
<PARAM NAME = font VALUE =” TimesRoman”>
<PARAM NAME =size VALUE =” 36”>
</applet>
</body>
</head>
</html>

DISPLAYING NUMERIC VALUE IN APPLET PROGRAMMING


If you assign any numeric values that can print in the applet as shown by the
following
import java.applet.Applet;
import java.awt.Graphics;
public class NumericApplet extends Applet
{
public void paint(Graphics g)
{
int first=100;
int second=200;
int sum=first+second;
String firstStr="First Number is
:"+String.valueOf(first);
String secondStr="Second Number
is:"+String.valueOf(second);
String sumStr="Sum is:"+String.valueOf(sum);
g.drawString(firstStr,20,20);
g.drawString(secondStr,20,40);
g.drawString(sumStr,20,60);
}
}
<html>
<head>
<title>Applet programming</title>
<body>
<applet code=NumericApplet.class width=200
height=200>
</applet>
</body
</head>
</html>

Update() method
This method is called when applet has requested that a portion of its window
the redrawn and after updating call inside the paint of method.
Example:
public void update()
{
//statements
}
public void paint(Graphics g)
{
Update(g);
}
repaint() method
An Applet writes to its window only when its update() or paint()
method.
Whenever our applet needs to applet the information displayed in its window,
it simply calls repaint().

Advantages of Applets
• Applets are cross platform and run on windows Mac OS, Linux, operating
system.
• Applets can work all the version of java plug-in.
• Applets run in a Sandbox, So the user does not need the trust the code.
• Applet are supported by most web browsers.
• Quick loading in the web browsers.

Disadvantages
• Java plug-in is required compulsory.
• Difficult to design.
• Java virtual machine is required compulsory.

Introduction to swing
What is swing in java?
• Java Swing is part of java Foundation Classes. Swing is the graphical user
interface toolkit that is used for developing windows based java applications
or programs.
• Java Swing is built on top of an abstract windowing toolkit API purely written
in java programming language.
• Java Swing provides lightweight and platform- independent components,
making it suitable and efficient in designing and developing desktop based
GUI applications.
• To use the Swing in java, javax.swing package needs to be used or import. It
is also known as java Swing.
Features of java Swing
1. Platform independent
It is platform-independent; the swing components that are used to build the
program are not platform-specific it can be used on any platform and
anywhere.

2. Lightweight
Swing components are lightweight as theyare written entirely in java and do
not depend on native peers (platform specific code resources).

3. Pluggable look and feel


Pluggable look and feel is a mechanism used in the java swing widget toolkit
allowing to change the look and feel of the graphical user interface at
runtime.

4. MVC
They mainly follow the concept of MVC that is the Model View Controller.
With the help of this, we can do the changes in one component without
impacting or touching other components.

5. Rich Controls
Swing provides a rich set of advanced controls like Tree, TabbedPane, Slider,
Color picker, and table controls.

AWT VS SWING
AWT SWING
AWT components are heavy weight Swing components are light weight
components components
AWT doesn’t support pluggable look Swing supports pluggable look and
and feel feel
AWT programs are not portable Swing programs are portable
AWT is old frame work for creating Swing is new framework for creating
GUIs GUIs
AWT components require java.awt Swing components require
package java.swing package
AWT supports limited number of Swing provides advanced GUI
GUI controls controls like j table, JTabbedPane etc
More code is needed to implement Less code is needed to implement
AWT controls functionally swing controls functionally
AWT doesn’t follow MVC Swing follows MVC

JAVA SWING CLASS HIERARCHY

COMPONENTS
In general, Swing components are derived from the JComponent
class.JComponent provides the functionality that is common to all
components. For example, JComponent supports the pluggable look and feel.
JComponent inherits the AWT classes Container and Component. Thus, a Swing
component is built on and compatible with an AWT component. All of Swing's
components are represented by classes defined within the package
javax.swing. Notice that all component classes begin with the letter ‘J’. For
example, the class for a label is JLabel; the class for a push button is JButton;
and the class for a scroll bar is JScrollBar.
Containers
Swing defines two types of containers. The first are top-level containers: JFrame,
JApple, JWindow, and JDialog.These containers do not inherit Component. They
do, however, inherit the AWT classes Component and Container. Unlike Swing's
other components, which are lightweight, the top level containers are
heavyweight. This makes the top-level containers a special case in the Swing
component library.
Swing Examples:
 JFrame
Frame frame new JFrame("Frame Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame setSize(400, 400);
frame.setVisible(true);

 JLabel
JFrame f = new JFrame("Java Swing Label"); JLabel
la1,1a2;lal= new JLabel("Java Programming");
La1.setBounds(70, 70, 120, 50);
La2=new JLabel("Java Swing");
la2.setBounds(70,120, 120, 50);
f.add(lal);
f.add(la2);
f.setSize(700, 700);
f.setLayout(null);f.setvisible(true);

 JButton
JFrame f=new JFrame("Creating Java Button");
JButton bt=new JButton("Sign in");
bt.setBounds (70,120,115,50);
f.add(bt);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);

 JTextField
JFrame f= new JFrame("Java Swing TextField");
JTextField tf1,tf2;
tfl=new JTextField("Java Programing");
tf1.setBounds (50, 100, 200,30);
tf2=new JTextField("Java Swing GUI");
tf2.setBounds(50 150, 200, 30);
f.add(tf1);
f.add(tf2);
f.setSize(700,700);
f.setLayout(null);
f.setVisible(true);

 JTextArea
JFrame f= new JFrame(); JTextArea ta=new JTextArea("Java");
ta.setBounds(10,30, 200,200);
f.add(ta);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);

 JCheckBox
JFrame f= new JFrame(“Java Swing CheckBox");
JCheckBox cb1 = new JCheckBox("C");
cb1.setBounds(100, 100, 50,50);
JCheckBox cb2 = new JCheckBox("Java", true);
cb2.setBounds(120,170, 70,70);
f.add(cb1);
f.add(cb2);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);

 JRadioButton
Frame f=new JFrame("RadiButton Example");
JRadioButton rb1=new JRadioButton("1) Male");
JRadioButton rb2=new JRadioButton("2) Female");
rb1.setBounds(80,50,90,30);
rb2.setBounds (80,188,90,30);
ButtonGroup btg-new ButtonGroup();
btg.add(rb1);
btg.add(rb2);
f.add(rb1);
f.add(rb2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);

EXCEPTION HANDLING
EXCEPTION
An exception is an error that occurs at run time.
Types of error in Java
1. Compile error
2. Runtime error.1.Compile error
1. Compile error
The compile error is nothing but syntax error or any general syntax mistake,
program fails during compile time. For example, semicolon missing, usage of
duplicate variables and so on.
Example:
Class test
{
Public static void main ()
{
System.out.println ("WELOME");
}
}

2. Runtime error
Runtime error is an error that occurs during at runtime.
Example: Division by Zero.

//Programming Example

Class Test
{
Public static void main (String args [])
{
Int I, j, k;
I=100;
J=0;
K=I/j;
System.out.println ("The value of k=" +k);
}
}
Definition of Exception Handling
Exception means run time error this error can handle by particular type of an
error and should define the error in a different fission of runtime error message
created by java.long package. This process is known as exception handling.

There are two types of runtime exceptions.


1. Check exception.
2. Run time unchecked exception.

General Syntax of Exception Handling


Try
{
/*Block of statements*/
}
Catch (Exception type var)
{
/*catch the Exception*/
}

The exception handling is basically used in 4 components.


• Try
• Catch
• Throw
• Finally

 Try: This method is used to execute the block of statements for throwing an
exception using the keyword try.

 Catch: It is used to create the type of an exception using keyword catch


Example: arithmetic exception, array out of bounds exception and so on.

 Throw: Throwing the exception type from catch block to try block.

 Finally: To submit the final report of error handling in exception using


finally keyword.
//Write a program to demonstrate Arithmetic Exception using try and
catch block

public class ArithmeticExceptionDemo


{
Public static void main (String args [])
{
int i=100, j=0;
int k;
try
{
K=i/j;
}
(catch Arithmetic Exception e)
{
System.out.println(“Exception occurred: Division
by Zero”);
K=i/(j+2);
}
System.out.println(“the value of K is =” +k);
}
}

Multiple catch statements


It is used to create two or more error types in an exception used in a number of
catch blocks known as multiple catch statements.
General syntax:
Try
{
/*Exception statements*/
}
catch (Exception type1 e1)
{
/*type1 exception*/
}
catch (Exception type2 e2)
{
/*type2 exception*/
}

----------------
----------------
----------------
Catch (Exception typeN en)
{
/*typeN exception*/
}

Finally Keyword
The final keyword is used to create the block of code that follows a try block.
General Syntax:
Try
{
/*Exception statements*/
}

catch (Exception type1 e1)


{
/*type1 exception*/
}

catch (Exception type2 e2)


{
/*type2 exception*/
}

----------------
----------------
----------------
Catch (Exception typeN en)
{
/*typeN exception*/
}

Finally ()
{
/*final statements*/
}

//Write a program to demonstrate the use of multiple catch


and finally keyword

Import java.io. *;
Public class fileReadBytes
{
Public static void main (String args [])
{
fileInputStream fos=null;
try
{
fos = new FileInputStream(“File1.txt”);
int size=fos. available ();
byte ba [] =new byte[size];fos. read(ba);
String data=new String(ba);
System.out.println(“the file contents are:” =+
data);
}
Catch (FileNotFoundException e)
{
System.out.println(“FileNotFoundExceptionoccurred”);
}
Catch (EOFException e)
{
System.out.println(“EOFException occurred”);
}
Catch (IOException e)
{
System.out.println(“IOException occurred”);
}
Finally
{
Try
{
fos. Close ();
}
Catch (Exception e)
{
System.out.println(“Exception while closing
file stream”);
}
}
}
}

The Following program illustrates once it gets an exception in try block, it will
not execute the rest of the code in the try block. It jumps to the catch block and
finally block.
class Demo
{
public static void main (String args[])
{
Demo t=new Demo ();
try
{
System.out.println(“one”);
t. method1();
System.out.println(“Two”);
}
catch (Arithmetic Exception e)
{
System.out.println(“Three”);
}
Finally
{
System.out.println(“Four”);
}
}
Void method1()
{
int a=o;
int b=100/a;
}
}

//To Demonstrate Caught Exception


class Demo
{
public static void main (String args [])
{
Demo cd=new Demo ();
try
{
cd.method1();
}
Catch (ArithmeticException e)
{
System.out.println(“/ caught an Exception”);
}
System.out.println(“Now I am out of try catch block”);
}
Void method1()
{
int a=0;
int b=100/a;
}
}

//The Following Program shows how display the exception details


class Demo
{
public static void main (String args [])
{
Demo cd=new Demo ();
try
{
cd.method ();
}
Catch (ArithmeticException e)
{
System.out.println(e);
}
}
Void method ()
{
int a=0;
int b=100/a;
}
}
UNIT 03. Exceptional handling mechanism
3 i/O programming

I/O STREAMS

Some examples of elements that form a flow of communication between source


and destination are:
 A keyboard(source) and a monitor(destination)
 A page of text on a monitor(source) and a file on a hard drive(destination)
 A file on a hard drive(source) and a monitor(destination)
 A keyboard(source) and a string(destination)
 A textfile (source) and a printer(destination)

Classification of I/O Streams


1. Byte Oriented classes (Byte Streams)
2. Character Oriented Classes(Character Streams)

1) Byte oriented stream of two types


a) Input Stream
b) Output Stream

2) Character oriented stream of two types


a) Reader
b) Writer

a) Input Stream
Input stream is an abstract class that provides the frame work from which all
other input streams are derived. In the below diagram, all the input streams
like FileInputStream , PipedInputStream are derived from InputStream class.
 We cannot create an instance of input stream class as it is abstract class.
 Whenever we want to read data in byte format then we use the Input Stream
classes.
 The InputStream class contains lots of methods for reading bytes, closing
streams, skipping part of data in the stream, finding the number of bytes
present in the input data, etc..,
 The important methods of Input stream classes are shown below:-

METHODS DESCRIPTION
Int available() Returns the number of bytes of input currently
available for reading.
Void close() Close the input source. Further read attempts
will generate an IO Exception.
Void mark(int numBytes) Places a mark at a current point in the input
stream that will remail valid until numBytes
bytes are read.
Boolean markSupported() Return true if mark()/reset() are supported by
the invoking stream.
Int read() Return an integer representation of the next
available byte of input 1 is returned when the end
of the file is encountered.
Int read(byte buffer[]) Attempts to read up to buffer length bytes into
buffer and returns the actual number of bytes
that were successfully read. -1 is returned when
the end of the file is encountered.
Int read(byte buffer[],int Attempts to read up to numBytes bytes into
offset,int numBytes) buffer starting at buffer(offset),reading the
number of
bytes successfully read, -1 is returned when the
end of the files is encountered.
Void reset() Resets the input pointer to the previously set
mark.
Long skip(long Ignores (that is, skips) numBytes bytes of
numBytes) input,returning the number of bytes actually
ignored.

b) Output Stream
OutputStream is an abstract class that provides the framework from which all
other output streams are derived. In the below diagram,all the output streams
like FileOutputStream, PipedOutputStream are derived from OutputStream
class.

 We cannot create an instance of OutputStream class it is abstract class.


 Whenever we want to write data in byte format, then we use the output
stream classes.
 The Output stream class contains lot of methods for writing bytes, closing
streams etc.,
 The important methods of OutputStream classes are shown below.

METHODS DESCRIPTION
Void close() Closes the output stream, Further write
attempts will generate an IOException.
Void flush() Finalizes the output state so that any buffers
are cleared. That is, it flushes the output
buffers.
Void write(int b) Writes a single bit to an output stream. Note
that the parameter is an int, which allows you
to call write with expressions without having
to cast them back to byte.
Void write(byte buffer[]) Writes a complete array of bytes to an output
stream.
Void write(byte buffer[],int Writes a subrange of numBytes bytes from
offset,int numBytes) the array buffer, beginning at buffer [offset].

c) Character Stream
Reader is an abstract class that provides the framework from which all other
reader streams are derived. In the below diagram all, all the reader streams like
BufferedReader, CharArrayReader are derived from Reader class.
Writer is an abstract class that provides the frame work from which all other
writer streams are derived. In the below diagram all the writer streams like
BufferedWriter, CharArrayWriter are derived from Writer class.

Input/Output Exceptions
Exceptions in java are the way of indicating the occurrence of abnormal
condition in the program. Actually these are objects that are thrown when
program encounters any problem executing the program further.

EXCEPTION MEANING
EOF Exception Signals that an end of the file reached, when we are
trying to read the file, if the position of the file is at
the end, we may get this exception.
File Not Found Exception If we are trying to access the file, and the file does
not exist, we will get this exception.
Interrupted IO Exception It warns that an I/o operation has been interrupted.
IO Exception Some sort of I/o exception has occurred. It is very
generic exception of I/o.
When we write code related to I/O operations, we should place the
statements in try block and handle the exceptions in catch block as shown
below.
Try
{
Statements related to I/o operations
}
Catch (IO Exception e)
{
Handle the exception
}

Creating Files
The following table explains the different ways of creating and reading files.
CONSTRUCTOR EXAMPLE
A file is opened for input by creating FileInputStream fis;
a FileInputStream Object. Try
FileInputStream(String ilename) {
throws FileNotFoundException fis=new
FileInputStream(“myFile.dat”);
}
catch(IOException)
{
}
FileInputStream(File f)throws File f=new File(“myFile.dat”);
FileNotFoundException FileInputStream fis;
Try
{
Fis=new FileInputStream(f);
}
catch(IOException)
{
}
To open a file for output,create a FileOutputStream fos;
FileOutputStream object. Here are Try
its two most commonly used {
constructors. Fos=new FileOutputStream(f);
FileOutputStream(StringfileName) }
Throws FileNotFoundException Catch(IOException)
{
}
FileOutputStream(File file)throws File f=new File(“myFile.dat”);
FileNotFoundException FileOutputStream fos;
Try
{
Fos=new FileOutputStream(f);
}
Catch(IOException)
{
}

Reading/Writing Bytes

1. Write a program to read data from the console and write this data
in a file named file1.txt

import java.io.*;
public class FileWriteBytes
{
public static void main(String args[])
{
Try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println(“Enter the Data:”);
String s1=br.readLine();
FileOutputStream fos=new
FileOutputStream(“File1.txt”,true);
Byte ba[]=s1.getbytes();
Fos.write(ba);
Fos.close();
}
Catch(IOException e)
{
System.out.println(“Exception Occurred”);
}
}
}

2. Write a program to read data from the file File1.txt and write this
data to console.

import java.io.FileInputStream;
import java.io.IOException;
public class FileReadBytes
{
public static void main(String args[])
{
try
{
FileInputStream fos=new
FileInputStream(“File1.txt”);
int size=fos.available();
byte ba[]=new byte[size];
fos.read(ba);
String data=new String(ba);
System.out.println(“The file contents are: “+data)
fos.close();
}
catch(IOException e)
{
System.out.println(“Exception occurred”);
}
}
}

You might also like