0% found this document useful (0 votes)
5 views29 pages

Mca(scheme- 2022 ) 2nd sem (Java) module 5

This document provides an overview of GUI programming in Java, focusing on AWT and Swing frameworks. It explains the hierarchy of components, types of containers, and key classes such as JFrame, JDialog, JPanel, JButton, JLabel, and JTextField, along with their constructors and commonly used methods. Additionally, it highlights the differences between AWT and Swing, emphasizing the advantages of Swing in terms of lightweight components and platform independence.

Uploaded by

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

Mca(scheme- 2022 ) 2nd sem (Java) module 5

This document provides an overview of GUI programming in Java, focusing on AWT and Swing frameworks. It explains the hierarchy of components, types of containers, and key classes such as JFrame, JDialog, JPanel, JButton, JLabel, and JTextField, along with their constructors and commonly used methods. Additionally, it highlights the differences between AWT and Swing, emphasizing the advantages of Swing in terms of lightweight components and platform independence.

Uploaded by

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

OBJECT ORIENTED PROGRAMMING USING JAVA

MODULE- 5 GUI PROGRAMMING AND APPLETS


GUI (Graphical User Interface
• GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for Java
applications.
• It is mainly made of graphical components like buttons, labels, windows, etc. through which
the user can interact with an application.
• GUI plays an important role to build easy interfaces for Java applications.
AWT class hierarchy:
• AWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.
• AWT components are platform-dependent i.e components are displayed according
to the view of operating system. AWT is heavyweight i.e. its components are using the
resources of OS.
• The java.awt package provides classes for AWT api such as TextField, Label,
TextArea,RadioButton, CheckBox, Choice, List etc.

Container
• The Container is one of the components in AWT that contains other components like
buttons, text fields, labels, etc.
• The classes that extend the Container class are known as containers such as Frame, Dialog,
and Panel as shown in the hierarchy.
Types of containers
• Container refers to the location where components can be added like text field, button,
checkbox, etc.
• There are four types of containers available in AWT, that is, Window, Frame, Dialog, and
Panel.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 1


OBJECT ORIENTED PROGRAMMING USING JAVA

• As shown in the hierarchy above, Frame and Dialog are subclasses of the Window class.
1. Window: The window is a container that does not have borders and menu bars. In order to create
a window, you can use frame, dialog or another window.
2. Panel: The Panel is the container/class that doesn’t contain the title bar and menu bars. It has
other components like buttons, text fields, etc.
3. Dialog: The Dialog is the container or class having a border and title. We cannot create an
instance of the Dialog class without an associated instance of the respective Frame class.
4. Frame: The Frame is the container or class containing the title bar and might also have menu
bars. It can also have other components like text field, button, etc.

Introduction to Swing
• Swing is used to create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.
• Unlike AWT, Java Swing provides platform-independent and lightweight components.
• The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing


• AWT and Swing are used to develop window-based applications in Java.
• Awt is an abstract window toolkit that provides various component classes like Label,
Button, TextField, etc., to show window components on the screen. All these classes are
part of the Java.awt package.
• Swing is the part of JFC (Java Foundation Classes) built on the top of AWT and written
entirely in Java.
• The javax.swing API provides all the component classes like JButton, JTextField,
JCheckbox, JMenu, etc.

Context AWT Swing

API Package The AWT Component classes are The Swing component classes are
provided by the java.awt package. provided by the javax.swing package.

Operating System The Components used in AWT are The Components used in Swing are
mainly dependent on the operating not dependent on the operating
system. system. It is completely scripted in
Java.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 2


OBJECT ORIENTED PROGRAMMING USING JAVA

Weightiness The AWT is heavyweight since it The Swing is mostly lightweight


uses the resources of the operating since it doesn't need any Operating
system. system object for processing. The
Swing Components are built on the
top of AWT.

Appearance The Appearance of AWT The Swing Components are


Components is mainly not configurable and mainly support
configurable. It generally depends pluggable look and feel.
on the operating system's look and
feels.

Number of The Java AWT provides a smaller Java Swing provides a greater number
Components number of components in of components than AWT, such as
comparison to Swing. list, scroll panes, tables, color
choosers, etc.

Full-Form Java AWT stands for Abstract Java Swing is mainly referred to as
Window Toolkit. Java Foundation Classes (JFC).

Functionality and Java AWT many features that are Swing components provide the
Implementation completely developed by the higher-level inbuilt functions for the
developer. It serves as a thin layer developer that facilitates the coder to
of development on the top of the write less code.
OS.

Memory Java AWT needs a higher amount Java Swing needs less memory space
of memory for the execution. as compared to Java AWT.

Speed Java AWT is slower than swing in Java Swing is faster than the AWT.
terms of performance.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 3


OBJECT ORIENTED PROGRAMMING USING JAVA

Hierarchy of Swing classes


The hierarchy of java swing API is given below.

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.

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

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

public void setVisible(boolean b) sets the visibility of the component. It is by default


false.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 4


OBJECT ORIENTED PROGRAMMING USING JAVA

Java Swing Examples


There are two ways to create a frame:
• By creating the object of Frame class (association)
• By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.
Simple Java Swing Example
File: FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame(); //creating instance of JFrame
JButton b=new JButton("click"); //creating instance of JButton
b.setBounds(130,100,100, 40); //x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500); //400 width and 500 height
f.setLayout(null); //using no layout managers
f.setVisible(true);//making the frame visible
} }
Output:

SINDHU S L,ASST PROFESSOR,BIET, DVG. 5


OBJECT ORIENTED PROGRAMMING USING JAVA

Container
• The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such
as Frame, Dialog and Panel.
• It is basically a screen where the components are placed at their specific locations. Thus it
contains and controls the layout of components.
Note: A container itself is a component (see the above diagram), therefore we can add a container
inside container.
JFrame:
• The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.
• JFrame works like the main window where components like labels, buttons, textfields are
added to create a GUI.
• Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
JFrame Example
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JFrameExample {
public static void main(String s[]) {
JFrame frame = new JFrame("JFrame Example");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("JFrame By Example");
JButton button = new JButton();
button.setText("Button");
panel.add(label);
panel.add(button);
frame.add(panel);
frame.setSize(200, 300);
frame.setLocationRelativeTo(null);

SINDHU S L,ASST PROFESSOR,BIET, DVG. 6


OBJECT ORIENTED PROGRAMMING USING JAVA

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output

JDialog
• The JDialog control represents a top level window with a border and a title used to take
some form of input from the user. It inherits the Dialog class.
• Unlike JFrame, it doesn't have maximize and minimize buttons.
JDialog class declaration
Syntax:
public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneContainer

Commonly used Constructors:

Constructor Description

JDialog() It is used to create a modeless dialog without a title and


without a specified Frame owner.

JDialog(Frame owner) It is used to create a modeless dialog with specified Frame as


its owner and an empty title.

JDialog(Frame owner, String title, It is used to create a dialog with the specified title, owner
boolean modal) Frame and modality.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 7


OBJECT ORIENTED PROGRAMMING USING JAVA

Java JDialog Example


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample
{
private static JDialog d;
DialogExample()
{
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 8


OBJECT ORIENTED PROGRAMMING USING JAVA

Output:

JPanel
• The JPanel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the JComponents class.
• It doesn't have title bar.
JPanel class declaration
public class JPanel extends JComponent implements Accessible
Commonly used Constructors:

Constructor Description

JPanel() It is used to create a new JPanel with a double buffer and a flow
layout.

JPanel(boolean It is used to create a new JPanel with FlowLayout and the specified
isDoubleBuffered) buffering strategy.

JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout manager.

JPanel Example
import java.awt.*;
import javax.swing.*;
public class PanelExample {
PanelExample()
{
JFrame f= new JFrame("Panel Example");

SINDHU S L,ASST PROFESSOR,BIET, DVG. 9


OBJECT ORIENTED PROGRAMMING USING JAVA

JPanel panel=new JPanel();


panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Output:

SINDHU S L,ASST PROFESSOR,BIET, DVG. 10


OBJECT ORIENTED PROGRAMMING USING JAVA

JButton
• The JButton class is used to create a labeled button that has platform independent
implementation.
• The application result in some action when the button is pushed. It inherits AbstractButton
class.
JButton class declaration
public class JButton extends AbstractButton implements Accessible
Commonly used Constructors:

Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

Button Example
import javax.swing.*;
public class ButtonExample
{
public static void main(String[] args)
{
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 11


OBJECT ORIENTED PROGRAMMING USING JAVA

Output:

JLabel
• The object of JLabel class is a component for placing text in a container.
• It is used to display a single line of read only text.
• The text can be changed by an application but a user cannot edit it directly.
• It inherits JComponent class.
JLabel class declaration
public class JLabel extends JComponent implements SwingConstants, Accessible

Commonly used Constructors:

Constructor Description

JLabel() Creates a JLabel instance with no image and with an


empty string for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image,
horizontalAlignment) and horizontal alignment.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 12


OBJECT ORIENTED PROGRAMMING USING JAVA

Commonly used Methods:

Methods Description

String getText() t returns the text string that a label displays.

void setText(String text) It defines the single line of text this component will
display.

void setHorizontalAlignment(int It sets the alignment of the label's contents along the X
alignment) axis.

Icon getIcon() It returns the graphic image that the label displays.

int getHorizontalAlignment() It returns the alignment of the label's contents along the
X axis.

JLabel Example
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 13


OBJECT ORIENTED PROGRAMMING USING JAVA

Output:

JTextField
• The object of a JTextField class is a text component that allows the editing of a single line
text. It inherits JTextComponent class.

JTextField class declaration


public class JTextField extends JTextComponent implements SwingConstants

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text.

JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.

JTextField(int columns) Creates a new empty TextField with the specified number of
columns.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 14


OBJECT ORIENTED PROGRAMMING USING JAVA

Commonly used Methods:

Methods Description

void addActionListener(ActionListener l) It is used to add the specified action listener to receive


action events from this textfield.

Action getAction() It returns the currently set Action for this ActionEvent
source, or null if no Action is set.

void setFont(Font f) It is used to set the current font.

void It is used to remove the specified action listener so that it


removeActionListener(ActionListener l) no longer receives action events from this textfield.

JTextField Example
import javax.swing.*;
class TextFieldExample {
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 15


OBJECT ORIENTED PROGRAMMING USING JAVA

Output:

JTextArea
• The object of a JTextArea class is a multi line region that displays text.
• It allows the editing of multiple line text. It inherits JTextComponent class

JTextArea class declaration


public class JTextArea extends JTextComponent

Commonly used Constructors:

Constructor Description

JTextArea() Creates a text area that displays no text initially.

JTextArea(String s) Creates a text area that displays specified text initially.

JTextArea(int row, int column) Creates a text area with the specified number of rows and columns
that displays no text initially.

JTextArea(String s, int row, int Creates a text area with the specified number of rows and columns
column) that displays specified text.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 16


OBJECT ORIENTED PROGRAMMING USING JAVA

Commonly used Methods:

Methods Description

void setRows(int rows) It is used to set specified number of rows.

void setColumns(int cols) It is used to set specified number of columns.

void setFont(Font f) It is used to set the specified font.

void insert(String s, int position) It is used to insert the specified text on the specified position.

void append(String s) It is used to append the given text to the end of the document.

JTextArea Example
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 17


OBJECT ORIENTED PROGRAMMING USING JAVA

Output:

LayoutManagers
• The LayoutManagers are used to arrange components in a particular manner.
• The Java LayoutManagers facilitates us to control the positioning and size of the
components in GUI forms.
• LayoutManager is an interface that is implemented by all the classes of layout managers.

There are the following classes that represent the layout managers:
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
javax.swing.BoxLayout
javax.swing.GroupLayout
javax.swing.ScrollPaneLayout
javax.swing.SpringLayout etc.
BorderLayout
• The BorderLayout is used to arrange the components in five regions: north, south, east,
west, and center.
• Each region (area) may contain one component only.
• It is the default layout of a frame or window.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 18


OBJECT ORIENTED PROGRAMMING USING JAVA

The BorderLayout provides five constants for each region:


public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
Constructors of BorderLayout class:
BorderLayout(): creates a border layout but with no gaps between the components.
BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical
gaps between the components.
Example of BorderLayout class: Using BorderLayout() constructor
FileName: Border.java
import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border()
{
f = new JFrame();
// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center

SINDHU S L,ASST PROFESSOR,BIET, DVG. 19


OBJECT ORIENTED PROGRAMMING USING JAVA

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

GridLayout
• The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.
Constructors of GridLayout class
GridLayout(): creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no
gaps between the components.
GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows
and columns along with given horizontal and vertical gaps.

Example of GridLayout class: Using GridLayout() Constructor


import java.awt.*;

SINDHU S L,ASST PROFESSOR,BIET, DVG. 20


OBJECT ORIENTED PROGRAMMING USING JAVA

import javax.swing.*;
public class GridLayoutExample
{
JFrame frameObj;
GridLayoutExample()
{
frameObj = new JFrame();
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
// adding buttons to the frame
frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);
// setting the grid layout using the parameterless constructor
frameObj.setLayout(new GridLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
public static void main(String argvs[])
{
new GridLayoutExample();
}
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 21


OBJECT ORIENTED PROGRAMMING USING JAVA

Output:

FlowLayout
• The Java FlowLayout class is used to arrange the components in a line, one after another (in
a flow). It is the default layout of the applet or panel.
Fields of FlowLayout class
public static final int LEFT
public static final int RIGHT
public static final int CENTER
public static final int LEADING
public static final int TRAILING

Constructors of FlowLayout class


FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and
vertical gap.
FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the
given horizontal and vertical gap.

Example of FlowLayout class: Using FlowLayout() constructor


import java.awt.*;
import javax.swing.*;
public class FlowLayoutExample
{
JFrame frameObj;

SINDHU S L,ASST PROFESSOR,BIET, DVG. 22


OBJECT ORIENTED PROGRAMMING USING JAVA

FlowLayoutExample()
{
frameObj = new JFrame();
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");
// adding the buttons to frame
frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b4);
frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.add(b8);
frameObj.add(b9); frameObj.add(b10);
// parameter less constructor is used
// therefore, alignment is center
// horizontal as well as the vertical gap is 5 units.
frameObj.setLayout(new FlowLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 23


OBJECT ORIENTED PROGRAMMING USING JAVA

Output:

Applet
• Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage/Features of Applet
There are many advantages of applet. They are as follows:
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac Os etc.
• Applet is a small and easy-to-write Java program.
• One can easily install Java applet along with various HTML documents.
• One needs a web browser (Java based) to use applets.
• Applet do not have access to the network or local disk and can only access browser-specific
services.
• It cannot perform system operations on local machines.
• Applet cannot establish access to local system.

Drawback of Applet
• Plugin is required at client browser to execute applet.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 24


OBJECT ORIENTED PROGRAMMING USING JAVA

Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the
subclass of Component.

Java Application Vs. Java Applet

Parameters Java Application Java Applet

Meaning A Java Application also known as The Java applet works on the client side,
application program is a type of and runs on the browser and makes use of
program that independently executes another application program so that we
on the computer. can execute it.

Requirement of Its execution starts with the main( ) It does not require the use of any main()
main( ) method method only. The use of the main( ) is method. Java applet initializes through
mandatory. init( ) method.

Execution It cannot run independently, but It cannot start independently but requires
requires JRE to run. APIs for use (Example. APIs like Web
API).

Installation We need to install the Java application Java applet does not need to be pre-
first and obviously on the local installed.
computer.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 25


OBJECT ORIENTED PROGRAMMING USING JAVA

Connectivity It is possible to establish connections It cannot establish connection to other


with server with other servers. servers.

Operation It performs read and write tasks on a It cannot run the applications on any local
variety of files located on a local computer.
computer.

File access It can easily access a file or data It cannot access the file or data found on
available on a computer system or any local system or computer.
device.

Security Java applications are pretty trusted, Java applets are less reliable. So, they
and thus, come with no security need to be safe.
concerns.

Applet Life Cycle


• 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

SINDHU S L,ASST PROFESSOR,BIET, DVG. 26


OBJECT ORIENTED PROGRAMMING USING JAVA

There are five methods of an applet life cycle, and they are:
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.
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.
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.
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.
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.

Life Cycle Working


• The plug-in software is responsible for managing the life cycle of an applet.
• 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.
• The init(), start(), stop() and destroy() methods belongs to the applet.Applet class.
• The paint() method belongs to the awt.Component class.
• If we want to make a class an Applet class, we need to extend the Applet
• 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.

SINDHU S L,ASST PROFESSOR,BIET, DVG. 27


OBJECT ORIENTED PROGRAMMING USING JAVA

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


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
}

SINDHU S L,ASST PROFESSOR,BIET, DVG. 28


OBJECT ORIENTED PROGRAMMING USING JAVA

public void destroy() {


// code to destroy the applet
}
}
Parameter in Applet
• We can get any information from the HTML file as a parameter.
• For this purpose, Applet class provides a method named getParameter().
Syntax:
public String getParameter(String parameterName)
Example of using parameter in Applet:
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
public void paint(Graphics g){
String str=getParameter("msg");
g.drawString(str,50, 50);
}
}
myapplet.html
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>

SINDHU S L,ASST PROFESSOR,BIET, DVG. 29

You might also like