Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Java Module-5

Java AWT (Abstract Window Toolkit) is an API for developing GUI applications in Java, utilizing platform-dependent components that reflect the operating system's native look and feel. It includes various classes for components like buttons, text fields, and containers, and supports event handling through interfaces such as ActionListener and MouseListener. AWT applications can be created by extending the Frame class or by creating instances of it, allowing for a flexible approach to GUI design.

Uploaded by

varadaraj.navkis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java Module-5

Java AWT (Abstract Window Toolkit) is an API for developing GUI applications in Java, utilizing platform-dependent components that reflect the operating system's native look and feel. It includes various classes for components like buttons, text fields, and containers, and supports event handling through interfaces such as ActionListener and MouseListener. AWT applications can be created by extending the Frame class or by creating instances of it, allowing for a flexible approach to GUI design.

Uploaded by

varadaraj.navkis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User

Interface (GUI) or windows-based applications in Java.


Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavy weight i.e. its
components are using the resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such
as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.
Why AWT is platform independent?
Java AWT calls the native platform calls the native platform (operating systems)
subroutine for creating API components like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button
will have different look and feel for the different platforms like Windows, MAC
OS, and Unix. The reason for this is the platforms have different view for their
native components and AWT directly calls the native subroutine that creates
those components.
In simple words, an AWT application will look like a windows application in
Windows OS whereas it will look like a Mac application in the MAC OS.
Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.
Components
All the elements like the button, text fields, scroll bars, etc. are called
components. In Java AWT, there are classes for each component as shown in
above diagram. In order to place every component in a particular position on a
screen, we need to add them to a container.
Container
The Container is a component in AWT that can contain another components
like buttons, textfields, labels etc. The classes that extends Container class are
known as container such as Frame, Dialog and Panel.
It is basically a screen where the 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.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window. We need to create an
instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is
generic container for holding the components. It can have other components like
button, text field etc. An instance of Panel class creates a container, in which we
can add components.
Frame
The Frame is the container that contain title bar and border and can have menu
bars. It can have other components like button, text field, scrollbar etc. Frame is
most widely used container while developing an AWT application.
Useful Methods of Component Class
Method Description
public void add(Component c) Inserts a component on this
component.
public void setSize(int width,int height) Sets the size (width and
height) of the component.
public void setLayout(LayoutManager Defines the layout manager
m) for the component.
public void setVisible(boolean status) Changes the visibility of the
component, by default false.
Java AWT Example
To create simple AWT example, you need a frame. There are two ways to create
a GUI using Frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
AWT Example by Inheritance
Let's see a simple example of AWT where we are inheriting Frame class. Here,
we are showing Button component on the Frame.
AWTExample1.java
// importing Java AWT class
import java.awt.*;

// extending Frame class to our class AWTExample1


public class AWTExample1 extends Frame {

// initializing using constructor


AWTExample1() {

// creating a button
Button b = new Button("Click Me!!");

// setting button position on screen


b.setBounds(30,100,80,30);

// adding button into frame


add(b);

// frame size 300 width and 300 height


setSize(300,300);

// setting the title of Frame


setTitle("This is our basic AWT example");

// no layout manager
setLayout(null);

// now frame will be visible, by default it is not visible


setVisible(true);
}

// main method
public static void main(String args[]) {

// creating instance of Frame class


AWTExample1 f = new AWTExample1();

The setBounds(int x-axis, int y-axis, int width, int height) method is used in the
above example that sets the position of the awt button.
Output:
AWT Example by Association
Let's see a simple example of AWT where we are creating instance of Frame
class. Here, we are creating a TextField, Label and Button component on the
Frame.
AWTExample2.java
// importing Java AWT class
import java.awt.*;

// class AWTExample2 directly creates instance of Frame class


class AWTExample2 {

// initializing using constructor


AWTExample2() {

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

// creating a Label
Label l = new Label("Employee id:");

// creating a Button
Button b = new Button("Submit");

// creating a TextField
TextField t = new TextField();

// setting position of above components in the frame


l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);

// adding components into frame


f.add(b);
f.add(l);
f.add(t);

// frame size 300 width and 300 height


f.setSize(400,300);

// setting the title of frame


f.setTitle("Employee info");
// no layout
f.setLayout(null);

// setting visibility of frame


f.setVisible(true);
}

// main method
public static void main(String args[]) {

// creating instance of Frame class


AWTExample2 awt_obj = new AWTExample2();

Output:
• Java AWT Label
• Java AWT Button
• Java AWT TextField
• Java AWT Checkbox
• Java AWT CheckboxGroup
• Java AWT Choice
• Java AWT List
• Java AWT Canvas
• AWT Scrollbar
• Java AWT MenuItem & Menu
• Java AWT PopupMenu
• Java AWT Panel
• Java AWT Toolkit

1. Java AWT Label


Syntax of AWT Label
public class Label extends Component implements Accessible
AWT Label Class Constructors
There are three types of Java AWT Label Class
1. Label():
Creates Empty Label.
2. Label(String str):
Constructs a Label with str as its name.
3. Label(String str, int x):
Constructs a label with the specified string and x as the specified alignment
2. Java AWT Button
AWT Button is a control component with a label that generates an event when
clicked on. Button Class is used for creating a labeled button that is platform-
independent.
Syntax of AWT Button
public class Button extends Component implements Accessible
Java AWT Button Class Constructors
There are two types of Button class constructors as mentioned below:
1. Button( ):
Creates a Button with no label i.e. showing an empty box as a button.
2. Button(String str):
Creates a Button with String str as a label. For example if str=”Click Here”
button with show click here as the value.
3. Java AWT TextField
Syntax of AWT TextField:
public class TextField extends TextComponent
TextField Class constructors
There are TextField class constructors are mentioned below:
1. TextField():
Constructs a TextField component.
2. TextField(String text):
Constructs a new text field initialized with the given string str to be displayed.
3. TextField(int col):
Creates a new text field(empty) with the given number of columns (col).
4. TextField(String str, int columns):
Creates a new text field(with String str in the display) with the given number of
columns (col).
4. Java AWT Checkbox
Syntax of AWT Checkbox:
public class Checkbox extends Component implements ItemSelectable, Accessi
ble
Checkbox Class Constructors
There are certain constructors in the AWT Checkbox class as mentioned below:
1. Checkbox():
Creates a checkbox with no label.
2. Checkbox(String str):
Creates a checkbox with a str label.
3. Checkbox(String str, boolean state, CheckboxGroup group):
Creates a checkbox with the str label, and sets the state in the mentioned group.
5. Java AWT CheckboxGroup
CheckboxGroup Class is used to group together a set of Checkbox.
Syntax of AWT CheckboxGroup:
public class CheckboxGroup extends Object implements Serializable
Note: CheckboxGroup enables the use of radio buttons in AWT.
6. Java AWT Choice
The object of the Choice class is used to show a popup menu of choices.
Syntax of AWT Choice:
public class Choice extends Component implements ItemSelectable, Accessible
AWT Choice Class constructor
Choice(): It creates a new choice menu.
7. Java AWT List
The object of the AWT List class represents a list of text items.
Syntax of Java AWT List:
public class List extends Component implements ItemSelectable, Accessible
AWT List Class Constructors
The List of class constructors is defined below:
1. List():
Creates a new list.
2. List(int row):
Creates lists for a given number of rows(row).
3. List(int row, Boolean Mode)
Ceates new list initialized that displays the given number of rows.
8. Java AWT Canvas
Syntax of AWT Canvas:
public class Canvas extends Component implements Accessible
Canvas Class Constructors
1. Canvas():
Creates new Canvas.
2. Canvas(GraphicConfiguration config):
It creates a new Canvas with the given Graphic configuration.
9. AWT Scrollbar
Syntax of AWT Scrollbar:
public class Scrollbar extends Component implements Adjustable, Accessible
Java AWT Scrollbar Class Constructors
There are three constructor classes in Java mentioned below:
1. Scrollbar():
It Creates a new vertical Scrollbar in the Application.
2. Scrollbar(int orientation):
Creates a new vertical Scrollbar with the given orientation.
3. Scrollbar(int orientation, int value, int visible, int mini, int maxi):
Creates a new scrollbar with the orientation mentioned with value as the
default value and [mini, maxi] as the lower and higher limit.
10. Java AWT MenuItem & Menu
MenuItem class adds a simple labeled menu item on the menu. The MenuItem
class allows you to create individual items that can be added to menus. And
Menu is a component used to create a dropdown menu that can contain a list of
MenuItem components.
Syntax of Java AWT MenuItem
public class MenuItem extends MenuComponent implements Accessible
Syntax of Java AWT Menu
public class Menu extends MenuItem implements MenuContainer, Accessible
Java AWT PopupMenu is a component that is used for dynamically popping up
a menu that appears when the user right-clicks or performs any other action on a
component.
Syntax of AWT PopupMenu
public class PopupMenu extends Menu implements MenuContainer, Accessible

12. Java AWT Panel


Java AWT Panel is a container class used to hold and organize graphical
components in a Java Application.
Syntax of Java AWT Panel:
public class Panel extends Container implements Accessible
13. Java AWT Toolkit
Java AWT Toolkit class provides us with a platform-independent way to access
various system resources and functionalities. Subclasses of Toolkit are used to
bind various components.
Syntax of Java AWT Toolkit
public abstract class Toolkit extends Object
Event Handling Components – Java AWT
Here are some of the event handling components in Java:
• Java ActionListener
• Java MouseListener
• Java MouseMotionListener
• Java ItemListener
• Java KeyListener
• Java WindowListener
• Close AWT Window
1. Java ActionListener
Java ActionListner is a interface which responds to the actions performed by the
components like buttons, menu items ,etc.
Syntax of Java ActionListener:
public class ActionListenerExample Implements ActionListener
There is only methods associated with ActionListner class that is
actionPerformed().
Syntax of actionPerformed() method:
public abstract void actionPerformed(ActionEvent e);
2. Java MouseListener
Java MouseListner is a interface that responds to the actions performed by
mouse events generated by the user. Example: mouse clicks , mouse
movements, etc.
There are 5 Methods associated with MouseListner:
1. mouseClicked(MouseEvent e):
Responds to mouse buttons when clicked on a component in the Application.
2. mousePressed(MouseEvent e):
Responds to mouse button is Pressed on a component in the Application.
3. mouseReleased(MouseEvent e):
Responds to Mouse button released after being pressed over a component in the
Application.
4. mouseEntered(MouseEvent e):
Responds to the situation when a Mouse cursor enters the bounds of a
component in an Application.
5. mouseExited(MouseEvent e):
Responds to the situation when a Mouse cursor exits a component’s bounds.
3. Java MouseMotionListener
Java MouseMotionListner is a interface which is notified when mouse is moved
or dragged.
It contains two Methods mentioned below:
1. mouseDragged(MouseEvent e):
Responds when the mouse is dragged with mouse button clicked over a
component in Application.
2. mouseMoved(MouseEvent e):
Responds when the mouse is moved over a component in Application.
4. Java ItemListener
Java ItemListner is an interface which handles events related to item selection
and deselection those that occur with checkboxes, radio buttons, etc. There is
only one Method associated with ItemListner that is itemStateChanged(). This
method provides information about the event, i.e. source of the event and the
changed state.
Syntax of itemStateChanged() method:
itemStateChanged(ItemEvent e)
5. Java KeyListener
Java KeyListner is an interface in Java notified whenever you change the state
of key or can be said for key related events.
Syntax of KeyListener:
public interface KeyListener extends EventListener
There are three methods associated with KeyListner as mentioned below:
1. keyPressed (KeyEvent e):
Responds to the event when key is pressed.
2. keyReleased (KeyEvent e):
Responds to the event when the key is released.
3. keyTyped (KeyEvent e):
Responds to the key has been typed.
6. Java WindowListener
Java WindowListener is a interface used for handling events related to window
actions. Events like opening , closing, minimizing, etc are handled using
WindowListener.
Syntax of WindowListener
public interface WindowListener extends EventListener
There are seven methods associated with WindowListener as mentioned below:
1. windowActivated (WindowEvent e):
Responds when window is first opened
2. windowClosed (WindowEvent e):
Responds when the user attempts to close the window
3. windowClosing (WindowEvent e):
Responds after a window has been closed
4. windowDeactivated (WindowEvent e):
Responds when a window is minimized
5. windowDeiconified (WindowEvent e):
Responds when a window is restored from a minimized state
6. windowIconified (WindowEvent e):
Responds when a window is activated
7. windowOpened (WindowEvent e):
Responds when a window loses focus
7. Java Adapter classes
Java adapter classes provide the default implementation of listener interfaces.
8. Close AWT Window
At the end we will need to Close AWT Window, So to perform this task we will
use dispose() method. This method releases the resources associated with the
window and also removes it from the screen.
Java AWT Examples
program our first Program in Java AWT as Hello World using Labels and
Frames.

// Java AWT Program for Hello World


import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

// Driver Class
public class AWT_Example {
// main function
public static void main(String[] args)
{
// Declaring a Frame and Label
Frame frame = new Frame("Basic Program");
Label label = new Label("Hello World!");

// Aligning the label to CENTER


label.setAlignment(Label.CENTER);

// Adding Label and Setting


// the Size of the Frame
frame.add(label);
frame.setSize(300, 300);

// Making the Frame visible


frame.setVisible(true);

// Using WindowListener for closing the window


frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
Java AWT Program to create Button
Below is the implementation of the Java AWT Program to create a Button:

// Java AWT Program for Button


import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

// Driver Class
public class Button_Example {
// main function
public static void main(String[] args)
{
// Creating instance of frame with the label
Frame frame = new Frame("Example 2");

// Creating instance of button with label


Button button = new Button("Click Here");

// Setting the position for the button in frame


button.setBounds(80, 100, 64, 30);

// Adding button to the frame


frame.add(button);

// setting size, layout and visibility of frame


frame.setSize(300, 300);
frame.setLayout(null);
frame.setVisible(true);

// Using WindowListener for closing the window


frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
Introduction to Swing:

Java Swing is a part of Java Foundation Classes (JFC) that 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.

Swing VS AWT

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.
No. Java AWT Java Swing
1) AWT components are platform- Java swing components
dependent. are platform-independent.
2) AWT components Swing components
are heavyweight. are lightweight.
3) AWT doesn't support pluggable Swing supports pluggable look
look and feel. and feel.
4) AWT provides less Swing provides more powerful
components than Swing. components such as tables, lists,
scrollpanes, colorchooser,
tabbedpane etc.
5) AWT doesn't follows Swing follows MVC.
MVC(Model View Controller)
where model represents data, view
represents presentation and
controller acts as an interface
between model and view.

What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify
the development of desktop applications.
Hierarchy for swing components

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 sets size of the component.
height)
public void sets the layout manager for the component.
setLayout(LayoutManager m)
public void setVisible(boolean b) sets the visibility of the component. It is by
default false.
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


Let's see a simple swing example where we are creating one button and adding
it on the JFrame object inside the main() method.

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
}
}

Example of Swing by Association inside constructor


We can also write all the codes of creating JFrame, JButton and method call
inside the java constructor.

import javax.swing.*;
public class SwingSimple {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


b.setBounds(130,100,100, 40);

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
}

public static void main(String[] args) {


new Simple();
}
}
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above
example that sets the position of the button.

Simple example of Swing by inheritance


We can also inherit the JFrame class, so there is no need to create the instance of
JFrame class explicitly.

import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);

add(b);//adding button on frame


setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new Simple2();
}}
Containers
Containers are an integral part of SWING GUI components. A container
provides a space where a component can be located. A Container in AWT is a
component itself and it provides the capability to add a component to itself.
Following are certain noticable points to be considered.
• Sub classes of Container are called as Container. For example, JPanel,
JFrame and JWindow.
• Container can add only a Component to itself.
• A default layout is present in each container which can be overridden
using setLayout method.
SWING Containers
Following is the list of commonly used containers while designed GUI using
SWING.

Sr.No. Container & Description

Panel
1 JPanel is the simplest container. It provides space in which any other
component can be placed, including other panels.

Frame
2
A JFrame is a top-level window with a title and a border.

Window
3
A JWindow object is a top-level window with no borders and no menubar.

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.
Nested Class
Modifier and Type Class Description

This class implements


protected class JFrame.AccessibleJFrame accessibility support for the
JFrame class.
Fields
Modifier and Type Field Description

protected The accessible


accessibleContext
AccessibleContext context property.

The exit application


static int EXIT_ON_CLOSE default window
close operation.

The JRootPane
instance that
manages the
contentPane and
protected JRootPane rootPane
optional menuBar
for this frame, as
well as the
glassPane.

If true then calls to


add and setLayout
protected boolean rootPaneCheckingEnabled
will be forwarded to
the contentPane.
Constructors
Constructor Description

It constructs a new frame that is initially


JFrame()
invisible.

It creates a Frame in the specified


JFrame(GraphicsConfiguration
GraphicsConfiguration of a screen
gc)
device and a blank title.

It creates a new, initially invisible Frame


JFrame(String title)
with the specified title.

It creates a JFrame with the specified


JFrame(String title, title and the specified
GraphicsConfiguration gc) GraphicsConfiguration of a screen
device.
Useful Methods
Modifier and Method Description
Type

addImpl(Component
Adds the specified child
protected void comp, Object constraints,
Component.
int index)

protected Called by the constructor methods


createRootPane()
JRootPane to create the default rootPane.

Called by the constructors to init


protected void frameInit()
the JFrame properly.

setContentPane(Containe
Void It sets the contentPane property
contentPane)

Provides a hint as to whether or


setDefaultLookAndFeelDe not newly created JFrames should
corated(boolean have their Window decorations
static void
defaultLookAndFeelDecor (such as borders, widgets to close
ated) the window, title...) provided by
the current look and feel.

setIconImage(Image It sets the image to be displayed


Void
image) as the icon for this window.

setJMenuBar(JMenuBar
Void It sets the menubar for this frame.
menubar)

setLayeredPane(JLayeredP
Void It sets the layeredPane property.
ane layeredPane)

It returns the rootPane object for


JRootPane getRootPane()
this frame.

It gets the transferHandler


TransferHandler getTransferHandler()
property.

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);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output

JApplet

JApplet class in Applet


As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing.
class extends the Applet class.
Example of EventHandling in JApplet:

import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener{

JButton b;
JTextField tf;
public void init(){

tf=new JTextField();
tf.setBounds(30,40,150,20);

b=new JButton("Click");
b.setBounds(80,150,70,40);

add(b);add(tf);
b.addActionListener(this);

setLayout(null);
}

public void actionPerformed(ActionEvent e){


tf.setText("Welcome");
}
}
In the above example, we have created all the controls in init() method because it is
invoked only once.

Myapplet.html
<html>
<body>
<applet code="EventJApplet.class" width="300" height="300">
</applet>
</body>
</html>

JDialog

JDialog is a part Java swing package. The main purpose of the dialog is to add
components to it. JDialog can be customized according to user need .
Constructor of the class are:

1. JDialog() : creates an empty dialog without any title or any specified


owner
2. JDialog(Frame o) :creates an empty dialog with a specified frame as its
owner
3. JDialog(Frame o, String s) : creates an empty dialog with a specified
frame as its owner
and a specified title
4. JDialog(Window o) : creates an empty dialog with a specified window
as its owner
5. JDialog(Window o, String t) : creates an empty dialog with a specified
window as its owner and specified title.
6. JDialog(Dialog o) :creates an empty dialog with a specified dialog as its
owner
7. JDialog(Dialog o, String s) : creates an empty dialog with a specified
dialog as its owner and specified title.
Commonly used methods

1. setLayout(LayoutManager m) : sets the layout of the dialog to specified


layout manager
2. setJMenuBar(JMenuBar m) : sets the menubar of the dialog to
specified menubar
3. add(Component c): adds component to the dialog
4. isVisible(boolean b): sets the visibility of the dialog, if value of the
boolean is true then visible else invisible
5. update(Graphics g) : calls the paint(g) function
6. remove(Component c) : removes the component c
7. getGraphics() : returns the graphics context of the component.
8. getLayeredPane() : returns the layered pane for the dialog
9. setContentPane(Container c) :sets the content pane for the dialog
10.setLayeredPane(JLayeredPane l) : set the layered pane for the dialog
11.setRootPane(JRootPane r) : sets the rootPane for the dialog
12.getJMenuBar() : returns the menubar of the component
13.setTransferHandler(TransferHandler n) : Sets the transferHandler
property, which is a mechanism to support transfer of data into this
component.
14.setRootPaneCheckingEnabled(boolean enabled) : Sets whether calls to
add and setLayout are forwarded to the contentPane.
15.setRootPane(JRootPane root) :Sets the rootPane property of the dialog.
16.setGlassPane(Component glass) : Sets the glassPane property of the
dialog.
17.repaint(long time, int x, int y, int width, int height): Repaints the
specified rectangle of this component within time milliseconds.
18.remove(Component c): Removes the specified component from the
dialog.
19.isRootPaneCheckingEnabled() : Returns whether calls to add and
setLayout are forwarded to the contentPane or not .
20.getTransferHandler() : returns the transferHandler property.
21.getRootPane() : Returns the rootPane object for this dialog.
22.getGlassPane() : Returns the glassPane object for this dialog.
23.createRootPane() : Called by the constructor methods to create the
default rootPane.
24.addImpl(Component co, Object c, int i) : Adds the specified child
Component to the dialog.

The following programs will illustrate the use of JDialog


1 .Program to create a simple JDialog

// java Program to create a simple JDialog


import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class solve extends JFrame implements ActionListener {

// frame
static JFrame f;

// main class
public static void main(String[] args)
{
// create a new frame
f = new JFrame("frame");

// create a object
solve s = new solve();

// create a panel
JPanel p = new JPanel();

JButton b = new JButton("click");

// add actionlistener to button


b.addActionListener(s);

// add button to panel


p.add(b);

f.add(p);

// set the size of frame


f.setSize(400, 400);

f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("click")) {
// create a dialog Box
JDialog d = new JDialog(f, "dialog Box");

// create a label
JLabel l = new JLabel("this is a dialog box");

d.add(l);

// setsize of dialog
d.setSize(100, 100);

// set visibility of dialog


d.setVisible(true);
}
}
}

Output:

2. Program to create a dialog within a dialog

// java Program to create a dialog within a dialog


import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class solve extends JFrame implements ActionListener {

// frame
static JFrame f;

// dialog
static JDialog d, d1;

// main class
public static void main(String[] args)
{
// create a new frame
f = new JFrame("frame");

// create a object
solve s = new solve();

// create a panel
JPanel p = new JPanel();

JButton b = new JButton("click");

// add actionlistener to button


b.addActionListener(s);

// add button to panel


p.add(b);

f.add(p);

// set the size of frame


f.setSize(400, 400);

f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("click")) {
// create a dialog Box
d = new JDialog(f, "dialog Box");
// create a label
JLabel l = new JLabel("this is first dialog box");

// create a button
JButton b = new JButton("click me");

// add Action Listener


b.addActionListener(this);

// create a panel
JPanel p = new JPanel();

p.add(b);
p.add(l);

// add panel to dialog


d.add(p);

// setsize of dialog
d.setSize(200, 200);

// set visibility of dialog


d.setVisible(true);
}
else { // create a dialog Box
d1 = new JDialog(d, "dialog Box");

// create a label
JLabel l = new JLabel("this is second dialog box");

d1.add(l);

// setsize of dialog
d1.setSize(200, 200);

// set location of dialog


d1.setLocation(200, 200);

// set visibility of dialog


d1.setVisible(true);
}
}
}

Output :

JPanel

JPanel, a part of the Java Swing package, is a container that can store a group of
components. The main task of JPanel is to organize components, various layouts
can be set in JPanel which provide better organization of components, however,
it does not have a title bar.
Constructors of JPanel
1. JPanel(): creates a new panel with a flow layout
2. JPanel(LayoutManager l): creates a new JPanel with specified
layoutManager
3. JPanel(boolean isDoubleBuffered): creates a new JPanel with a
specified buffering strategy
4. JPanel(LayoutManager l, boolean isDoubleBuffered): creates a new
JPanel with specified layoutManager and a specified buffering strategy
Commonly used Functions of JPanel
1. add(Component c): Adds a component to a specified container
2. setLayout(LayoutManager l): sets the layout of the container to the
specified layout manager
3. updateUI(): resets the UI property with a value from the current look and
feel.
4. setUI(PanelUI ui): sets the look and feel of an object that renders this
component.
5. getUI(): returns the look and feel object that renders this component.
6. paramString(): returns a string representation of this JPanel.
7. getUIClassID(): returns the name of the Look and feel class that renders
this component.
8. getAccessibleContext(): gets the AccessibleContext associated with this
JPanel.
Let us take a sample program in order to illustrate the use of JPanel class by
appending sequential execution snapshots of outputs justifying the below
program sets as follows:
Example:

// Java Program to Create a Simple JPanel


// and Adding Components to it

// Importing required classes


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// Class 1
// Helper class extending JFrame class
class solution extends JFrame {

// JFrame
static JFrame f;

// JButton
static JButton b, b1, b2;

// Label to display text


static JLabel l;

// Main class
public static void main(String[] args)
{
// Creating a new frame to store text field and
// button
f = new JFrame("panel");

// Creating a label to display text


l = new JLabel("panel label");

// Creating a new buttons


b = new JButton("button1");
b1 = new JButton("button2");
b2 = new JButton("button3");

// Creating a panel to add buttons


JPanel p = new JPanel();

// Adding buttons and textfield to panel


// using add() method
p.add(b);
p.add(b1);
p.add(b2);
p.add(l);

// setbackground of panel
p.setBackground(Color.red);

// Adding panel to frame


f.add(p);

// Setting the size of frame


f.setSize(300, 300);

f.show();
}
}

Output:

Example 2:

// Java Program to Create a JPanel with a Border Layout


// and Adding Components to It

// Importing required classes


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// Main class
// Extending JFrame class
class solution extends JFrame {

// JFrame
static JFrame f;

// JButton
static JButton b, b1, b2, b3;

// Label to display text


static JLabel l;

// Main driver method


public static void main(String[] args)
{
// Creating a new frame to store text field and
// button
f = new JFrame("panel");

// Creating a label to display text


l = new JLabel("panel label");

// Creating a new buttons


b = new JButton("button1");
b1 = new JButton("button2");
b2 = new JButton("button3");
b3 = new JButton("button4");

// Creating a panel to add buttons


// and a specific layout
JPanel p = new JPanel(new BorderLayout());

// Adding buttons and textfield to panel


// using add() method
p.add(b, BorderLayout.NORTH);
p.add(b1, BorderLayout.SOUTH);
p.add(b2, BorderLayout.EAST);
p.add(b3, BorderLayout.WEST);
p.add(l, BorderLayout.CENTER);

// setbackground of panel
p.setBackground(Color.red);

// Adding panel to frame


f.add(p);

// Setting the size of frame


f.setSize(300, 300);

f.show();
}
}

Output:

Example 3:

// Java Program to Create a JPanel with a Box layout


// and Adding components to it

// Importing required classes


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// Main class
// Extending JFrame class
class solution extends JFrame {

// JFrame
static JFrame f;

// JButton
static JButton b, b1, b2, b3;

// Label to display text


static JLabel l;

// Main drive method


public static void main(String[] args)
{
// Creating a new frame to store text field and
// button
f = new JFrame("panel");

// Creating a label to display text


l = new JLabel("panel label");

// Creating a new buttons


b = new JButton("button1");
b1 = new JButton("button2");
b2 = new JButton("button3");
b3 = new JButton("button4");

// Creating a panel to add buttons and


// textfield and a layout
JPanel p = new JPanel();

// Setting box layout


p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));

// Adding buttons and textfield to panel


p.add(b);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(l);
// Setting background of panel
p.setBackground(Color.red);

// Adding panel to frame


f.add(p);

// Setting the size of frame


f.setSize(300, 300);

f.show();
}
}

Output:

Overview of swing components

JButton:

The Jbutton class is used to create a 38oolean38 button that has platform
independent implementation. The application result in some action when the
button is pushed. It inherits AbstractButton class.

Jbutton class declaration

Let’s see the declaration for javax.swing.Jbutton class.


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.

Commonly used Methods of AbstractButton class:

Methods Description
void setText(String s) It is used to set specified text
on button
String getText() It is used to return the text of
the button.
Void setEnabled(39oolean b) It is used to enable or disable
the button.
Void setIcon(Icon b) It is used to set the specified
Icon on the button.
Icon getIcon() It is used to get the Icon of
the button.
Void setMnemonic(int a) It is used to set the
mnemonic on the button.
Void addActionListener(ActionListener a) It is used to add the action
listener to this object.

Java Jbutton 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);
}
}

JLabel

Java 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

Let's see the declaration for javax.swing.JLabel class.

1. public class JLabel extends JComponent implements SwingConstants,


Accessible
Commonly used Constructors:
Constructor Description

Creates a JLabel instance with


JLabel() no image and with an empty
string for the title.

Creates a JLabel instance with


JLabel(String s)
the specified text.

Creates a JLabel instance with


JLabel(Icon i)
the specified image.

Creates a JLabel instance with


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

Commonly used Methods:


Methods Description

t returns the text string that a


String getText()
label displays.

It defines the single line of text


void setText(String text)
this component will display.
It sets the alignment of the
void setHorizontalAlignment(int
label's contents along the X
alignment)
axis.

It returns the graphic image that


Icon getIcon()
the label displays.

It returns the alignment of the


int getHorizontalAlignment() label's contents along the X
axis.

Java JLabel Example

1. import javax.swing.*;
2. class LabelExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("Label Example");
7. JLabel l1,l2;
8. l1=new JLabel("First Label.");
9. l1.setBounds(50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. l2.setBounds(50,100, 100,30);
12. f.add(l1); f.add(l2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }
Output:
Java JLabel Example with ActionListener
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LabelExample extends Frame implements ActionListener{
JTextField tf; JLabel l; JButton b;
LabelExample(){
tf=new JTextField();
tf.setBounds(50,50, 150,20);
l=new JLabel();
l.setBounds(50,100, 250,20);
b=new JButton("Find IP");
b.setBounds(50,150,95,30);
b.addActionListener(this);
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try{
String host=tf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new LabelExample();
}}
Output:
JTextField

Java 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
Let's see the declaration for javax.swing.JTextField class.
1. public class JTextField extends JTextComponent implements SwingCon
stants
Commonly used Constructors:
Constructor Description

JTextField() Creates a new TextField

Creates a new TextField


JTextField(String text) initialized with the specified
text.

Creates a new TextField


JTextField(String text, int columns) initialized with the specified
text and columns.

Creates a new empty


JTextField(int columns) TextField with the specified
number of columns.

Commonly used Methods:


Methods Description

It is used to add the


specified action listener to
void addActionListener(ActionListener l)
receive action events from
this textfield.

It returns the currently set


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

It is used to set the current


void setFont(Font f)
font.

It is used to remove the


specified action listener so
void removeActionListener(ActionListener l) that it no longer receives
action events from this
textfield.

Java JTextField Example


1. import javax.swing.*;
2. class TextFieldExample
3. {
4. public static void main(String args[])
5. {
6. JFrame f= new JFrame("TextField Example");
7. JTextField t1,t2;
8. t1=new JTextField("Welcome to Javatpoint.");
9. t1.setBounds(50,100, 200,30);
10. t2=new JTextField("AWT Tutorial");
11. t2.setBounds(50,150, 200,30);
12. f.add(t1); f.add(t2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. }
Output:
Java JTextField Example with ActionListener
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class TextFieldExample implements ActionListener{
4. JTextField tf1,tf2,tf3;
5. JButton b1,b2;
6. TextFieldExample(){
7. JFrame f= new JFrame();
8. tf1=new JTextField();
9. tf1.setBounds(50,50,150,20);
10. tf2=new JTextField();
11. tf2.setBounds(50,100,150,20);
12. tf3=new JTextField();
13. tf3.setBounds(50,150,150,20);
14. tf3.setEditable(false);
15. b1=new JButton("+");
16. b1.setBounds(50,200,50,50);
17. b2=new JButton("-");
18. b2.setBounds(120,200,50,50);
19. b1.addActionListener(this);
20. b2.addActionListener(this);
21. f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
22. f.setSize(300,300);
23. f.setLayout(null);
24. f.setVisible(true);
25. }
26. public void actionPerformed(ActionEvent e) {
27. String s1=tf1.getText();
28. String s2=tf2.getText();
29. int a=Integer.parseInt(s1);
30. int b=Integer.parseInt(s2);
31. int c=0;
32. if(e.getSource()==b1){
33. c=a+b;
34. }else if(e.getSource()==b2){
35. c=a-b;
36. }
37. String result=String.valueOf(c);
38. tf3.setText(result);
39. }
40.public static void main(String[] args) {
41. new TextFieldExample();
42.} }
Output:

JTextArea

Java 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
Let's see the declaration for javax.swing.JTextArea class.
1. public class JTextArea extends JTextComponent
Commonly used Constructors:
Constructor Description
Creates a text area that displays
JTextArea()
no text initially.

Creates a text area that displays


JTextArea(String s)
specified text initially.

Creates a text area with the


specified number of rows and
JTextArea(int row, int column)
columns that displays no text
initially.

Creates a text area with the


specified number of rows and
JTextArea(String s, int row, int column)
columns that displays specified
text.

Commonly used Methods:


Methods Description

It is used to set specified


void setRows(int rows)
number of rows.

It is used to set specified


void setColumns(int cols)
number of columns.

It is used to set the specified


void setFont(Font f)
font.

It is used to insert the


void insert(String s, int position) specified text on the
specified position.

It is used to append the given


void append(String s) text to the end of the
document.

Java JTextArea Example


1. import javax.swing.*;
2. public class TextAreaExample
3. {
4. TextAreaExample(){
5. JFrame f= new JFrame();
6. JTextArea area=new JTextArea("Welcome to javatpoint");
7. area.setBounds(10,30, 200,200);
8. f.add(area);
9. f.setSize(300,300);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13.public static void main(String args[])
14. {
15. new TextAreaExample();
16. }}
Output:

Java JTextArea Example with ActionListener


1. import javax.swing.*;
2. import java.awt.event.*;
3. public class TextAreaExample implements ActionListener{
4. JLabel l1,l2;
5. JTextArea area;
6. JButton b;
7. TextAreaExample() {
8. JFrame f= new JFrame();
9. l1=new JLabel();
10. l1.setBounds(50,25,100,30);
11. l2=new JLabel();
12. l2.setBounds(160,25,100,30);
13. area=new JTextArea();
14. area.setBounds(20,75,250,200);
15. b=new JButton("Count Words");
16. b.setBounds(100,300,120,30);
17. b.addActionListener(this);
18. f.add(l1);f.add(l2);f.add(area);f.add(b);
19. f.setSize(450,450);
20. f.setLayout(null);
21. f.setVisible(true);
22.}
23.public void actionPerformed(ActionEvent e){
24. String text=area.getText();
25. String words[]=text.split("\\s");
26. l1.setText("Words: "+words.length);
27. l2.setText("Characters: "+text.length());
28.}
29.public static void main(String[] args) {
30. new TextAreaExample();
31.}
32.}
Output:

Java JPasswordField
The object of a JPasswordField class is a text component specialized for
password entry. It allows the editing of a single line of text. It inherits
JTextField class.

JPasswordField class declaration


Let's see the declaration for javax.swing.JPasswordField class.
1. public class JPasswordField extends JTextField

Commonly used Constructors:


Constructor Description

Constructs a new JPasswordField, with a default


JPasswordField() document, null starting text string, and 0 column
width.

Constructs a new empty JPasswordField with the


JPasswordField(int columns)
specified number of columns.

Constructs a new JPasswordField initialized with the


JPasswordField(String text)
specified text.

JPasswordField(String text, int Construct a new JPasswordField initialized with the


columns) specified text and columns.

Java JPasswordField Example


1. import javax.swing.*;
2. public class PasswordFieldExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Password Field Example");
5. JPasswordField value = new JPasswordField();
6. JLabel l1=new JLabel("Password:");
7. l1.setBounds(20,100, 80,30);
8. value.setBounds(100,100,100,30);
9. f.add(value); f.add(l1);
10. f.setSize(300,300);
11. f.setLayout(null);
12. f.setVisible(true);
13.}
14.}
Output:
Java JPasswordField Example with ActionListener
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class PasswordFieldExample {
4. public static void main(String[] args) {
5. JFrame f=new JFrame("Password Field Example");
6. final JLabel label = new JLabel();
7. label.setBounds(20,150, 200,50);
8. final JPasswordField value = new JPasswordField();
9. value.setBounds(100,75,100,30);
10. JLabel l1=new JLabel("Username:");
11. l1.setBounds(20,20, 80,30);
12. JLabel l2=new JLabel("Password:");
13. l2.setBounds(20,75, 80,30);
14. JButton b = new JButton("Login");
15. b.setBounds(100,120, 80,30);
16. final JTextField text = new JTextField();
17. text.setBounds(100,20, 100,30);
18. f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b); f.add(te
xt);
19. f.setSize(300,300);
20. f.setLayout(null);
21. f.setVisible(true);
22. b.addActionListener(new ActionListener() {
23. public void actionPerformed(ActionEvent e) {
24. String data = "Username " + text.getText();
25. data += ", Password: "
26. + new String(value.getPassword());
27. label.setText(data);
28. }
29. });
30.}
31.}
Output:

Layout Management

BorderLayout (LayoutManagers)
Java 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:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north,
south, east, west, and center. Each region (area) may contain one component
only. It is the default layout of a frame or window. The BorderLayout provides
five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps between the
components.
o 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 E
AST
JButton b4 = new JButton("WEST");; // the button will be labeled as
WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled a
s CENTER

f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Dir


ection
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Dir
ection
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Directi
on
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direc
tion
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center

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

Example of BorderLayout class: Using BorderLayout(int hgap, int vgap)


constructor
The following example inserts horizontal and vertical gaps between buttons
using the parameterized constructor BorderLayout(int hgap, int gap)
FileName: BorderLayoutExample.java
// import statement
import java.awt.*;
import javax.swing.*;
public class BorderLayoutExample
{
JFrame jframe;
// constructor
BorderLayoutExample()
{
// creating a Frame
jframe = new JFrame();
// create buttons
JButton btn1 = new JButton("NORTH");
JButton btn2 = new JButton("SOUTH");
JButton btn3 = new JButton("EAST");
JButton btn4 = new JButton("WEST");
JButton btn5 = new JButton("CENTER");
// creating an object of the BorderLayout class using
// the parameterized constructor where the horizontal gap is 20
// and vertical gap is 15. The gap will be evident when buttons are
placed
// in the frame
jframe.setLayout(new BorderLayout(20, 15));
jframe.add(btn1, BorderLayout.NORTH);
jframe.add(btn2, BorderLayout.SOUTH);
jframe.add(btn3, BorderLayout.EAST);
jframe.add(btn4, BorderLayout.WEST);
jframe.add(btn5, BorderLayout.CENTER);
jframe.setSize(300,300);
jframe.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new BorderLayoutExample();
}
}
Output:
Java BorderLayout: Without Specifying Region
The add() method of the JFrame class can work even when we do not
specify the region. In such a case, only the latest component added is shown
in the frame, and all the components added previously get discarded. The
latest component covers the whole area. The following example shows the
same.
FileName: BorderLayoutWithoutRegionExample.java
// import statements
import java.awt.*;
import javax.swing.*;

public class BorderLayoutWithoutRegionExample


{
JFrame jframe;

// constructor
BorderLayoutWithoutRegionExample()
{
jframe = new JFrame();

JButton btn1 = new JButton("NORTH");


JButton btn2 = new JButton("SOUTH");
JButton btn3 = new JButton("EAST");
JButton btn4 = new JButton("WEST");
JButton btn5 = new JButton("CENTER");

// horizontal gap is 7, and the vertical gap is 7


// Since region is not specified, the gaps are of no use
jframe.setLayout(new BorderLayout(7, 7));

// each button covers the whole area


// however, the btn5 is the latest button
// that is added to the frame; therefore, btn5
// is shown
jframe.add(btn1);
jframe.add(btn2);
jframe.add(btn3);
jframe.add(btn4);
jframe.add(btn5);

jframe.setSize(300,300);
jframe.setVisible(true);
}

// main method
public static void main(String argvs[])
{
new BorderLayoutWithoutRegionExample();
}
}
Output:
Border

Border Layout Manager in Java


In Java, graphical user interfaces (GUIs) play a crucial role in creating
interactive applications. One of the key aspects of GUI programming is the
layout manager that determines how components are arranged within a
container. The border layout manager is one such layout manager that
simplifies the process of organizing components in a Java GUI.
Layout Managers
Layout managers in Java help control the positioning and sizing of components
within a container. They ensure that components are displayed correctly
regardless of the size of the container or the platform on which the program is
running. Java provides several layout managers, each with its own approach to
organizing components.
Border Layout Manager
The Border Layout Manager is one of the most commonly used layout
managers in Java. It divides a container into five regions: North, South, East,
West, and Center. Each region can hold one component, and the Center region
can hold the main component, that takes up the remaining space.
o North: Positioned at the top of the container. Typically used for titles,
headings, or menus.
o South: Positioned at the bottom of the container. Often used for status
bars or navigation controls.
o East: Positioned to the right of the container. Suitable for components
like toolbars or panels with navigation options.
o West: Positioned to the left of the container. Similar to the East region,
it's suitable for toolbars or panels with navigation options.
o Center: Takes up the remaining space in the container and is typically
used for the main content of the GUI.
Implementation of Border Layout Manager
To use the Border Layout Manager in Java, you'll need to follow these steps:
Create a Container: This can be a JFrame, JPanel, or any other container that
supports layout managers.
Set the Layout Manager: Use the setLayout() method to set the container's
layout manager to BorderLayout. For example:
1. Container container = new Container();
2. container.setLayout(new BorderLayout());
Add Components: Use the add() method to add components to the container,
specifying the region in which you want them to be placed. For example:
1. container.add(component, BorderLayout.NORTH); // Places component i
n the North region
Optional: Specify Constraints: If needed, you can use constants provided by
BorderLayout (e.g., BorderLayout.NORTH, BorderLayout.SOUTH, etc.) to
explicitly set components in specific regions.
Set Container Size: Ensure that your container has a preferred size or use
methods like pack() to automatically size the container based on its components.
Display the Container: If using a JFrame, make sure to set its visibility using
setVisible(true).
Border Layout Manager Java Program
Here's a simple example demonstrating the use of the Border Layout Manager:
import javax.swing.*;
import java.awt.*;
public class BorderLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Border Layout Example");
Container container = frame.getContentPane();
container.setLayout(new BorderLayout());
container.add(new JButton("North"), BorderLayout.NORTH);
container.add(new JButton("South"), BorderLayout.SOUTH);
container.add(new JButton("East"), BorderLayout.EAST);
container.add(new JButton("West"), BorderLayout.WEST);
container.add(new JButton("Center"), BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
In this example, we create a JFrame and set its content pane's layout manager to
BorderLayout. We then add buttons to each region (North, South, East, West,
and Center). When you run this program, you'll see the buttons arranged
accordingly.
Below is a complete Java program that uses the Border Layout Manager to
create a simple GUI with buttons in different regions.
BorderLayoutExample.java
import javax.swing.*;
import java.awt.*;
public class BorderLayoutExample {
public static void main(String[] args) {
// Step 1: Create a JFrame
JFrame frame = new JFrame("Border Layout Example");
// Step 2: Get the content pane and set BorderLayout
Container container = frame.getContentPane();
container.setLayout(new BorderLayout());
// Step 3: Add components to the container
container.add(new JButton("North"), BorderLayout.NORTH);
container.add(new JButton("South"), BorderLayout.SOUTH);
container.add(new JButton("East"), BorderLayout.EAST);
container.add(new JButton("West"), BorderLayout.WEST);
container.add(new JButton("Center"), BorderLayout.CENTER);
// Step 4: Set frame size and properties
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Step 5: Make the frame visible
frame.setVisible(true);
}
}
Output:
When we run this program, a window will appear with buttons labeled "North",
"South", "East", "West", and "Center" arranged according to the Border Layout.
We can resize the window to see how the components adjust to the changes in
size.
The Border Layout Manager is a versatile tool in Java GUI programming that
simplifies the organization of components within a container. By understanding
how to use it, we can create visually appealing and user-friendly graphical
applications. Experimenting with different combinations of components and
regions will help us fine-tune the layout to suit our specific application's needs.

Grid & Flow Layout

Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular
grid. One component is displayed in each rectangle.
Constructors of GridLayout class
1. GridLayout(): creates a grid layout with one column per component in a
row.
2. GridLayout(int rows, int columns): creates a grid layout with the given
rows and columns but no gaps between the components.
3. 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
The GridLayout() constructor creates only one row. The following example
shows the usage of the parameterless constructor.
FileName: GridLayoutExample.java
// import statements
import java.awt.*;
import javax.swing.*;
public class GridLayoutExample
{
JFrame frameObj;

// constructor
GridLayoutExample()
{
frameObj = new JFrame();

// creating 9 buttons
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


// since, we are using the parameterless constructor, therfore;
// the number of columns is equal to the number of buttons we
// are adding to the frame. The row count remains one.
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);
}

// main method
public static void main(String argvs[])
{
new GridLayoutExample();
}
}
Output:
Example of GridLayout class: Using GridLayout(int rows, int columns)
Constructor
FileName: MyGridLayout.java
import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
f=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");
// adding buttons to the frame
f.add(b1); f.add(b2); f.add(b3);
f.add(b4); f.add(b5); f.add(b6);
f.add(b7); f.add(b8); f.add(b9);

// setting grid layout of 3 rows and 3 columns


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

Example of GridLayout class: Using GridLayout(int rows, int columns, int


hgap, int vgap) Constructor
The following example inserts horizontal and vertical gaps between buttons
using the parameterized constructor GridLayout(int rows, int columns, int hgap,
int vgap).
FileName: GridLayoutExample1.java
// import statements
import java.awt.*;
import javax.swing.*;

public class GridLayoutExample1


{

JFrame frameObj;

// constructor
GridLayoutExample1()
{
frameObj = new JFrame();

// creating 9 buttons
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


// since, we are using the parameterless constructor, therefore;
// the number of columns is equal to the number of buttons we
// are adding to the frame. The row count remains one.
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
// a 3 * 3 grid is created with the horizontal gap 20
// and vertical gap 25
frameObj.setLayout(new GridLayout(3, 3, 20, 25));
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new GridLayoutExample();
}
}
Output:
Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one
after another (in a flow). It is the default layout of the applet or panel.
Fields of FlowLayout class
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a
default 5 unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment
and a default 5 unit horizontal and vertical gap.
3. 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
FileName: FlowLayoutExample.java
// import statements
import java.awt.*;
import javax.swing.*;

public class FlowLayoutExample


{

JFrame frameObj;

// constructor
FlowLayoutExample()
{
// creating a frame object
frameObj = new JFrame();

// creating the buttons


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.ad
d(b4);
frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.a
dd(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);
}

// main method
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}
Output:

Example of FlowLayout class: Using FlowLayout(int align) constructor


FileName: MyFlowLayout.java
import java.awt.*;
import javax.swing.*;

public class MyFlowLayout{


JFrame f;
MyFlowLayout(){
f=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");

// adding buttons to the frame


f.add(b1); f.add(b2); f.add(b3); f.add(b4); f.add(b5);

// setting flow layout of right alignment


f.setLayout(new FlowLayout(FlowLayout.RIGHT));

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

Example of FlowLayout class: Using FlowLayout(int align, int hgap, int vgap)
constructor
FileName: FlowLayoutExample1.java
// import statement
import java.awt.*;
import javax.swing.*;

public class FlowLayoutExample1


{
JFrame frameObj;

// constructor
FlowLayoutExample1()
{
// creating a frame object
frameObj = new JFrame();

// creating the buttons


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.ad
d(b4);
frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.a
dd(b8);
frameObj.add(b9); frameObj.add(b10);

// parameterized constructor is used


// where alignment is left
// horizontal gap is 20 units and vertical gap is 25 units.
frameObj.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 25));

frameObj.setSize(300, 300);
frameObj.setVisible(true);
}
// main method
public static void main(String argvs[])
{
new FlowLayoutExample1();
}
}
Output:
Java BoxLayout
The Java BoxLayout class is used to arrange the components either vertically
or horizontally. For this purpose, the BoxLayout class provides four constants.
They are as follows:
Note: The BoxLayout class is found in javax.swing package.
Fields of BoxLayout Class
1. public static final int X_AXIS: Alignment of the components are
horizontal from left to right.
2. public static final int Y_AXIS: Alignment of the components are
vertical from top to bottom.
3. public static final int LINE_AXIS: Alignment of the components is
similar to the way words are aligned in a line, which is based on the
ComponentOrientation property of the container. If the
ComponentOrientation property of the container is horizontal, then the
components are aligned horizontally; otherwise, the components are
aligned vertically. For horizontal orientations, we have two cases: left to
right, and right to left. If the value ComponentOrientation property of the
container is from left to right, then the components are rendered from left
to right, and for right to left, the rendering of components is also from
right to left. In the case of vertical orientations, the components are
always rendered from top to bottom.
4. public static final int PAGE_AXIS: Alignment of the components is
similar to the way text lines are put on a page, which is based on the
ComponentOrientation property of the container. If the
ComponentOrientation property of the container is horizontal, then
components are aligned vertically; otherwise, the components are aligned
horizontally. For horizontal orientations, we have two cases: left to right,
and right to left. If the value ComponentOrientation property of the
container is also from left to right, then the components are rendered from
left to right, and for right to left, the rendering of components is from
right to left. In the case of vertical orientations, the components are
always rendered from top to bottom.
Constructor of BoxLayout class
1. BoxLayout(Container c, int axis): creates a box layout that arranges the
components with the given axis.
Example of BoxLayout class with Y-AXIS:
FileName: BoxLayoutExample1.java
import java.awt.*;
import javax.swing.*;

public class BoxLayoutExample1 extends Frame {


Button buttons[];

public BoxLayoutExample1 () {
buttons = new Button [5];

for (int i = 0;i<5;i++) {


buttons[i] = new Button ("Button " + (i + 1));
// adding the buttons so that it can be displayed
add (buttons[i]);
}
// the buttons will be placed horizontally
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}
// main method
public static void main(String args[]){
BoxLayoutExample1 b=new BoxLayoutExample1();
}
}
Output:
Example of BoxLayout class with X-AXIS
FileName: BoxLayoutExample2.java
import java.awt.*;
import javax.swing.*;

public class BoxLayoutExample2 extends Frame {


Button buttons[];

public BoxLayoutExample2() {
buttons = new Button [5];

for (int i = 0;i<5;i++) {


buttons[i] = new Button ("Button " + (i + 1));
// adding the buttons so that it can be displayed
add (buttons[i]);
}
// the buttons in the output will be aligned vertically
setLayout (new BoxLayout(this, BoxLayout.X_AXIS));
setSize(400,400);
setVisible(true);
}
// main method
public static void main(String args[]){
BoxLayoutExample2 b=new BoxLayoutExample2();
}
}
Output:

Example of BoxLayout Class with LINE_AXIS


The following example shows the effect of setting the value of
ComponentOrientation property of the container to RIGHT_TO_LEFT. If we do
not set the value of ComponentOrientation property, then the components would
be laid out from left to right. Comment line 11, and see it yourself.
FileName: BoxLayoutExample3.java
// import statements
import java.awt.*;
import javax.swing.*;

public class BoxLayoutExample3 extends Frame


{
Button buttons[];

// constructor of the class


public BoxLayoutExample3()
{
buttons = new Button[5];
setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); //
line 11

for (int i = 0; i < 5; i++)


{
buttons[i] = new Button ("Button " + (i + 1));

// adding the buttons so that it can be displayed


add (buttons[i]);
}

// the ComponentOrientation is set to RIGHT_TO_LEFT. Therefore,


// the added buttons will be rendered from right to left
setLayout (new BoxLayout(this, BoxLayout.LINE_AXIS));
setSize(400, 400);
setVisible(true);
}

// main method
public static void main(String argvs[])
{
// creating an object of the class BoxLayoutExample3
BoxLayoutExample3 obj = new BoxLayoutExample3();
}
}
Output:
Example of BoxLayout Class with PAGE_AXIS
The following example shows how to use PAGE_AXIS.
FileName: BoxLayoutExample4.java
// import statements
import java.awt.*;
import javax.swing.*;

public class BoxLayoutExample4 extends Frame


{
Button buttons[];
// constructor of the class
public BoxLayoutExample4()
{
JFrame f = new JFrame();
JPanel pnl = new JPanel();
buttons = new Button[5];
GridBagConstraints constrntObj = new GridBagConstraints();

constrntObj.fill = GridBagConstraints.VERTICAL;
for (int i = 0; i < 5; i++)
{
buttons[i] = new Button ("Button " + (i + 1));

// adding the buttons so that it can be displayed


add(buttons[i]);
}

// the components will be displayed just like the line is present on a page
setLayout (new BoxLayout(this, BoxLayout.PAGE_AXIS));
setSize(400, 400);
setVisible(true);
}

// main method
public static void main(String argvs[])
{
// creating an object of the class BoxLayoutExample4
BoxLayoutExample4 obj = new BoxLayoutExample4();
}
}
Output:
The above output shows that the buttons are aligned horizontally. Now, we will
display the buttons vertically using the PAGE_AXIS.
FileName: BoxLayoutExample5.java
// import statementss
import java.awt.*;
import javax.swing.*;

public class BoxLayoutExample5 extends Frame


{
Button buttons[];

// constructor of the class


public BoxLayoutExample5()
{
JFrame f = new JFrame();
buttons = new Button[5];

// Creating a Box whose alignment is horizontal


Box horizontalBox = Box.createHorizontalBox();

// ContentPane returns a container


Container contentPane = f.getContentPane();

for (int i = 0; i < 5; i++)


{
buttons[i] = new Button ("Button " + (i + 1));

// adding the buttons to the box so that it can be displayed


horizontalBox.add(buttons[i]);
}

// adding the box and the borderlayout to the content pane


contentPane.add(horizontalBox, BorderLayout.NORTH);

// now, the rendered components are displayed vertically.


// it is because the box is aligned horizontally
f.setLayout (new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));

f.setSize(400, 400);
f.setVisible(true);
}

// main method
public static void main(String argvs[])
{
// creating an object of the class BoxLayoutExample5
BoxLayoutExample5 obj = new BoxLayoutExample5();
}
}
Output:
Applets

Java 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 of Applet
There are many advantages of applet. They are as follows:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms, including
Linux, Windows, Mac Os etc.
Drawback of Applet
• Plugin is required at client browser to execute applet.

Do You Know
o Who is responsible to manage the life cycle of an applet ?
o How to perform animation in applet ?
o How to paint like paint brush in applet ?
o How to display digital clock in applet ?
o How to display analog clock in applet ?
o How to communicate two applets ?
Hierarchy of Applet

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

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class
provides 1 life cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4
life cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only
once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet
is stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only
once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides
Graphics class object that can be used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?


Java Plug-in software.

How to run an Applet?


There are two ways to run an applet
1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:


To execute the applet by html file, create an applet and compile it. After that
create an html file and place the applet code in html file. Now click the html
file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome",150,150);
}

}
Note: class must be public because its object is created by Java Plugin software
that resides on the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains applet
tag in comment and compile it. After that run it by: appletviewer First.java.
Now Html file is not required but it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome to applet",150,150);
}

}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java
c:\>appletviewer First.java

Displaying Graphics in Applet


java.awt.Graphics class provides many methods for graphics programming.
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to
draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a
rectangle with the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used
to fill rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is
used to draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used
to fill oval with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to
draw line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int
startAngle, int arcAngle): is used to fill a circular or elliptical arc.
10.public abstract void setColor(Color c): is used to set the graphics
current color to the specified color.
11.public abstract void setFont(Font font): is used to set the graphics
current font to the specified font.

Example of Graphics in applet:

import java.applet.Applet;
import java.awt.*;

public class GraphicsDemo extends Applet{

public void paint(Graphics g){


g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);

g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);

}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>

Inheritance hierarchy for applets

Differences between applets and applications

Life Cycle of an applet

An applet is a Java program that can be embedded into a web page. It runs
inside the web browser and works on the client-side. An applet is embedded
in an HTML page using the APPLET or OBJECT tag and hosted on a web
server. The entire life cycle of an applet is managed by the Applet
Container. All applets are sub-classes (either directly or indirectly) of
java.applet.Applet class. Applets are not stand-alone programs. They run
either within a web browser or an applet viewer.

Note:
Java applet is deprecated because it’s no longer widely used on the web. The
popularity of applets has decreased over the years as browser support for
applets has declined, and more advanced technologies such as web-based
applications and JavaScript have become more prevalent. Additionally,
applets are considered a security risk as they can execute arbitrary code on
the client machine, and many browsers now disable them by default. As a
result, Java’s applet technology is no longer seen as a valuable feature for
Java developers and is removed from the newer versions of Java.
• Applets generate Dynamic content
• Applets work on the client-side
• The response time is fast

We can view our Applet with the help of a standard applet viewer tool
called Applet Viewer. Unlike the general executions and outputs of the java
programs, applet execution does not begin at main() method, and the
output of an applet window is not catered by System.out.println(). Rather it
is handled with various Abstract Window Toolkit (AWT) methods, such as
drawString().
Let us do see a hierarchy of Applet before landing up on stages in the
lifecycle of the java applet that is as follows in the below media:

Stages in the Life Cycle of Java Applet


• Initializing an Applet
• Starting the Applet
• Painting the Applet
• Stopping the Applet
• Destroying the Applet
In order to implement the Applet we need to import awt package,
java.awt.applet.*;
Life Cycle of Applet
Step 1: Initialization
public void init()
There is no main method unlike our normal java programs. Every Applet will
start it’s execution from init() method. It is executed only once
Step 2: Start
public void start()
After init() method start() method is invoked. Executed when the browser is
maximized
Step 3: Paint
public void paint (Graphics g)
Paint method is used to display the content on the applet. We can create the
objects or components to the applet or we can directly write a message on the
applet. It will take Graphics class as a parameter.
Step 4: Stop
public void stop()
stop() method is used to stop the applet. It is executed when the browser is
minimized.
Step 5: Destroy
public void destroy()
destroy() method is used to completely close the applet. It is executed when the
applet is closed.
Implementation:
Implementation of java Applet can be done in two ways as follows:
1. Using HTML file
2. Applet viewer tool
Way 1: Using HTML file
<HTML>
<applet>
code,width,height
</applet>
</HTML>
Note: Drawbacks of using HTML file is you need a plugin (java plugin) to
run it on your browser.
Way 2: Applet viewer tool
Methods of Applet Life Cycle:
There are five methods of an Applet Life Cycle namely;
1. init()
2. start()
3. paint()
4. stop()
5. destroy()

All these are available in AWT Package java.awt.applet.* and in order ton
import paint (Graphics g) we do use java.awt.component package
Let’s understand each method in a detailed manner :
Method 1: init()
• This is the first method to be called
• Variables can be initialized here
• This method can be called only once during the run time of the applet
• It is invoked at the time of Initialization
Syntax:
public void init()
{
// To initialize objects
}
Method 2: start()
• This method is called after init() method
• start() method is used for starting the applet
• It is also called to restart an applet after it has been stopped. i.e. to
resume the applet
Syntax:
public void start()
{
// To start the applet code
}
Note: init() is called once i.e. when the first time an applet is loaded whereas
start( ) is called each time an applet’s HTML document is displayed onscreen.
Method 3: paint()
void paint(Graphics g){ }
• paint() method is used for painting any shapes like square, rectangle,
trapeziums, etc.
• paint() method has one parameter of type Graphics Class, this
Graphics class enables the painting features in an applet.
• This parameter will contain the graphics context, which is used
whenever output for the applet is required.
Syntax:
public void paint(Graphics graphics)
{
// Any shape's code
}
Note: This is the only method among all the method mention above, which is
parameterized.
Method 4: stop()
• It is invoked every time the browser is stopped, minimized or when
there is an abrupt failure in the application.
• After stop()method called, we can also use start() method whenever
we want.
• This method mainly deals with clean up code.
• The stop( ) method is called when a web browser leaves the HTML
document containing the applet when it goes to another page, for
example, when stop( ) is called, the applet is probably running. You
should use stop( ) to suspend threads that don’t need to run when the
applet is not visible. You can restart them when start( ) is called if the
user returns to the page.
Syntax:
public void stop()
{
// To stop the applet code
}
Method 5: destroy()
• destroy() method is used to destroy the application once we are done
with our applet work. It can be invoked only once.
• Once applet is destroyed we can’t start() the applet (we cannot
restore the applet again)
• The destroy( ) method is called when the environment determines
that your applet needs to be removed completely from memory.
Syntax:
public void destroy()
{
// To destroy the applet
}
Note: The stop( ) method is always called before destroy( )
Syntax: Entire Applet Life Cycle

Class AppletLifeCycle extends Applet


{
public void init()
{
// Initializes objects
}
public void start()
{
// Starts the applet code
}
public void paint(Graphics graphics)
{
// Any shape's code
}
public void stop()
{
// Stops the applet code
}
public void destroy()
{
// Destroys the applet code
}
}

Passing parameters to applets

You might also like