0% found this document useful (0 votes)
2 views59 pages

Java 3rd Module (4)

The document provides an overview of the Abstract Window Toolkit (AWT) in Java, detailing its components, containers, and event handling mechanisms. It explains the delegation event model, event sources, listeners, and various event classes and interfaces used for GUI development. Additionally, it includes examples of handling mouse events and outlines the steps required for event handling in Java applications.

Uploaded by

charancm
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views59 pages

Java 3rd Module (4)

The document provides an overview of the Abstract Window Toolkit (AWT) in Java, detailing its components, containers, and event handling mechanisms. It explains the delegation event model, event sources, listeners, and various event classes and interfaces used for GUI development. Additionally, it includes examples of handling mouse events and outlines the steps required for event handling in Java applications.

Uploaded by

charancm
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OBJECT ORIENTED PROGRAMMING USING JAVA 3RD MODULE

AWT (Abstract Window Toolkit):

AWT represents a class library to develop applications using GUI. The [Link]
package consists of classes and interfaces to develop GUIs.

Component: A component represents an object which is displayed pictorially on the screen


and interacts with the user.

Ex. Button, TextField, TextArea

Container: A Container is a subclass of Component; it has methods that allow other


components to be nested in it. A container is responsible for laying out (that is positioning) any
component that it contains. It does this with various layout managers.

Panel: Panel class is a subclass of Container and is a super class of Applet. When screen output
is redirected to an applet, it is drawn on the surface of the Panel object. In, essence panel is a
window that does not contain a title bar, menu bar or border.
Window: A window represents a rectangular area on the screen without any borders or title
bar. The Window class create a top-level window.

Frame: It is a subclass of Window and it has title bar, menu bar, border and resizing windows.

Delegation Event Model:

The modern approach (from version 1.1 onwards) to handle events is based on the
delegation event model. Its concept is quite simple: a source generates an event and sends it
to one or more listeners.

In this scheme, the listener simply waits until it receives an event. Once an event is received,
the listener processes the event and then returns. The advantage of this design is that the
application logic that processes events is cleanly separated from the user interface logic that
generates those events.
A user interface element is able to ―delegate‖ the processing of an event to a separate
piece of code. In the delegation event model, listeners must register with a source in order to
receive an event notification. This provides an important benefit: notifications are sent only to
listeners that want to receive them.

Events: An event is an object that describes a state change in a source. It can be generated as
a consequence of a person interacting with the elements in a GUI. Some of the activities
that cause events to be generated are pressing a button, entering a character via the
keyboard, selecting an item in a list, and clicking the mouse.

Event Sources: A source is an object that generates an event. Generally sources are
components. Sources may generate more than one type of event.
A source must register listeners in order for the listeners to receive notifications
about a specific type of event. Each type of event has its own registration method.
Here is the general form:
public void addTypeListener (TypeListener el )
Here, Type is the name of the event, and el is a reference to the event listener. For
example, the method that registers a keyboard event listener is called addKeyListener( ).
A source must also provide a method that allows a listener to unregister an
interest in a specific type of event. The general form of such a method is this:
public void removeTypeListener(TypeListener el )

Event Listeners: A listener is an object that is notified when an event occurs. It has two
major requirements.
1. It must have been registered with one or more sources to receive
notifications about specific types of events.
2. It must implement methods to receive and process these notifications.

The methods that receive and process events are defined in a set of interfaces found in
[Link] package.

Sources of Events:

Event Source Description


Button Generates action events when the button is pressed.
Check box Generates item events when the check box is selected or deselected.
Choice Generates item events when the choice is changed.
List Generates action events when an item is double-clicked;
Generates action events when a menu item is selected; generates item
Menu item events when a checkable menu item is selected or deselected.
Scroll bar Generates adjustment events when the scroll bar is manipulated.
Text components Generates text events when the user enters a character.
Generates window events when a window is activated, closed,
Window
deactivated, deiconified, iconified, opened, or quit.

Event Classes and Listener Interfaces:

The [Link] package provides many event classes and Listener interfaces for
event handling. At the root of the Java event class hierarchy is EventObject, which is in
[Link]. It is the super class for all events. It‘s one constructor is shown here:

EventObject(Object src) - Here, src is the object that generates this event.

EventObject contains two methods:


Object getSource( ) - Object on which event initially occurred.
String toString( ) - toString( ) returns the string equivalent of the event.

The class AWTEvent, defined within the [Link] package, is a subclass of


EventObject. It is the superclass (either directly or indirectly) of all AWT-based events used
by the delegation event model. Its getID( ) method can be used to determine the type of the
event. The signature of this method is shown here:
int getID( )
.
The package [Link] defines many types of events that are generated by various user
interface elements

Event Class Description Listener Interface


Generated when a button is pressed, a list
ActionEvent item is double-clicked, or a menu item is ActionListener
selected.
AdjustmentEvent Generated when a scroll bar is manipulated. AdjustmentListener
Generated when a component is hidden,
ComponentEvent ComponentListener
moved, resized, or becomes visible.
Generated when a component is added to or
ContainerEvent ContainerListener
removed from a container.
Generated when a component gains or
FocusEvent FocusListener
losses keyboard focus.
Abstract super class for all component input
InputEvent
event classes.
Generated when a check box or list item is
ItemEvent ItemListener
clicked
Generated when input is received from the
KeyEvent KeyListener
keyboard.
Generated when the mouse is dragged,
moved, clicked, pressed, or released; MouseListener and
MouseEvent
also generated when the mouse enters or MouseMotionListener
exits a component.
Generated when the value of a text area or
TextEvent TextListener
text field is changed.
Generated when a window is activated,
WindowEvent closed, deactivated, deiconified, iconified, WindowListener
opened, or quit.

Useful Methods of Component class:

Method Description
public void add(Component c) inserts a component.
sets the size (width and height) of the
public void setSize(int width,int height)
component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
changes the visibility of the component, by
public void setVisible(boolean status)
default false.
The ActionEvent Class:
An ActionEvent is generated when a button is pressed, a list item is double-clicked, or
a menu item is selected.
The ActionEvent class defines four integer constants that can be used to identify any
modifiers associated with an action event: ALT_MASK, CTRL_MASK, META_MASK (Ex.
Escape), and SHIFT_MASK.

ActionEvent has these three constructors:


o ActionEvent(Object src, int type, String cmd)
o ActionEvent(Object src, int type, String cmd, int modifiers)
o ActionEvent(Object src, int type, String cmd, long when, int modifiers)

You can obtain the command name for the invoking ActionEvent object by using the
getActionCommand( ) method, shown here:
String getActionCommand( ) -Returns the command string associated
with this action

The AdjustmentEvent Class:

An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events.

The user clicked inside the scroll bar to decrease its


BLOCK_DECREMENT
value.
The user clicked inside the scroll bar to increase its
BLOCK_INCREMENT
value.
TRACK The slider was dragged.
The button at the end of the scroll bar was clicked to
UNIT_DECREMENT
decrease its value.
The button at the end of the scroll bar was clicked to
UNIT_INCREMENT
increase its value.

The ComponentEvent Class:

A ComponentEvent is generated when the size, position, or visibility of a component


is changed. There are four types of component events. The ComponentEvent class defines
integer constants that can be used to identify them:
COMPONENT_HIDDEN The component was hidden.
COMPONENT_MOVED The component was moved.
COMPONENT_RESIZED The component was resized.
COMPONENT_SHOWN The component became visible.

ComponentEvent is the superclass either directly or indirectly of ContainerEvent,


FocusEvent, KeyEvent, MouseEvent, and WindowEvent, among others.

The getComponent( ) method returns the component that generated the event. It is
shown here:
Component getComponent( )
The ContainerEvent Class:
A ContainerEvent is generated when a component is added to or removed from a
container. There are two types of container events. The ContainerEvent class defines
constants that can be used to identify them: COMPONENT_ADDED and COMPONENT_REMOVED.

The FocusEvent Class:


A FocusEvent is generated when a component gains or loses input focus. These
events are identified by the integer constants FOCUS_GAINED and FOCUS_LOST.

The InputEvent Class:


The abstract class InputEvent is a subclass of ComponentEvent and is the super class
for component input events. Its subclasses are KeyEvent and MouseEvent.
InputEvent defines several integer constants that represent any modifiers, such as the
control key being pressed, that might be associated with the event. Originally, the InputEvent
class defined the following eight values to represent the modifiers:

ALT_MASK ALT_GRAPH_MASK BUTTON2_MASK BUTTON3_MASK


BUTTON1_MASK CTRL_MASK META_MASK SHIFT_MASK

However, because of possible conflicts between the modifiers used by keyboard events and
mouse events, and other issues, the following extended modifier values were added:

ALT_DOWN_MASK ALT_GRAPH_DOWN_MASK BUTTON1_DOWN_MASK

BUTTON2_DOWN_MASK BUTTON3_DOWN_MASK CTRL_DOWN_MASK

META_DOWN_MASK SHIFT_DOWN_MASK

The KeyEvent Class


A KeyEvent is generated when keyboard input occurs. There are three types of
key events, which are identified by these integer constants: KEY_PRESSED,
KEY_RELEASED, and KEY_TYPED.
The first two events are generated when any key is pressed or released. The last event
occurs only when a character is generated. Remember, not all key presses result in characters.
For example, pressing shift does not generate a character.
There are many other integer constants that are defined by KeyEvent. For example,
VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers
and letters.
The MouseEvent Class:
There are eight types of mouse events. The MouseEvent class defines the following
integer constants that can be used to identify them:
MOUSE_CLICKED The user clicked the mouse
MOUSE_DRAGGED The user dragged the mouse
MOUSE_ENTERED The mouse entered a component
MOUSE_EXITED The mouse exited from a
component.
MOUSE_MOVED The mouse moved
MOUSE_RELEASED The mouse was released.
MOUSE_WHEEL The mouse wheel was moved.

Two commonly used methods in this class are getX( ) and getY( ). These return the X
and Y coordinates of the mouse within the component when the event occurred. Their forms
are shown here:
int getX( )
int getY( )

The TextEvent Class:


Instances of this class describe text events. These are generated by text fields and text
areas when characters are entered by a user or program. TextEvent defines the integer constant
TEXT_VALUE_CHANGED.

The WindowEvent Class:


The WindowEvent class defines integer constants that can be used to identify
different types of events:

WINDOW_ACTIVATED The window was activated.


WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the window be closed.
WINDOW_DEACTIVATED The window was deactivated.
WINDOW_DEICONIFIED The window was deiconified.
WINDOW_GAINED_FOCUS The window was iconified.
WINDOW_ICONIFIED The window gained input focus.
WINDOW_LOST_FOCUS The window lost input focus.
WINDOW_OPENED The window was opened.
EventListener Interfaces:

An event listener registers with an event source to receive notifications about the events
of a particular type. Various event listener interfaces defined in the [Link] package
are given below:

Interface Description
Defines the actionPerformed() method to receive and process
ActionListener action events.
void actionPerformed(ActionEvent ae)
Defines five methods to receive mouse events, such as when a
mouse is clicked, pressed, released, enters, or exits a component
void mouseClicked(MouseEvent me)
MouseListener void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
Defines two methods to receive events, such as when a mouse is
dragged or moved.
MouseMotionListener
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
Defines the adjustmentValueChanged() method to receive and
AdjustmentListner process the adjustment events.
void adjustmentValueChanged(AdjustmentEvent ae)
Defines the textValueChanged() method to receive and process an
TextListener event when the text value changes.
void textValueChanged(TextEvent te)
Defines seven window methods to receive events.
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
WindowListener
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
Defines the itemStateChanged() method when an item has been
ItemListener
void itemStateChanged(ItemEvent ie)
This interface defines two methods: windowGainedFocus( ) and
windowLostFocus( ). These are called when a window gains or
WindowFocusListener loses input focus. Their general forms are shown here:
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
This interface defines four methods that are invoked when a
component is resized, moved, shown, or hidden. Their general
forms are shown here:
ComponentListener void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
This interface contains two methods. When a component is added
to a container, componentAdded( ) is invoked. When a
component is removed from a container, componentRemoved( )
ContainerListener is invoked.
Their general forms are shown here:
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
This interface defines two methods. When a component obtains
keyboard focus, focusGained( ) is invoked. When a component
loses keyboard focus, focusLost( ) is called. Their general forms
FocusListener
are shown here:
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
This interface defines three methods.
void keyPressed(KeyEvent ke)
KeyListener
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)

Steps to perform Event Handling

Following steps are required to perform event handling:


1. Register the component with the Listener
2. Implement the concerned interface

Registration Methods:

For registering the component with the Listener, many classes provide the registration
methods. For example:

 Button
o public void addActionListener(ActionListener a){}
 MenuItem
o public void addActionListener(ActionListener a){}
 TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
 TextArea
o public void addTextListener(TextListener a){}
 Checkbox
o public void addItemListener(ItemListener a){}
 Choice
o public void addItemListener(ItemListener a){}
 List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
 Mouse
o public void addMouseListener(MouseListener a){}
Handling Mouse Events Example Program:

// Demonstrate the mouse event handlers.


import [Link].*;
import [Link].*;
class MouseDemo extends Frame implements MouseListener
{
String msg="";
MouseDemo()
{
addMouseListener(this);

}
public void mouseClicked(MouseEvent me)
{
msg="mouse clicked"; repaint();
}
public void mouseEntered(MouseEvent me)
{ msg="mouse entered";repaint();
}
public void mouseExited(MouseEvent me){
msg="mouse exited";repaint();
}
public void mousePressed(MouseEvent me){
msg="mouse pressed";repaint();
}
public void mouseReleased(MouseEvent me){
msg="mouse released";repaint();
}
public void paint(Graphics g)
{
[Link](msg,200,200);
}
}
class MouseEventsExample
{
public static void main(String arg[])
{
MouseDemo d=new MouseDemo();
[Link](400,400);
[Link](true);
[Link]("Mouse Events Demo Program");

[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
10
Output:

Handling Key Board Events:

import [Link].*;
import [Link].*;
class MyFrame extends Frame implements KeyListener
{
String keystate="Hello GFG";
String msg="";
MyFrame()
{
addKeyListener(this);
addWindowListener(new MyWindow() );
}
public void keyPressed(KeyEvent ke)
{
keystate="Key Pressed";
msg+=[Link]( [Link]());
repaint();
}
public void keyTyped(KeyEvent ke)
{
keystate="Key Typed"; repaint();
msg=msg+[Link]();
}
public void keyReleased(KeyEvent ke)
{
keystate="Key Released"; repaint();
}
public void paint(Graphics g)
{
[Link](keystate,100,50);
[Link](msg,100,100);
}
11
}
class KeyEventsExample
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link]("Key Events Example");
[Link](500,300);
[Link](true);
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});

}
}

Window Events Example Program:


import [Link].*;
import [Link].*;
class WindowEx1 extends Frame implements WindowListener
{
String msg;
WindowEx1(){
addWindowListener(this);
}
public void paint(Graphics g)
{
[Link](msg,150,200);
}
public void windowActivated(WindowEvent arg0) {
msg="activated";
repaint();
}
public void windowClosed(WindowEvent arg0) {
msg="closed"; repaint();
}
public void windowClosing(WindowEvent arg0) {
[Link]("closing");
[Link](0);
}
public void windowDeactivated(WindowEvent arg0) {
msg="deactivated" ;
}
public void windowDeiconified(WindowEvent arg0) {
msg="deiconified" ; repaint();
}
public void windowIconified(WindowEvent arg0) {
msg="iconified" ; repaint();
12
}
public void windowOpened(WindowEvent arg0) {
msg="opened" ; repaint();
}
}
class WindowExample
{
public static void main(String[] args) {
WindowEx1 w=new WindowEx1();
[Link](400,400);
[Link](null);
[Link](true);
}
}

Adapter Classes:

Java provides a special feature, called an adapter class, that can simplify the creation
of event handlers in certain situations. An adapter class provides an empty implementation of
all methods in an event listener interface. Adapter classes are useful when you want to receive
and process only some of the events that are handled by a particular event listener interface.
For example,
MouseListener MouseAdapter
void mouseClicked(MouseEvent me) void mouseClicked(MouseEvent me){ }
void mouseEntered(MouseEvent me) void mouseEntered(MouseEvent me) { }
void mouseExited(MouseEvent me) void mouseExited(MouseEvent me) { }
void mousePressed(MouseEvent me) void mousePressed(MouseEvent me) { }
void mouseReleased(MouseEvent me) void mouseReleased(MouseEvent me) { }

Table: Commonly used Listener Interfaces implemented by Adapter Classes


Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener

Example Program

import [Link].*;
import [Link].*;
class WindowEx1 extends Frame
{
String msg;

13
WindowEx1(){
addWindowListener(new WA());
}
}
class WA extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
}
class WindowAdapterEx
{
public static void main(String[] args) {
WindowEx1 w=new WindowEx1();
[Link](400,400);
[Link](null);
[Link](true);
}
}

Inner Classes:

Inner class is a class defined within another class, or even within an expression.

Example:
import [Link].*;
import [Link].*;
class WindowEx1 extends Frame
{
String msg;
WindowEx1(){
addWindowListener(new WA());
}
class WA extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
}
}
class WindowAdapterInner
{
public static void main(String[] args) {
WindowEx1 w=new WindowEx1();
[Link](400,400);
[Link](null);
[Link](true);

14
}
}

Anonymous Inner Classes:

An anonymous inner class is one that is not assigned a name.

Example:

import [Link].*;
import [Link].*;
class WindowEx1 extends Frame
{
String msg;
WindowEx1(){
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
class WindowAdapterAnonymous
{
public static void main(String[] args) {
WindowEx1 w=new WindowEx1();
[Link](400,400);
[Link](null);
[Link](true);
}
}

Control Fundamentals:
The AWT supports the following types of controls:
 Labels
 Push buttons
 Check boxes
 Choice lists
 Lists
 Scroll bars
 Text Editing
These controls are subclasses of Component

Adding and Removing Controls: To include a control in a window, you must add it to the
window. To do this, you must first create an instance of the desired control and then add it to
a window by calling add(), which is defined by Container.
The General form is:
15
Component add(Component compObj)
Here, compObj is an instance of the control that you want to add. A reference to compObj is
returned.
Sometimes you will want to remove a control from a window when the control is no
longer needed. To do this, call remove( ). This method is also defined by Container. Here is
one of its forms:
void remove(Component obj)
Here, obj is a reference to the control you want to remove. You can remove all controls by
calling removeAll( ).

The HeadlessException:
Most of the AWT controls have constructors that can throw a HeadlessException when
an attempt is made to instantiate a GUI component in a non-interactive environment (such as
one in which no display, mouse, or keyboard is present).

Labels:
A label is an object of type Label, and it contains a string, which it displays. Labels are
passive controls that do not support any interaction with the user. Label defines the following
constructors:
Label( ) throws HeadlessException
Label(String str) throws HeadlessException
Label(String str, int how) throws HeadlessException
The first version creates a blank label. The second version creates a label that contains
the string specified by str. This string is left-justified. The third version creates a label that
contains the string specified by str using the alignment specified by how. The value of how
must be one of these three constants: [Link], [Link], or [Link].

Using Buttons:
A push button is a component that contains a label and that generates an event when
it is pressed. Push buttons are objects of type Button. Button defines these two constructors:
Button( ) throws HeadlessException
Button(String str) throws HeadlessException
The first version creates an empty button. The second creates a button that contains
str as a label.
After a button has been created, you can set its label by calling setLabel( ). You can
retrieve its label by calling getLabel( ). These methods are as follows:
void setLabel(String str)
String getLabel( )
Here, str becomes the new label for the button

Example:
import [Link].*;
import [Link].*;
class MyFrame extends Frame implements ActionListener
16
{
Button b1,b2,b3;
MyFrame()
{
b1=new Button("Red");
b2=new Button("Green");
b3=new Button("Blue");
add(b1); add(b2); add(b3);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
if([Link]()=="Red")
setBackground(new Color(255,0,0));
if([Link]()=="Green")
setBackground(new Color(0,255,0));
if([Link]()=="Blue")
setBackground(new Color(0,0,255));
}
}
class ButtonDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}

Or

import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
Button b1,b2,b3;
MyFrame()
{
b1=new Button("Red");
b2=new Button("Green");
b3=new Button("Blue");
add(b1); add(b2); add(b3);

}
class ButtonDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}

Check Boxes:
A check box is a control that is used to turn an option on or off. It consists of a small
box that can either contain a check mark or not. There is a label associated with each check
box that describes what option the box represents. Check boxes can be used individually or
as part of a group. Check boxes are objects of the Checkbox class.
Checkbox supports these constructors:
Checkbox( ) throws HeadlessException
Checkbox(String str) throws HeadlessException
Checkbox(String str, boolean on) throws HeadlessException
Checkbox(String str, boolean on, CheckboxGroup cbGroup) throws HeadlessException
Checkbox(String str, CheckboxGroup cbGroup, boolean on) throws HeadlessException
The first form creates a check box whose label is initially blank. The state of thecheck
box is unchecked. The second form creates a check box whose label is specified by [Link]
state of the check box is unchecked. The third form allows you to set the initial state of the
check box. If on is true, the check box is initially checked; otherwise, it is cleared. The fourth
and fifth forms create a check box whose label is specified by str and whose group is specified
by cbGroup. If this check box is not part of a group, then cbGroup must be null. The value of
on determines the initial state of the check box.
Methods:
boolean getState( ) - To retrieve the current state of a check box
void setState(boolean on) - to set the state of a check box
String getLabel( ) – returns the label associated with check box
void setLabel(String str) – to set the label
Example:
import [Link].*;
import [Link].*;
class MyFrame extends Frame implements ItemListener
{
String msg="";
Checkbox m,f,t;
MyFrame()
{
m=new Checkbox();
[Link]("Male");
f=new Checkbox("Female",true);
t=new Checkbox("Transzender");

add(m); add(f); add(t);


[Link](this);
[Link](this);
[Link](this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg="Current State";
[Link](msg,150,150);

msg="Male (True/False)"+[Link]();
[Link](msg,150,200);

19
msg="Female (True/False)"+[Link]();
[Link](msg,150,250);

msg="Transzender (True/False)"+[Link]();
[Link](msg,150,300);
}
}
class Demo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}

Or

import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
Checkbox m,f,t;
MyFrame()
{
m=new Checkbox();
[Link]("Male");
f=new Checkbox("Female",true);
t=new Checkbox("Transzender");
add(m); add(f); add(t);
}
}
class Demo
{
public static void main(String arg[])

20
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}

CheckboxGroup(RADIO BUTTON)
It is possible to create a set of mutually exclusive check boxes in which one and only
one check box in the group can be checked at any one time. These check boxes are often called
radio buttons —only one button can be selected at any one time.
To create a set of mutually exclusive check boxes, you must first define the group to
which they will belong and then specify that group when you construct the check boxes. Check
box groups are objects of type CheckboxGroup.
Only the default constructor is defined, which creates an empty group.
Methods:
Checkbox getSelectedCheckbox( ) - which check box in a group is currently selected
void setSelectedCheckbox(Checkbox which) - which is the check box that you want to
be selected. The previously selected check box will be turned off

Example:

import [Link].*;
import [Link].*;
class MyFrame extends Frame implements ItemListener
{
String msg="";
Checkbox m,f,t;
CheckboxGroup cbg;
MyFrame()
{
cbg=new CheckboxGroup();
m=new Checkbox("Male",false,cbg);
f=new Checkbox("Female",false,cbg);
t=new Checkbox("Transzender",false,cbg);
[Link](f);

21
add(m); add(f); add(t);
[Link](this);
[Link](this);
[Link](this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg="Current State : " +[Link]();
[Link](msg,150,150);
}
}
class Demo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}

Or
import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
Checkbox m,f,t;
CheckboxGroup cbg;
MyFrame()
{
cbg=new CheckboxGroup();
m=new Checkbox("Male",false,cbg);
f=new Checkbox("Female",false,cbg);
t=new Checkbox("Transzender",false,cbg);
[Link](f);

add(m); add(f); add(t);


}
}
class Demo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}

Choice Controls:
The Choice class is used to create a pop-up list of items from which the user may
choose. Choice defines only the default constructor, which creates an empty list. To add a
selection to the list, call add( ). It has this general form:

void add(String name) - name is the name of the item being added.
Items are added to the list in the order in which calls to add( ) occur.
Methods:
String getSelectedItem( ) – returns the item which is currently selected
int getSelectedIndex( ) - returns the index of the item. The first item is at index 0. By
default, the first item added to the list is selected.
int getItemCount( ) – returns number of items in the list
void select(int index) - to set the currently selected item with index
void select(String name) - to set the currently selected item with a string
String getItem(int index) – returns the name associated with the index
Example:

23
mport [Link].*;
import [Link].*;
class MyFrame extends Frame implements ItemListener
{
Choice c;
String msg="";
MyFrame()
{
c=new Choice();
[Link]("GFG");
[Link]("MGD");
[Link]("BU");
[Link]("BLR"); add(c);
[Link](this);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
public void paint(Graphics g)
{
msg="Current Selection : "+[Link]();
[Link](msg, 150,150);

msg="Selected Index : "+[Link]();


[Link](msg, 150,200);

msg="Total No of Items : "+[Link]();


[Link](msg, 150,250);
}

}
class ChoiceDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}

Or
import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
Choice c;

MyFrame()
{
c=new Choice();
[Link]("GFG");
[Link]("MGD");
[Link]("BU");
[Link]("BLR");
add(c);
}

}
class ChoiceDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
List:
The List class provides a compact, multiple-choice, scrolling selection list. Unlike the
Choice object, which shows only the single selected item in the menu, a List object can be
constructed to show any number of choices in the visible window. It can also be created to
allow multiple selections.
List provides these constructors:
List( ) throws HeadlessException
List(int numRows) throws HeadlessException
List(int numRows, boolean multipleSelect) throws HeadlessException
The first version creates a List control that allows only one item to be selected at any
one time. In the second form, the value of numRows specifies the number of entries in the list
that will always be visible (others can be scrolled into view as needed). In the third form, if
multipleSelect is true, then the user may select two or more items at a time. If it is false, then
only one item may be selected.
To add a selection to the list, call add( ). It has the following two forms:
void add(String name)
void add(String name, int index)
Here, name is the name of the item added to the list. The first form adds items to the
end of the list. The second form adds the item at the index specified by index. Indexing begins
at zero. You can specify –1 to add the item to the end of the list.

Example:
// Demonstrate Lists.
import [Link].*;
import [Link].*;

class MyFrame extends Frame implements ActionListener


{
List l;
String msg="";
MyFrame()
{
l=new List(2,true);
[Link]("GFG");
[Link]("MGD");
[Link]("BU");
[Link]("BLR");
add(l);

[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
repaint();

26
}
public void paint(Graphics g)
{
for(int i:[Link]())
msg+=i;
[Link](msg,150,150);
msg="";
for(String i:[Link]())
msg+=i;
[Link](msg,150,200);

}
}
class ListDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}

Or
// Demonstrate Lists.
import [Link].*;
import [Link].*;

class MyFrame extends Frame


{
List l;
String msg="";
MyFrame()
{
l=new List(2,true);

27
[Link]("GFG");
[Link]("MGD");
[Link]("BU");
[Link]("BLR");
add(l);

}
}
class ListDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}

TextField:
The TextField class implements a single-line text-entry area. Text fields allow the user
to enter strings and to edit the text using the arrow keys, cut and paste keys, and mouse
selections.
TextField is a subclass of TextComponent. TextField defines the following
constructors:
TextField( ) throws HeadlessException
TextField(int numChars) throws HeadlessException
TextField(String str) throws HeadlessException
TextField(String str, int numChars) throws HeadlessException
The first version creates a default text field. The second form creates a text field that
is numChars characters wide. The third form initializes the text field with the string contained
in str. The fourth form initializes a text field and sets its width.
Methods:
 String getText( ) - To obtain the string currently contained in the text field
28
 void setText(String str) - To set the text, here, str is the new string.
 String getSelectedText( ) - returns currently selected text
 void select(int startIndex, int endIndex) - selects the characters beginning at startIndex
and ending at endIndex –1.
 boolean isEditable( ) – returns boolean value (true/false)
 void setEditable(boolean canEdit) - if canEdit is true, the text may be changed. If it is
false, the text cannot be altered.
 void setEchoChar(char ch) – specified echo character will be displayed in TextField
 boolean echoCharIsSet( ) –returns true or false
 char getEchoChar( ) – returns the echo character

Example:

import [Link].*;
import [Link].*;
class MyFrame extends Frame implements TextListener
{
TextField t ;
String msg="";
MyFrame()
{
Label l=new Label("Enter Name");
t=new TextField(35);
add(l);
add(t);

[Link](this);
}
public void textValueChanged(TextEvent te)
{
repaint();
}
public void paint(Graphics g)
{
msg="Text in the Field : "+[Link]();
[Link](msg,150,150);
msg="Text in the Field : "+[Link]();
[Link](msg,150,200);

msg="is editable:"+[Link]();
[Link]( msg ,150,250);

}
}
29
class TextFieldDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}
Or

import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
TextField t ;
String msg="";
MyFrame()
{
Label l=new Label("Enter Name");
t=new TextField(35);
add(l);
add(t);
}
}
class TextFieldDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)

30
{
[Link](0);
}
});
}
}

TextArea:
Sometimes a single line of text input is not enough for a given task. To handle these
situations, the AWT includes a simple multiline editor called TextArea. Following are the
constructors for TextArea:
TextArea( ) throws HeadlessException
TextArea(int numLines, int numChars) throws HeadlessException
TextArea(String str) throws HeadlessException
TextArea(String str, int numLines, int numChars) throws HeadlessException
TextArea(String str, int numLines, int numChars, int sBars) throws
HeadlessException
Here, numLines specifies the height, in lines, of the text area, and numChars specifies
its width, in characters. Initial text can be specified by str. In the fifth form, you can specify
the scroll bars that you want the control to have. sBars must be one of these values:
SCROLLBARS_BOTH
SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
TextArea is a subclass of TextComponent. Therefore, it supports the getText( ),
setText( ), getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods described
in the preceding section.
TextArea adds the following methods:
void append(String str) - appends the string specified by str to the end of the current
void insert(String str, int index) - inserts the string passed in str at the specified index
void replaceRange(String str, int startIndex, int endIndex) - replaces the characters
from startIndex to endIndex–1, with the replacement text passed in str

Example:
import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
TextArea ta;
MyFrame()
{
ta=new TextArea("PVP Siddhartha Inst. of Technology");

add(ta);
}
}
class TextDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}

Scroll Bars:
Scrollbar control represents a scroll bar component in order to enable user to select
from range of values.
Scroll bars are encapsulated by the Scrollbar class. Scrollbar defines the following
constructors:
Scrollbar( ) throws HeadlessException
Scrollbar(int style) throws HeadlessException
Scrollbar(int style, int initialValue, int thumbSize, int min, int max) throws
HeadlessException

The first form creates a vertical scroll bar. The second and third forms allow you to
specify the orientation of the scroll bar. If style is [Link], a vertical scroll
bar is created. If style is [Link], the scroll bar is horizontal. In the third
form of the constructor, the initial value of the scroll bar is passed in initialValue. The number
of units represented by the height of the thumb is passed in thumbSize. The minimum and
maximum values for the scroll bar are specified by min and max.

Methods:

void setValues(int initialValue, If we construct a scroll bar by using one of the


int thumbSize, int min, int max) first two constructors, then you need to set its
parameters by using setValues()
int getValue( ) To get the current value
void setValue(int newValue) TO set the current value
int getMinimum( ) To get the minimum value
int getMaximum( ) To get the maximum value
Example:

import [Link].*;
import [Link].*;
class MyFrame extends Frame implements AdjustmentListener
{
Scrollbar r,g,b;
String msg="";
MyFrame()
{
r=new Scrollbar(0,20,10,1,255);
g=new Scrollbar(1,20,10,1,255);
b=new Scrollbar(0,20,10,1,255);
add(r,"South");
add(g,"East");
add(b,"North");
[Link](this);
[Link](this);
[Link](this);

}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
setBackground(new Color([Link](),[Link](),[Link]()));
}

}
class ScrollbarDemo2
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Scrollbar Programs...");
[Link](true);
[Link](new BorderLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}

Or

import [Link].*;
import [Link].*;
class MyFrame extends Frame
33
{
Scrollbar r,g,b;
String msg="";
MyFrame()
{
r=new Scrollbar(0,20,10,1,255);
g=new Scrollbar(1,20,10,1,255);
b=new Scrollbar(0,20,10,1,255);
add(r );
add(g);
add(b);

}
class ScrollbarDemo2
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Scrollbar Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}

Layout Manager
A layout manager is a class that is useful to arrange components in a particular manner
in container or a frame.
Java soft people have created a LayoutManager interface in [Link] package which is
implemented in various classes which provide various types of layouts to arrange the
components. The following classes represents the layout managers in Java:
1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
5. GridBagLayout
6. BoxLayout

To set a particular layout, we should first create an object to the layout class and pass
the object to setLayout() method. For example, to set FlowLayout to the container:
34
FlowLayout obj=new FlowLayout();
c. setLayout(obj); // assume c is container

FlowLayout:
FlowLayout is useful to arrange the components in a line one after the other. When a
line is filled with components, they are automatically placed in a next line. This is the default
layout in applets.
Constructors:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
The first form creates the default layout, which centres components and leaves five
pixels of space between each component. The second form lets you specify how each line is
aligned. Valid values for how are as follows:
[Link]
[Link]
[Link]
The third constructor allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively.

Example:
import [Link].*;
import [Link].*;

class MyFrame extends Frame


{
List l;
String msg="";
MyFrame()
{
l=new List(2,true);
[Link]("GFGC");
[Link]("MGD");
[Link]("BU");
[Link]("BLR");
add(l);

}
}
class ListDemo
{
public static void main(String arg[])
{

35
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);
[Link](new FlowLayout());
[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}

BorderLayout:
BorderLayout is useful to arrange the components in the four borders of the frame as
well as in the centre. The borders are identified with the names of the directions. The top border
is specified as ‗North‘, the right side border as ‗East‘, the bottom one as ‗South‘ and the left
one as ‗West‘. The centre is represented as ‗Centre‘.
Constructors:
 BorderLayout( )
 BorderLayout(int horz, int vert)
The first form creates a default border layout. The second allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively.
BorderLayout defines the following constants that specify the regions:
[Link]
[Link]
[Link]
[Link]
[Link]
When adding components, you will use these constants with the following form of
add( ), which is defined by Container:
void add(Component compObj, Object region)
Here, compObj is the component to be added, and region specifies where the component will
be added.

Example:
import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
Button b1,b2,b3,b4,b5;

36
MyFrame()
{
b1=new Button("East");
b2=new Button("West");
b3=new Button("South");
b4=new Button("North");
b5=new Button("Center");
add(b1,"East");
add(b2,"West");
add(b3,"South");
add(b4,"North");
add(b5,"Center");
}
}
class BorderDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);

[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}

GridLayout:
GridLayout is useful to divide the container into a 2D grid form that contains several
rows and columns. The container is divided into equal-sized rectangle; and one component is
placed in each rectangle.

Constructors:
GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)

The first form creates a single-column grid layout. The second form creates a grid
layout with the specified number of rows and columns. The third form allows you to specify
the horizontal and vertical space left between components in horz and vert, respectively.
Either numRows or numColumns can be zero. Specifying numRows as zero allows for
unlimitedlength columns. Specifying numColumns as zero allows for unlimited-length rows.

Example:
import [Link].*;
import [Link].*;
class MyFrame extends Frame
{
Button b1,b2,b3,b4;
MyFrame()
{
setLayout(new GridLayout(2,2,20,20));
b1=new Button("GFGC");
b2=new Button("MGD");
b3=new Button("BU");
b4=new Button("BLR");
add(b1 );
add(b2);
add(b3);
add(b4);
}
}
class GridDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame();
[Link](400,400);
[Link]("Event Handling Programs...");
[Link](true);

[Link](new WindowAdapter(){
public void windowClosing(WindowEvent we)
{
[Link](0);
}
});
}
}

Java AWT MenuItem and Menu


The object of 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 object of Menu class is a pull down menu component which is displayed on the menu
bar. It inherits the MenuItem class.

AWT MenuItem class declaration


1. public class MenuItem extends MenuComponent implements Accessible
AWT Menu class declaration
1. public class Menu extends MenuItem implements MenuContainer, Accessible
Java AWT MenuItem and Menu Example
import [Link].*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
[Link](i1);
[Link](i2);
[Link](i3);
[Link](i4);
[Link](i5);
[Link](submenu);
[Link](menu);
[Link](mb);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new MenuExample();
}
}
Output:

Java JSlider
The Java JSlider class is used to create the slider. By using JSlider, a user can select a value
from a specific range.

Commonly used Constructors of JSlider class


Constructor Description

JSlider() creates a slider with the initial value of 50 and range of 0 to 100.

JSlider(int orientation) creates a slider with the specified orientation set by either [Link]
or [Link] with the range 0 to 100 and initial value 50.

JSlider(int min, int max) creates a horizontal slider using the given min and max.

JSlider(int min, int max, int creates a horizontal slider using the given min, max and value.
value)

JSlider(int orientation, int min, creates a slider using the given orientation, min, max and value.
int max, int value)

Commonly used Methods of JSlider class


Method Description

public void setMinorTickSpacing(int n) is used to set the minor tick spacing to the slider.

public void setMajorTickSpacing(int n) is used to set the major tick spacing to the slider.

public void setPaintTicks(boolean b) is used to determine whether tick marks are painted.
public void setPaintLabels(boolean b) is used to determine whether labels are painted.

public void setPaintTracks(boolean b) is used to determine whether track is painted.

Java JSlider Example


import [Link].*;
public class SliderExample1 extends JFrame{
public SliderExample1() {
JSlider slider = new JSlider([Link], 0, 50, 25);
JPanel panel=new JPanel();
[Link](slider);
add(panel);
}

public static void main(String s[]) {


SliderExample1 frame=new SliderExample1();
[Link]();
[Link](true);
}
}

Output:

Java JSlider Example: painting ticks


import [Link].*;
public class SliderExample extends JFrame{
public SliderExample() {
JSlider slider = new JSlider([Link], 0, 50, 25);
[Link](2);
[Link](10);
[Link](true);
[Link](true);

JPanel panel=new JPanel();


[Link](slider);
add(panel);
}
public static void main(String s[]) {
SliderExample frame=new SliderExample();
[Link]();
[Link](true);
}
}

Output:

Applets
An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java
application, including the following −
 An applet is a Java class that extends the [Link] class.
 A main() method is not invoked on an applet, and an applet class will not define
main().
 Applets are designed to be embedded within an HTML page.
 When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
Applet Life Cycle in Java

In Java, an applet is a special type of program embedded in the web page to generate
dynamic content. Applet is a class in Java.

The applet life cycle can be defined as the process of how the object is created, started,
stopped, and destroyed during the entire execution of its application. It basically has five
core methods namely init(), start(), stop(), paint() and destroy().These methods are invoked
by the browser to execute.

Along with the browser, the applet also works on the client side, thus having less processing
time.
Methods of Applet Life Cycle

There are five methods of an applet life cycle, and they are:

o init(): The init() method is the first method to run that initializes the applet. It can be
invoked only once at the time of initialization. The web browser creates the initialized
objects, i.e., the web browser (after checking the security settings) runs the init()
method within the applet.
o start(): The start() method contains the actual code of the applet and starts the
applet. It is invoked immediately after the init() method is invoked. Every time the
browser is loaded or refreshed, the start() method is invoked. It is also invoked
whenever the applet is maximized, restored, or moving from one tab to another in
the browser. It is in an inactive state until the init() method is invoked.
o stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to
another in the browser, the stop() method is invoked. When we go back to that page,
the start() method is invoked again.
o destroy(): The destroy() method destroys the applet after its work is done. It is
invoked when the applet window is closed or when the tab containing the webpage
is closed. It removes the applet object from memory and is executed only once. We
cannot start the applet once it is destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.
Sequence of method execution when an applet is executed:

1. init()
2. start()
3. paint()

Sequence of method execution when an applet is executed:

1. stop()
2. destroy()

Applet Life Cycle Working


o The Java plug-in software is responsible for managing the life cycle of an applet.
o An applet is a Java application executed in any web browser and works on the client-
side. It doesn't have the main() method because it runs in the browser. It is thus
created to be placed on an HTML page.
o The init(), start(), stop() and destroy() methods belongs to the [Link] class.
o The paint() method belongs to the [Link] class.
o In Java, if we want to make a class an Applet class, we need to extend the Applet
o Whenever we create an applet, we are creating the instance of the existing Applet
class. And thus, we can use all the methods of that class.

Flow of Applet Life Cycle:

These methods are invoked by the browser automatically. There is no need to call them
explicitly.

Syntax of entire Applet Life Cycle in Java/skeleton of applet life cycle


class TestAppletLifeCycle extends Applet {
public void init() {
// initialized objects
}
public void start() {
// code to start the applet
}
public void paint(Graphics graphics) {
// draw the shapes
}
public void stop() {
// code to stop the applet
}
public void destroy() {
// code to destroy the applet
}
}

Java I/O Streams


In Java, streams are the sequence of data that are read from the source and written to the
destination.

An input stream is used to read data from the source. And, an output stream is used to write data to
the destination.

class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
For example, in our first Hello World example, we have used [Link] to print a string. Here,
the System. Out is a type of output stream.

Similarly, there are input streams to take input.

Input stream reads data from source to program and output stream writes file from program to
destination

Types of Streams
Depending upon the data a stream holds, it can be classified into:

Byte Stream
Character Stream

Byte stream is used to read and write a single byte (8 bits) of data.
All byte stream classes are derived from base abstract classes called InputStream and
OutputStream

Character Stream
Character stream is used to read and write a single character of data.

All the character stream classes are derived from base abstract classes Reader and Writer

Java InputStream Class


The InputStream class of the [Link] package is an abstract superclass that
represents an input stream of bytes.
Since InputStream is an abstract class, it is not useful by itself. However, its subclasses
can be used to read data.

Subclasses of InputStream

In order to use the functionality of InputStream, we can use its subclasses. Some of
them are:
 FileInputStream
 ByteArrayInputStream
 ObjectInputStream

Java FileInputStream class


We will learn about all these subclasses in the next tutorial.
Create an InputStream

In order to create an InputStream, we must import the [Link] package


first. Once we import the package, here is how we can create the input stream.

// Creates an InputStream
InputStream object1 = new FileInputStream();

Here, we have created an input stream using FileInputStream. It is


because InputStream is an abstract class. Hence we cannot create an object
of InputStream.
Note: We can also create an input stream from other subclasses of InputStream.

Methods of InputStream

The InputStream class provides different methods that are implemented by its
subclasses. Here are some of the commonly used methods:
 read() - reads one byte of data from the input stream
 read(byte[] array) - reads bytes from the stream and stores in the specified array
 available() - returns the number of bytes available in the input stream
 mark() - marks the position in the input stream up to which data has been read
 reset() - returns the control to the point in the stream where the mark was set
 markSupported() - checks if the mark() and reset() method is supported in the
stream
 skips() - skips and discards the specified number of bytes from the input stream
 close() - closes the input stream

Example: InputStream Using FileInputStream

Here is how we can implement InputStream using the FileInputStream class.


Suppose we have a file named [Link] with the following content.

This is a line of text inside the file.

Let's try to read this file using FileInputStream (a subclass of InputStream).

import [Link];
import [Link];

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

byte[] array = new byte[100];

try {
InputStream input = new FileInputStream("[Link]");

[Link]("Available bytes in the file: " +


[Link]());

// Read byte from the input stream


[Link](array);
[Link]("Data read from the file: ");

// Convert byte array into string


String data = new String(array);
[Link](data);

// Close the input stream


[Link]();
} catch (Exception e) {
[Link]();
}
}
}

Output

Available bytes in the file: 39


Data read from the file:
This is a line of text inside the file

In the above example, we have created an input stream using


the FileInputStream class. The input stream is linked with the file [Link].

InputStream input = new FileInputStream("[Link]");


To read data from the [Link] file, we have implemented these two methods.

[Link](array); // to read data from the input stream


[Link](); // to close the input stream

Java OutputStream Class

The OutputStream class of the [Link] package is an abstract superclass that


represents an output stream of bytes.
Since OutputStream is an abstract class, it is not useful by itself. However, its
subclasses can be used to write data.

Subclasses of OutputStream

In order to use the functionality of OutputStream, we can use its subclasses. Some of
them are:
 FileOutputStream
 ByteArrayOutputStream
 ObjectOutputStream

OutputStreamWriter
We will learn about all these subclasses in the next tutorial.
Create an OutputStream

In order to create an OutputStream, we must import


the [Link] package first. Once we import the package, here is how we
can create the output stream.

// Creates an OutputStream
OutputStream object = new FileOutputStream();

Here, we have created an object of output stream using FileOutputStream. It is


because OutputStream is an abstract class, so we cannot create an object
of OutputStream.

Note: We can also create the output stream from other subclasses of
the OutputStream class.

Methods of OutputStream

The OutputStream class provides different methods that are implemented by its
subclasses. Here are some of the methods:
 write() - writes the specified byte to the output stream
 write(byte[] array) - writes the bytes from the specified array to the output stream
 flush() - forces to write all data present in output stream to the destination
 close() - closes the output stream

Example: OutputStream Using FileOutputStream

Here is how we can implement OutputStream using the FileOutputStream class.

import [Link];
import [Link];
public class Main {

public static void main(String args[]) {


String data = "This is a line of text inside the file.";

try {
OutputStream out = new FileOutputStream("[Link]");

// Converts the string into bytes


byte[] dataBytes = [Link]();

// Writes data to the output stream


[Link](dataBytes);
[Link]("Data is written to the file.");

// Closes the output stream


[Link]();
}

catch (Exception e) {
[Link]();
}
}
}

In the above example, we have created an output stream using


the FileOutputStream class. The output stream is now linked with the file [Link].

OutputStream out = new FileOutputStream("[Link]");

To write data to the [Link] file, we have implemented these methods.

[Link](); // To write data to the file


[Link](); // To close the output stream

When we run the program, the [Link] file is filled with the following content.

This is a line of text inside the file.

Java Reader Class

The Reader class of the [Link] package is an abstract superclass that represents a
stream of characters.
Since Reader is an abstract class, it is not useful by itself. However, its subclasses can
be used to read data.

Subclasses of Reader

In order to use the functionality of Reader, we can use its subclasses. Some of them are:
 BufferedReader
 InputStreamReader
 FileReader
 StringReader

Subclasses of Reader
We will learn about all these subclasses in the next tutorial.

Create a Reader

In order to create a Reader, we must import the [Link] package first. Once we
import the package, here is how we can create the reader.

// Creates a Reader
Reader input = new FileReader();

Here, we have created a reader using the FileReader class. It is because Reader is an
abstract class. Hence we cannot create an object of Reader.

Note: We can also create readers from other subclasses of Reader.

Methods of Reader

The Reader class provides different methods that are implemented by its subclasses.
Here are some of the commonly used methods:
 ready() - checks if the reader is ready to be read
 read(char[] array) - reads the characters from the stream and stores in the specified
array
 read(char[] array, int start, int length) - reads the number of characters
equal to length from the stream and stores in the specified array starting from the start
 mark() - marks the position in the stream up to which data has been read
 reset() - returns the control to the point in the stream where the mark is set
 skip() - discards the specified number of characters from the stream

Example: Reader Using FileReader

Here is how we can implement Reader using the FileReader class.


Suppose we have a file named [Link] with the following content.

This is a line of text inside the file.

Let's try to read this file using FileReader (a subclass of Reader).

import [Link];
import [Link];
class Main {
public static void main(String[] args) {

// Creates an array of character


char[] array = new char[100];

try {
// Creates a reader using the FileReader
Reader input = new FileReader("[Link]");

// Checks if reader is ready


[Link]("Is there data in the stream? " +
[Link]());

// Reads characters
[Link](array);
[Link]("Data in the stream:");
[Link](array);

// Closes the reader


[Link]();
}

catch(Exception e) {
[Link]();
}
}
}

Output

Is there data in the stream? true


Data in the stream:
This is a line of text inside the file.

In the above example, we have created a reader using the FileReader class. The reader
is linked with the file [Link].

Reader input = new FileReader("[Link]");

To read data from the [Link] file, we have implemented these methods.

[Link](); // to read data from the reader


[Link](); // to close the reader
Java Writer Class

The Writer class of the [Link] package is an abstract superclass that represents a
stream of characters.
Since Writer is an abstract class, it is not useful by itself. However, its subclasses can
be used to write data.

Subclasses of Writer

In order to use the functionality of the Writer, we can use its subclasses. Some of them
are:
 BufferedWriter
 OutputStreamWriter
 FileWriter
 StringWriter

Subclasses of Writer
We will learn about all these subclasses in the next tutorial.
Create a Writer

In order to create a Writer, we must import the [Link] package first. Once we
import the package, here is how we can create the writer.

// Creates a Writer
Writer output = new FileWriter();

Here, we have created a writer named output using the FileWriter class. It is because
the Writer is an abstract class. Hence we cannot create an object of Writer.

Note: We can also create writers from other subclasses of the Writer class.

Methods of Writer

The Writer class provides different methods that are implemented by its subclasses.
Here are some of the methods:
 write(char[] array) - writes the characters from the specified array to the output
stream
 write(String data) - writes the specified string to the writer
 append(char c) - inserts the specified character to the current writer
 flush() - forces to write all the data present in the writer to the corresponding
destination
 close() - closes the writer

Example: Writer Using FileWriter

Here is how we can implement the Writer using the FileWriter class.

import [Link];
import [Link];
public class Main {

public static void main(String args[]) {

String data = "This is the data in the output file";

try {
// Creates a Writer using FileWriter
Writer output = new FileWriter("[Link]");

// Writes string to the file


[Link](data);

// Closes the writer


[Link]();
}

catch (Exception e) {
[Link]();
}
}
}

In the above example, we have created a writer using the FileWriter class. The writer
is linked with the file [Link].

Writer output = new FileWriter("[Link]");

To write data to the [Link] file, we have implemented these methods.

[Link](); // To write data to the file


[Link](); // To close the writer

When we run the program, the [Link] file is filled with the following content.

This is a line of text inside the file.

RandomAccessFile

This class is used for reading and writing to random access file. A random access file behaves like
a large array of bytes. There is a cursor implied to the array called file pointer, by moving the
cursor we do the read write operations. If end-of-file is reached before the desired number of byte
has been read than EOFException is thrown. It is a type of IOException.
Constructor
Constructor Description

RandomAccessFile(File Creates a random access file stream to read from, and


file, String mode) optionally to write to, the file specified by the File
argument.

RandomAccessFile(String Creates a random access file stream to read from, and


name, String mode) optionally to write to, a file with the specified name.

Method
Modifier Method Method
and Type

void close() It closes this random access file stream and releases
any system resources associated with the stream.

FileChannel getChannel() It returns the unique FileChannel object associated


with this file.

int readInt() It reads a signed 32-bit integer from this file.

String readUTF() It reads in a string from this file.

void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.

void writeDouble(double It converts the double argument to a long using the


v) doubleToLongBits method in class Double, and then
writes that long value to the file as an eight-byte
quantity, high byte first.

void writeFloat(float v) It converts the float argument to an int using the


floatToIntBits method in class Float, and then writes
that int value to the file as a four-byte quantity, high
byte first.

void write(int b) It writes the specified byte to this file.

int read() It reads a byte of data from this file.

long length() It returns the length of this file.

void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
Example
import [Link];
import [Link];

public class RandomAccessFileExample {


static final String FILEPATH ="[Link]";
public static void main(String[] args) {
try {
[Link](new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
} catch (IOException e) {
[Link]();
}
}
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
[Link](position);
byte[] bytes = new byte[size];
[Link](bytes);
[Link]();
return bytes;
}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
[Link](position);
[Link]([Link]());
[Link]();
}
}

The [Link] contains text "This class is used for reading and writing to random access file."

after running the program it will contains

This class is used for reading I love my country and my peoplele.

You might also like