You are on page 1of 35

UNIT - 5

I/O STREAMS & FILES


A Stream is a path along the data flows. Every stream has a source and
destination. The two fundamental types of streams are input streams and Output streams.
An output streams writes data into a file, an input stream read data from the file.
TEXT and BINARY FORMATS OF DATA
The are two ways to store a data,
i )Text format :
Data items are stored in human-readable form in the text format.
ii )Binary format:
Data items are represented in bytes in the case of binary format. As a byte
consists of 8 bits, it can represent one of 256 values
❖ If the data items are available in text format, we have to use the Reader and Writer
classes and their sub classes to process the input and output.
❖ If the data items are available in binary format, we have to use the Inputstream and
Outputstream Classes.
INPUT STREAM and OUTPUT STREAM CLASSES
❖ The input stream and output stream classes are used for dealing with data in
binary format. The important methods in these two classes are described below.

Srimad Andavan Arts and Science College


Department of Computer Sciecne
Methods in Output Stream classes:

Syntax Use
write() To write a byte to the Output stream
write(byte b[]) To write all bytes in the array b to the
Output stream.
write(byte b[],int n,int m) To write m bytes from array b starting
from nth byte
close() To close the Output stream.

Methods in Input Stream class:

Syntax Use
read() To read a byte from the Input stream
read(byte b[]) To read an array of b.length bytes into
array b.
read(byte b[],int n,int m) To read m bytes into b starting from nth
close() byte
reset() To close the Input stream.
skip(n) To go back to the beginning of the stream.

Output Stream Class:


The two important subclass of the output stream class are,
I) FileOutputStream:
The functionality of this class is, it write one byte at a time into
a file.
II) BufferedOutputStream:
The functionality of this class is, it write buffers of bytes into a file.
❖ Some other important subclasses of the output stream class are listed below.

Name of the subclass Functionality


OutputStream Performing Output Operation
BufferedOutputStream Buffering Output
ByteArrayOutputStream Writing to an array
FileOutputStream Writing to a file
FilterOutputStream Filtering the Output Srimad Andavan Arts and Scienc e College
Department of Compute r Sciecne
PrintStream Outputs the primitive type to console
Input Stream Class:
The two important subclass of the Input stream class are,
I ) FileInputStream:
The functionality of this class is, it reads one byte at a time from
a file.
II) BuffereInputStream:
The functionality of this class is,it reads buffers of bytes from a file.
❖ Some other important subclasses of the output stream class are listed below.

Name of the subclass Functionality


InputStream Performing Input Operation
BufferedInputStream Buffering Input
ByteArrayInputStream Reading from an array
FileInputStream Reading from a file
FilterInputStream Filtering the Input
StringBufferInputStream Reading from a String

Program for writing a data into a file using FileOutputStream class


import java.io.*;
public class writedemo
{
public static void main(String args[])
{
String s=”welcome”;
byte b[]=s.getBytes();
FileOutputStream fos=new FileOutputStream(“A.txt”);
for(int i=0;i<b.length;i++)
fos.write(b[i]);
fos.close();
}
}
Output: welcome (this string is written in the A.txt file)
Program for reading a byte of data from a file using FileInputStream class
import java.io.*;
public class readdemo
{
public static void main(String args[])
{
FileInputStream fis=new FileInputStream(“A.txt”);
Srimad Andavan Arts and Science College
Department of Computer Sciecne
int c;
while((c=fis.read())!=-1)
System.out.println(“The read character is : “+(char)c);
fis.close();
}
}
Output:
The read character is : w
The read character is : e
The read character is : l
The read character is : c
The read character is : o
The read character is : m
The read character is : e

READER and WRITER CLASS


❖ The Reader and Writer classes are used for dealing with data in the text format.
❖ The methods in the reader and writer class identical to those methods in the
Inputstream and outputstream classes. The only difference is the methods in
Reader and Writer class are designed to deal with characters.
Writer Class:
The two important subclass of the Writer class are,
I ) FileWriter :
The functionality of this class is, it writes one character at a time into
a file.

II) BufferedWriter :
The functionality of this class is, it writes buffers of characters into
a file.
❖ Some other important subclasses of the Writer class are listed below.

Name of the subclass Functionality


Writer Performing Output Operation
BufferedWriter Buffering Output
CharArrayWriter Writing to an array
FileWriter Writing to a file
FilterWriter Filtering the Output
OutputStreamWriter Translating character stream into a byte
stream
r Sciecne
Srimad Andavan Arts and Scienc e College
PrintWriter Printing values and objects. Department of Compute
Reader Class:
The two important subclass of the Reader class are,
I ) FileReader :

The functionality of this class is, it read one character at a time from a file.
II) BufferedReader :
The functionality of this class is, it read buffers of characters from a file.
❖ Some other important subclasses of the Reader class are listed below.

Name of the subclass Functionality


Reader Performing Input Operation
BufferedReader Buffering Input
CharArrayReader Reading from an array
FileReader Reading from a file
FilterReader Filtering the Input
InputStreamReader Translating byte stream into a character
stream
LineNumberReader Keeping track of line numbers

Program to illustrate the use of FileWriter Class


import java.io.*;
public class writerdemo
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter(“A.txt”);
for(char c=65;i<91;i++)
{
fw.write();
}
fw.close();
}
catch(Exception e)
{
System.out.println(“Exception : “+e);
}
}
}
Output:
Srimad Andavan Arts and Science College
Department of Computer Sciecne
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Program to illustrate the use of FilerReader Class


import java.io.*;
public class readerdemo
{
public static void main(String args[])
{
try
{
FileReader fr=new FileReader(“A.txt”);
int i;
while((i=fr.read())!=-1)
System.out.println((char)i);
fr.close();
}

catch(Exception e)
{
System.out.println(“Exception : “+e);
}
}
}
Output: ABCDEFGHIJKLMNOPQRSTUVWXYZ

DATAOUTPUTSTREAM and DATAINPUTSTREAM CLASS


DataOutputStream Class:
❖ The DataOutputStream class extends FilterOutputStream class and implements
DataOutput interface. The FilterOutputStream class extends the OutputStream
class Therefore, the DataOutputStream class contains all the methods in
OutputStream Class.
❖ In addition, the following are the methods included in the DataOutputStream
class.
1) writeShort() 2) writeInt() 3) writeLong() 4) writeFloat() 5) writeDouble() 6)
writeBytes() 7) writeChar() 8) writeBoolean()

DataInputStream Class:
❖ The DataInputStream class extends FilterInputStream class and implements
DataInput interface. The FilterInputStream class extends the InputStream class
Therefore ,the DataInputStream class contains all the methods in InputStream
Srimad Andavan Arts and Science College
Department of Computer Sciecne
Class.

Srimad Andavan Arts and Science College


Department of Computer Sciecne
❖ In addition, the following are the methods included in the DataInputStream
class.
1) readShort() 2) readInt() 3) readLong() 4) readFloat() 5) readDouble() 6) readBytes()
7) readChar() 8) readBoolean()
PRINT STREAMS
• The print streams are used to output the data into a file or to the console.
• The print stream class has the print() method of the following forms.
1. print(String s)
2. print(char c)
3. print(char cArray[])
4. print(int i)
5. print(double d)
6. print(Boolean b)
7. print(object o)
• When an object is passed to the print() method, the objects toString() method
converts it to a String object.
• We can also use the println() method wherever we use the print() method.
• The println() method inserts a new line character at the end of the output.
OBJECT STREAMS
15. The object streams enable us to store and retrieve all instance variables of an
object automatically.
16. The important Object stream classes are ObjectInputStream and
ObjectOutputStream.
17. The ObjectOutputStream class helps to save an entire object out to disk.
18. The ObjectInputStream class helps to read the object back in.
19. The objects are saved in binary format.
20. The process of saving an object to a stream is called Serialization.
21. Only if a class implements serializable interface ,we can store the instance
variables in an object of that class.

Srimad Andavan Arts and Science College


Department of Computer Sciecne
AWT Classes
➢ AWT stands for Abstract Window Toolkit.
➢ It contains several classes and methods that allow you to create and manage windows.
➢ The AWT classes are contained in the java.awt package.
➢ It is one of the Java’s largest packages.
Class Description
BorderLayout The border Layout Manager.
Button Creates the push button control
CardLayout The card Layout manager
Checkbox Creates a check control
CheckboxGroup Creates a group of checkbox control
Choice Creates a pop-up list
Color Manages colors in a portable platform
independent fashion.
Component An abstract super class for various AWT
components.
Container A subclass of component that can hold other
Components
FlowLayout The flow layout manager
Font Encapsulates a type font
Frame Creates a standard window that has a title bar,
resize corners and a menu bar
Graphics Encapsulates the graphics context. this is used
by various output methods to display output in
a window.
Image Encapsulates graphical images
Label Creates a label that displays a string
List Creates a list from which the user can choose
Menu Creates a pull down menu
Menubar Creates a menu bar

Srimad Andavan Arts and Science College


Department of Computer Sciecne
MenuItem Creates a menu item
Panel The simplest concrete subclass of container
Scrollbar Creates a scrollbar control
TextArea Creates a multi line edit control
TextField Creates a single line edit control

Window Fundamentals
▪ The AWT defines windows according to a class hierarchy.
▪ The two most common windows are,
❖ Panel, which is used by applets.
❖ Frame, which is used to create standard window.
▪ The functionality of these windows is derived from their parent
classes.
The Class Hierarchy for Panel and Frame

Component
▪ Component is an abstract class that encapsulates all of the attributes of a visual
component.

Srimad Andavan Arts and Science College


Department of Computer Sciecne
▪ All user interface elements that are displayed on the screen and interact with the
user are subclasses of Component.
▪ It defines hundred of public methods that are responsible for managing events.
▪ A Component object is responsible for remembering the current foreground
and background colors and the currently selected text font.

Container
❖ The Container class is a subclass of Component.
❖ It has additional methods that allow other Component objects to be nested within it.
❖ A Container is responsible for laying out (positioning) any component that it contains.
❖ It uses various layout managers to do this work.
Panel
• The Panel class is a concrete subclass of Container.
• It does not add any new methods, but it simply implements Container.
• Panel is the super class for Applet. When screen output is directed to
an applet, it is drawn on the surface of the Panel object.
• Panel is a window that does not contain a title bar, menu bar, or border.
Since you don’t see these items when an applet is run inside a browser.
• Other components can be added to a Panel object by its add () method.
You can position and resizing the components by using setLocation (),
setSize (), or subtends () methods defined by the Component.

Window

• The Window class creates a top-level window. It sits directly on the desktop.
• You can’t create Window objects directly. But you will use a subclass of Window
called Frame.

Frame
❖ It is a subclass of Window. It has a title bar, menu bar, borders, and resizing
corners.

Srimad Andavan Arts and Science College


Department of Computer Sciecne
❖ Using Frame we can create a normal window. (I.e., it encapsulates what is
commonly available in window).
❖ Frame run on local machine. (But Applet run on web browser also).

Canvas
❖ This encapsulates a blank window upon which we can draw

Working with Frame Windows


Awt Controls:
• After the applet, you will mostly create windows by using Frame.

Constructors

13. Frame () Creates a standard window that does not contain a


title.
14. Frame (String Name) Creates a window with the title specified by Name.
LABEL
• A Label component displays a line of text. The text can be aligned to the left,
right, or center of the Label. The user isn't allowed to edit the text in a Label.
• A Textfield is placed often after the label.
• The Constructors for the Label are as follows.
1) Label(), 2) Label(String s), 3) Label(String s,int align)
1. Here, s is the text for the label.
2. align indicates whether the label should be left-justified or right justified.
3. The value of align should be set to LEFT,RIGHT or CENTER

• The Label contains a string to be displayed.


• Do not support any interaction with the user.
Methods:
• void setText (String STR) Set or change the text in a label. Where STR specify the
new label.
• String getText () Returns the current label.

Srimad Andavan Arts and Science College


Department of Computer Sciecne
• void setAlignment (int align) Set the alignment of the string within the label.
• int getAlignment () Returns the current alignment of the string within the
label.

BUTTON
❖ The most widely used control is the push button. A push button is a component
that contains a label and that generate an event when it is pressed.
Constructors:
Button () Creates an empty button.
Button (String caption) Creates a button that contains caption as a label.

Methods:
void setLabel (String Str) Sets the button label by Str.
String getLabel () Return the label of the button.
Handling Events:
• Each time a button is pressed, an action event is generated. Each listener implements
the ActionListener interface.
• When events occur the actionPerformed () method will be invoked. An ActionEvent
object is the argument of this method.
• The label is obtained by calling the getActionCommand () method on the ActionEvent
object.
CHECKBOX
This control is used to turn an option on or off.there is a label associated
with each checkbox.
Constructors:
Checkbox() - creates empty checkbox
Checkbox(String s) - creates checkbox with string label
Checkbox(String s,Boolean on) - creates checkbox with string label and selcted/deselcted
option
Checkbox(String s,CheckboxGroup cg,boolean on) - creates checkbox with string label
and selcted/deselcted option with group
Methods
Srimad Andavan Arts and Science College
Department of Computer Sciecne
1. getState() - Retrieves the control
2. setState - Sets the state true or false for a check box.
3. getLabel - Fetches the current label associated with the checkbox
4.setLabel() - Sets the label for a checkbox

When a checkbox is selected or deselected, an item event is


generated. This is sent to any listener. The listener implements “ ItemListener” interface. It
defines “itemstatechanged()” method. An “Item Event” object is passed as a parameter to
this method “ItemEvent” contains information about the event(selection or deselection.)
The name of the checkbox(i.e.label) currently selected/deselected can be obtained by
calling “getItem()” method.
CHECKBOX GROUP
A set of mutually exclusive checkboxes in which one and only one
check box in the group can be checked at any one time. These checkboxes are often called “
radio buttons”. To create such checkboxes, we must define the group.

Constructor
CheckboxGroup();
Methods

getState - Returns the state of a checkbox group.


setState - sets the state for a checkbox group item.
getLabel() - fetches the label for a checkbox group item.
setLabel() - sets the label for the item.
getCurrent() -retrieves all the details such as label, state checkbox no etc for the currently
selected item.
getSelectedCheckbox() - retrieves the same details as the getcurrent() method.
Events
When a checkbox group item is selected or deselected (turned on or off), an
item event is generated. This is sent to any listener. The listener implements “ItemListener”
interface. It defines “itemstatechanged()” method. An “ItemEvent” object is passed as a
parameter to this method. “ ItemEvent” contains information about the event(selection or de-
selection).
Srimad Andavan Arts and Science College
Department of Computer Sciecne
CHOICE
➢ The functionality of the choice control is simple.
➢ It displays the first choice among all of the allowed choices.
➢ When the user clicks on a choice, this control displays all of the
allowed Choices. Then the user can select any one of the choice.
➢ The constructor of the choice control is as follows
Choice()
▪ A item event is generated when a user selects one of the entries listed
in a choice control.
▪ The listener can register to receive the ItemEvent object by
the
following method.
void addItemListener(this)
22. We can add an item to a choice control through the following
method
addItem(String s)
23. The source that generated an item event can be obtained through
the following method,
getItemSelectable()

getSelectedIndex() - returns the index of the item selected.

getItemCount()—returns the no of items in the list.

getItem(int index)-- returns the name associated with the index.

select(int index)—set the currently selected item on top.

Event
▪ Each time a choice is selected, an item event is generated. This is sent to any
listener. Each listener implements “ItemListener” interface.

Srimad Andavan Arts and Science College


Department of Computer Sciecne
▪ This interface defines “itemStateChanged()” method. An “ItemEvent” is passed to
this method. It notes down the details of the currently selected item in choice.
LIST
List Controll:
24. List control enables the user to select an item from the list of
items.
25. This control also allows the user to select two or more items
at a time.
26. The list control initially displays all the available items.
27. If the size of the list control is not enough to display all the
allowed items,a Vertical scrollbar is automatically included.
28. The constructor of the choice control is as follows

1. List()
2. List(int rows)
3. List(int rows,boolean multiple)
1. Here, rows represents the number of items that are visible to a user at a time.
2. When a multiple is true, a user can select two or more items in a list.
❖ An itemEvent Object is generated when a user selects or deselects one of the items
listed in a list control.
❖ An ActionEvent object is generated when a user double-clicks the item.
❖ An ItemListener object can be register to receive the item event by the following
method.
addItemListener(this)
• We can add an item to a list control by using the following method.
add(String s)
• The source that generated an itemEvent can be obtained through the
getItemSelectable().
The ItemListener interface declares the itemStateChanged() method,while the
ActionListener declares the actionPerformed() method.

Events:

Srimad Andavan Arts and Science College


Department of Computer Sciecne
To process the list events implement “ActionListener” interface. Each time a list
item is double clicked a “ActionEvent” object is generated.
O getActionCommand() method can be used to retrieve the name of the
newly selected item
O getStateChange() method can be used to determine whether a selection or
de-election triggered this event
TEXTFIELD
▪ The TextField class implements a single line text-entry area. (Also called as edit
control).
▪ Allow the user to enter strings and to edit the test using the arrow keys, cut and
paste keys and mouse selections.
Constructors:
➢ TextField ( ) Creates a default text field.
➢ TextField (int numChars) - Creates a text field with width specified by
numChars.
➢ TextField (String Str) - Initialize the text field with the string specified by Str.
➢ TextField (String Str, int numChars) - Initialize the text field by Str and set its
width by numChars.
Methods:
➢ String getText() - Returns the string currently available in the text field.
➢ void setText(String Str) - Set the text with the value specified by Str.
➢ String getSelectedText () - Returns the selected text only.
➢ void select(int stIndex, int enIndex) - Select the characters beginning at stIndex and
ending at enIndex-1.
➢ boolean isEditable () - Returns true if the text may be changed.
➢ void setEditable(boolean flag) - If the flag true, then the text may be changed.
Otherwise the text can’t be changed.
➢ void setEchoChar(char ch) - Set echo character to the text field. (Such as password)
➢ boolean echoCharIsSet () -Check a text filed whether it is in echoChar mode or not.
➢ char getEchoChar () - Returns the current echo character of a text field.
TEXTAREA

Srimad Andavan Arts and Science College


Department of Computer Sciecne
The TextArea class implements a multi-line text-entry area. Allow the user
to enter strings and to edit the test using the arrow keys, cut and paste keys and mouse
selections.
Constructors:
o TextArea () - Creates a default text area.
o TextArea (int numLines,int numChars) - Create a text area with height numLines
and width numChars.
o TextArea (String Str) - Initialize the text area with the string specified by Str.
o TextArea (String Str,int numLines,int numChars) - Initialize the text area by Str
and
set its height by numLines and width by numChars.
o TextArea (String Str,int numLines, int numChars,int sBar) - where sBar specify the
scrollbar control.ScrollBar must be one these values
1. SCROLLBARS_BOTH 2. SCROLLBARS_NONE
3.SCROLLBARS_HORIZONTAL_ONLY
4. SCROLLBARS_VERTICAL_ONLY
Methods:
o It supports the getText (), setText (), getSelectedText (), select (), isEditable () and
setEditable () methods.
o void append (String Str) - Append the string Str to the end of the text.
o void insert (String Str, int Index) - Insert the string Str at the location specified
Index.
o void replaceRange (String Str, int stIndex, int enIndex) - Replace the char’s
from stIndex to enIndex-1 by Str.
ScrollBar:
• The scrollbar control contains a slider or stub.
• The user shall click the buttons at both the ends or at any position of the slider between
the buttons.
• The three possible constructors of the scrollbar control are as follows.
1. Scrollbar()
2. Scrollbar(int orientation)
3. Scrollbar(int orientation,int value,int w,int min,int max)
Srimad Andavan Arts and Science College
Department of Computer Sciecne
1. Here, orientation is used to indicate whether the scrollbar is intended to be
oriented horizontally or vertically by the two static constants namely
Scrollbar.HORIZONTAL and Scrollbar. VERTICAL.
2. The value represents the initial position of the slider.
3. The width represents the width of the slider.
4. The min and max value represents the range of the scrollbar.
• An AdjustmentEvent object is generated whenever the value represented by a
scrollbar is changed.
• An AdjustmentListener object can be registered to receive an AdjustementEvent
by the following methods.
addAdjustmentListener(this)
▪ The source of the event can be obtained by th method getAdjustable().

LAYOUT MANAGERS
• A layout manager automatically arranges your controls within a window.
• The layout managers are used to organize the controls or components.
• Layout managers are placed inside a Frame or Applet or Panel

To Set Layouts:
• setLayout (null) -Null layout cancels the container’s layout. So users must manually
placed the components by using the setBounds () method.
• setLayout (new LayoutManager) - To set the layout model. If no call to setLayout ()
method, then the default layout manager is used.
▪ setBounds (int left,int top,int width,int height) -Set the components
position and
size.
Ex: - Label L=new Label ();
L.setBounds (100,100,75,25);
FLOWLAYOUT : Default layout for Applets and Panel.
Constructors:
▪ FlowLayout (); Default constructor, which centers components and
leaves 5 pixels of space between each component.
Srimad Andavan Arts and Science College
Department of Computer Sciecne
▪ FlowLayout (Align); Specify how each line is aligned.
▪ FlowLayout (Align, int hoz, int ver); Specify the horizontal and
vertical space between each component.
Align : 1. FlowLayout.LEFT 2. FlowLayout.RIGHT
3.FlowLayout.CENTER
Container class methods:
1. setLayout (new Layout (…)); 2. add (component) 3. remove (component)
BORDERLAYOUT : Default layout for Frames.
Constructors:
❖ BorderLayout (); Set the default border layout.
❖ BorderLayout (int hor, int ver) Specify horizontal and vertical space between
components.
Container class methods: 1. setLayout (new BorderLayout(…));
2. add (Component,Direction);
Direction: 1. BorderLayout.NORTH 2. BorderLayout.SOUTH
3. BorderLayout.EAST 4. BorderLayout.WEST
5. BorderLayout.CENTER

GRIDLAYOUT : Same width and height for all cells.


Constructors:
• GridLayout () - Creates a single-column grid layout.
• GridLayout (int row,int col) - Creates a grid layout with the specified number of rows
and columns.
• GridLayout (int row, int col, int Hspace, int Vspace)
- Specify the horizontal and vertical space between components.
- If row is zero, then number of columns will be unlimited length.
- If col. is zero, then number of rows will be unlimited length.
Container class methods: 1. setLayout (new GridLayout(…)); 2. add(Component);

CARDLAYOUT : Stores several different layouts.


Deck: - Collection of cards.
Constructors:
Srimad Andavan Arts and Science College
Department of Computer Sciecne
 CardLayout () - Create default card layout.
 CardLayout (int hor, int ver) - Specify the horizontal and vertical space between
components.
Methods: 1. void first(container) 2. void next(container)
3. void previous(container)
4. void last(container) 5. void show(container, cardName)
Container class methods: 1. setLayout (new CardLayout(…));
2.add (component, Name);
Font class:
Font (String fontName, int fontStyle, int Size) where fontName is name of the font.
Style: 1. Font.PLAIN 2. Font.BOLD 3. Font.ITALIC
void setFont(Font fontObject) where fontObject contain the desired font.
Ex: - setFont (new Font (“Courier”, Font.BOLD | Font.ITALIC, 20));
Menu Bar ,Menus and MenuItems
11. Menu bar contains one or more Menu objects.
12. Each menu object contains a list of MenuItem objects.
13. Each MenuItem object represents something that can be selected by the user.
14. To create a menu bar, First create an instance of MenuBar.
15. Second create instances of Menu, that will be displayed on the menu bar.
16. Third create instances for MenuItem. Next add the MenuItems to Menu.
17. Then add the Menu to MenuBar.
Handling Events by Extending AWT Components:
❖ Java allows you to handle events by extending the AWT components.
❖ To extend an AWT component, you must call the enableEvents () method of
Component.
❖ G.F: - protected final void enableEvents (long eventMask)

Event Handling Mechanism


7. Events can be handled by
1. Delegation event model
2. Handling events by extending AWT components
8. Delegation event model
Srimad Andavan Arts and Science College
Department of Computer Sciecne
i) The modern approach to handling the event is based on this model, which
defines a standard set of mechanism to generate and process events
ii) A source generates an event and sends it to one or more ‘listeners’. The
listener waits for the event and then processes it.
9. Events
4. An ‘Event’ is an object that describes a state change in a source.
5. It is generated when a person interacts with the element, by pressing a button or
clicking the mouse.
10. Event Sources
➢ A ‘source’ is an object that generates an event. This occurs when the internal state
of that object changes in some way.
➢ A source must register listeners, such as addActionListener(),addItemListener()
etc..
11. EventListener
➢ A ‘Listener ‘ is an object that is notified when event occurs.
➢ The method that receive and process events are defined in a set of interfaces
found in ‘java.awt.event’.they are, ActionListener,ItemListener.
12. Event class
The package ‘java.awt.event’ defines several types of events that are
generated by various user interface elements.

HANDLING EVENTS

Event Handling Methods:


A listener interface specifies the methods that are required to
process the specified events. Such methods are known as event handling methods.

Event Class Event Handling methods


ActionEvent actionPerformed()
AdjustmentEvent adjustmentValueChanged()
componentHidden()
ComponentEvent componentMoved()
componentResized()
Srimad Andavan Arts and Science College
Department of Computer Sciecne
componentShown()
componentAdded()
ContainerEvent componentRemoved()
focusGained()
FocusEvent focusLost()
ItemEvent itemStateChanged()
keyPressed()
KeyEvent keyReleased()
keyTyped()
mouseClicked()
mouseEntered()
MouseEvent mouseExited()
mousePressed()
mouseReleased()
mouseDragged()
mouseMoved()
TextEvent textValueChanged()
WindowEvent windowActivated()
windowClosed()
windowClosing()
windowDeactivated()
windowIconified()
windowDeiconified()
windowOpened()

Listeners:
• A Listener receives the click event of the button by calling the appropriate listener
methods.
• A listener should implement the appropriate listener interface.
• All of the listener interfaces are specified in the java.awt.event package.

Event Class Corresponding Listener Interface

Srimad Andavan Arts and Science College


Department of Computer Sciecne
ActionEvent ActionListener
AdjustmentEvent AdjustmentListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
ItemEvent ItemListener
KeyEvent KeyListener
MouseEvent MouseListener,MouseMotionListener
TextEvent TextListener
WindowEvent WindowListener

Example Program For AWT Component: -


import java.awt.*;

class AwtDemo
{
Frame f;
Label lb;
TextField txt;
TextArea ta;
List l1;
Choice ch;
Scrollbar sc;
Checkbox cb;

AwtDemo()
{
f=new Frame("Thiyagu");
f.setSize(300,300);
f.setLayout(new FlowLayout());
lb=new Label("empnmae");
txt=new TextField(10);
ta=new TextArea(10,10);
l1=new List(5);
l1.add("rajan");
l1.add("mala");
l1.add("ravi");
l1.add("ramu");
l1.add("mani");
l1.add("vani");
Srimad Andavan Arts and Science College
Department of Computer Sciecne
l1.add("manu");
ch=new Choice();
ch.add("rajan");
ch.add("mala");
ch.add("ravi");
ch.add("ramu");
sc=new Scrollbar();
cb=new Checkbox();
f.add(lb);
f.add(txt);
f.add(ta);
f.add(l1);
f.add(ch);
f.add(sc);
f.add(cb);
f.setVisible(true);
}
public static void main(String arg[])
{
new AwtDemo();
}
}

Srimad Andavan Arts and Science College


Department of Computer Sciecne
APPLETS
Applet
• A Java programs that appears to be embedded in a web document.
• Applets are a small java program that runs inside a web browser.
• The byte code for an applet is stored as part of a web page that is made
available on a web server.
• An applet does not have a main method.
• The web browser is responsible for starting up the java virtual machine.
The Life Cycle of an Applet

Begin Initialization
(Load Applet)

start()
stop()

Display Stopped

paint()
start()

destroy()

Destroyed End
▪ An applet has a well-defined life cycle, as shown in the figu re.

Applets

do not need to be explicitly constructed.


Srimad Andavan Arts and Science College
Department of Computer Sciecne
▪ There are five methods that are called during the cycle of an applet. They
are init(),start(),stop(),paint()and destroy().
• The init(),start(),stop() and destroy() methods are defined by the
java.applet.Applet class, the paint() method is inherited by the Applet
class from the component class, which is the super class of the Applet
class.
1. The init() method provides the capability to load applet parameters and
perform any necessary initialization processing.

Srimad Andavan Arts and Science College


Department of Computer Sciecne
2. The start() method serves as the execution entry point for an applet when it is
initially executed .when a user moves from a web page that contains the applet
to another web page, the execution
of the applet will be stopped.
• The stop() method provides the capability to stop an applet's execution
when the Web page containing the applet is no longer active. It is
called by the web browser.
• The destroy() method is used at the end of an applet's life cycle to
perform any termination processing. It is called by the appletviewer or
by the web browser.
• The paint() method is automatically called by the appletviewer or the web
browser whenever the applet needs to be refreshed.
• Apart from the paint() method ,the update() method and the repaint() method
are also invoked sometimes during the life cycle of an applet.
• When the update() method is invoked ,the present screen contents will be
removed and the full screen will be painted again with the background color
• When the repaint() method is invoked ,it calls the update() method .

The Applet Class:


The applet class provides all necessary support for applet executions
such as starting and stopping it also provides methods that load and display images
and methods that load and play audio clips.
o The java Applet class extends java.lanag.object, java.awt.Component,
java.awt.Container and java.awt.Panel classes. The hierarchy of inheritance is
shown below.

Srimad Andavan Arts and Science College


Department of Computer Sciecne
java.lang.object

java.awt.Component

java.awt.Cotainer

java.awt.Panel

java.applet.Applet

o The java.awt.Component class is an important class that has many useful


methods. They are, 1.paint() 2.update() 3.repaint() 4.setFont() 5.getFont()
6.setSize() 7.getSize() 8.setBackground() 9.setForeground()
o These classes provide support for java’s window based, graphical interface.
Applet Architecture
An applet is a window-based program. Its architecture is different
from normal java programs.
29. Applets are event driven,
1. An applet resembles a set of interrupt service routines.
2. An applet waits until an event occurs.
3. The AWT notifies the applet about an event by calling an event handler.
30. The user initiates interaction with an applet,
▪ The user interacts with the applet, as they want.
▪ These interactions are sent to the applet as events to which the applet must
respond.
▪ Eg) When a user clicks a mouse inside the applets window has input focus, a
key press event is generated.
Applet Skeleton
import java.awt.*;
import java.applet.*;
public class appletskele extends Applet
{
public void init()
{
//Initialization
}

public void start()


{
Srimad Andavan Arts and Science College
Department of Computer Sciecne
//Start or resume execution
}
public void stop()
{
//Suspends Execution
}
public void destroy()
{
//Perform shutdown operation
}
public void paint(Graphics g)
{
//Redisplay contents of window
}
}

▪ These are the five methods that provide basic mechanism by which the
browser or applet viewer interface to the applet and control its execution.
▪ This skeleton does not do anything, it can be compiled and run.
Syntax of the HTML Applet Tag
<applet
[codebase=codebase-url]
code=”appletname.class”
[alt=alternate-text]
[name=applet-instance-name]
width=pixels
height=pixels
[align=alignment]
[vspace=pixels]
[hspace=pixels]
>
[<param name=name1 value=value1>]
[<param name=name2 value=value2>]
…….
.. …….
</applet>
• From the above applet tag, the attributes shown inside the [ ] brackets are
optional.

Srimad Andavan Arts and Science College


Department of Computer Sciecne
• Other than the attributes closed inside of [ ] bracket must be important for
creating an applet tag.
1. codebase : This entry is used to specify the URL of the directory in which the
applet resides
2. code=Appletname.class : This attribute is compulsory. It is used to specify the
name of the class file.
3. width=pixels height=pixels : To specify the width and height of the applet
output frame.
4. alt =alternate-text : It is optional. On java-enabled web browsers cannot
recognize and execute the applet code. Such browsers will display this alternate
text in the place of the applet’s output.
5. Name=applet-instance-name : This is optional. This entry specifies the name
for the applet
6. align=alignment : This is optional. This specifies the alignment, according to
which the applet’s output will appear.
7. vspace =pixels : This is optional. This specifies the amount of vertical blank
space of the web page
8. hspace =pixels : This is optional. This specifies the amount of horizontal blank
space of the web page.
Execution of an Applet Program
//File Name: Hello. java
import java.awt.*;
import java.applet.*;
public class Hello extends Applet
{
public void paint(Graphics g)
{
g.drawString(”Hello”,100,100);
}
}
//File Name: Hello.html
<html>
Srimad Andavan Arts and Science College
Department of Computer Sciecne
<body>
<applet code=”Hello. class” width=500 height=500>
</applet>
</body>
</html>
o Each applet program should have the public access control modifier.
o To run the applet program a html code should be created and it should be saved
in a file name as the program name with html extension.

Methods in the Graphics Class


S.No Method Description
To draw a line between
1. void drawLine(int x,int y,int x1,int y1) points(x,y) and (x1,y1)
To draw a rectangle with upper-
2. void drawRect(int x,int y,int w,int h) left corner at the co-ordinates x
and y,width w and height h.
3. void drawString(String s,int x,int y) To draw a string s at location (x,y)
To draw an oval, the centre of
4. void drawOval(int x,int y,int w,int h) the oval will be the same as centre
of a rectangle with upper- left
corner at x and y, width w and
height h.
To draw a polygon with n
5. void drawPolygan(int x[],int y[],int n) vertices. The co-ordinates are
given by the elements of the
arrays x and y. The first and last
points of the polygon are
automatically connected.
To draw an Arc starting from
degree0 and the length
6. void drawArc(int x,int y,int w,int corresponding to degree1. The
h,int degree0,int degree1) centre of the arc will be same as
Srimad Andavan Arts and Science College
Department of Computer Sciecne
the centre of a rectangle with
upper-left corner at co-ordinates x
and y, width w and height h.
To fill a rectangle with upper-left
7. void fillRect(int x,int y,int w,int h) corner at co-ordinates x and y,
width w and height h.
To fill an oval. The centre of the
8. void fillOval(int x,int y,int w,int h) oval will be same as the centre of
the rectangle with upper-left
corner at x and y, width w and
height h
To fill an arc starting from
9. void fillArc(int x,int y,int w,int h,int degree0 and of the length
degree0,int degree1) corresponding to degree1.

Passing Parameters in Applet


15. The applet tag in html allows us to pass parameters to the applet.
16. To retrieve a parameter,getParameter() method is used.
17. This retrieve method returns the value of the specified parameter in the form of
String object.
18. For the numeric and boolean values, we need to convert their string representation
into their internal formats.
Program for passing parameters to an applet
import java.awt.*;
import java.applet.*;
public class paramdemo extends Applet
{
String name;
int age;
public void start()
{
name=getParameter(“sname”);
age=Integer.parseInt(getParameter(“sage”));
}
Srimad Andavan Arts and Science College
Department of Computer Sciecne
public void paint(Graphics g)

Srimad Andavan Arts and Science College


Department of Computer Sciecne
{
g.drawString(“Name : “+name,100,100);
g.drawString(“Age : “+age,100,150);
}
}
/*<applet code=” paramdemo.class” width=500 height=500>
<param name=sname value=vino>
<param name=sage value=25>
</applet>*/
Output:

Srimad Andavan Arts and Science College


Department of Computer Sciecne

You might also like