IV Module
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
• 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.
Drawback of Applet
• Plugin is required at client browser to execute applet.
Hierarchy of Applet
Components: AWT provides various components such as buttons, labels, text fields, checkboxes,
etc used for creating GUI elements for Java Applications.
Containers: AWT provides containers like panels, frames, and dialogues to organize and group
components in the Application.
Layout Managers: Layout Managers are responsible for arranging data in the containers sone of
the layout managers are BorderLayout, FlowLayout, etc.
Event Handling: AWT allows the user to handle the events like mouse clicks, key presses, etc.
using event listeners and adapters.
Graphics and Drawing: It is the feature of AWT that helps to draw shapes, insert images and write
text in the components of a Java Application.
Lifecycle of Java Applet
• Applet is initialized.
• Applet is started.
• Applet is painted.
• Applet is stopped.
• Applet is destroyed.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods
of applet.
• public void init(): is used to initialized the Applet. It is invoked only once.
• public void start(): is invoked after the init() method or browser is maximized. It is used to
start the Applet.
• public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
• public void destroy(): is used to destroy the Applet. It is invoked only once.
How to run an Applet?
There are two ways to run an applet
• By html file.
• By appletViewer tool (for testing purpose).
Simple example of Applet by 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); } }
myapplet.html
<html> <body>
<applet code="First.class" width="300" height="300">
</applet> </body> </html>
Simple example of Applet by appletviewer tool:
//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
Button:A button is basically a control component with a label that generates an event when pushed.
Example
Button b = new Button("Click Here");
Label:The object of the Label class is a component for placing text in a container. It is used to
display a single line of read only text.
Example
Label l1;
l1 = new Label ("First Label.”);
Canvas
The Canvas class controls and represents a blank rectangular area where the application can draw or
trap input events from the user. It inherits the Component class.
Frame f = new Frame("Canvas Example");
// adding canvas to frame
f.add(new MyCanvas());
// setting layout, size and visibility of frame
f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);
}
Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a GUI
component allows us to see invisible number of rows and columns.
Scrollbar s = new Scrollbar();
text components
TextField
The object of a TextField class is a text component that allows a user to enter a single line text and
edit it. It inherits TextComponent class, which further inherits Component class.
TextField t1;
t1 = new TextField("Welcome.");
t1.setBounds(50, 100, 200, 30);
Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Clicking on a Checkbox changes its state from "on" to "off" or from "off" to “on”.
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
CheckboxGroup
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only one
check box button is allowed to be in "on" state and remaining check box button in "off" state. It
inherits the object class.
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
Choice:The object of Choice class is used to show popup menu of choices. Choice selected by user
is shown on the top of a menu. It inherits Component class.
Choice c = new Choice();
c.setBounds(100, 100, 75, 75);
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
Panel:The Panel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the Container class.
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Dialog:The Dialog 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 Window class.
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
MenuItem and Menu
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu
must belong to the MenuItem or any of its subclass.
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
menu.add(i1);
submenu.add(i2);
menu.add(submenu);
mb.add(menu);
Graphics in Applet
java.awt.Graphics class provides many methods for graphics programming.
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);
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.
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.
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
f = new JFrame();
JButton b1 = new JButton(“NORTH");
JButton b2 = new JButton(“SOUTH");
f.add(b1, BorderLayout.NORTH);
f.add(b2, BorderLayout.SOUTH);
GridLayout :The Java GridLayout class is used to arrange the components in a rectangular grid.
One component is displayed in each rectangle.
GridLayoutExample()
{
frameObj = new JFrame();
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
frameObj.add(btn1); frameObj.add(btn2);
frameObj.setLayout(new GridLayout());
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
FlowLayoutExample()
{
frameObj = new JFrame();
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
frameObj.add(b1); frameObj.add(b2);
frameObj.setLayout(new FlowLayout());
CardLayout:The Java CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known as
CardLayout.
crd = new CardLayout();
GridBagLayout:The Java GridBagLayout class is used to align components vertically, horizontally
or along their baseline.
GridBagLayout layout = new GridBagLayout();
Events
An event can be defined as changing the state of an object or behavior by performing actions.
Actions can be a button click, cursor movement, keypress through keyboard or page scrolling, etc.
Event Source : Description
Button : Generates action events when the button is pressed.
Check box : Generates item events when the check box is selected or deselected.
Choice : Generates item events when the choice is changed.
List : Generates action events when an item is double-clicked; generates item events when an
item is selected or deselected.
Menu item : Generates action events when a menu item is selected; generates item events when
a checkable menu item is selected or deselected.
Scroll bar : Generates adjustment events when the scroll bar is manipulated.
Text components : Generates text events when the user enters a character.
Window : Generates window events when a window is activated, closed, deactivated, deiconified,
iconified, opened, or quit.
Java Event classes and Listener interfaces
Event Classes Listener Interfaces
ActionEvent ActionListener
MouseEvent MouseListener and MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Steps to perform Event Handling
Following steps are required to perform event handling:
• Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For
example
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}
Java event handling by implementing ActionListener
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true); }
public void actionPerformed(ActionEvent e){
tf.setText("Welcome"); }
public static void main(String args[]){
new AEvent(); } }
Out put
The Delegation Model
The Delegation Model is available in Java since Java 1.1. it provides a new delegation-based event
model using AWT to resolve the event problems. It provides a convenient mechanism to support
complex Java programs.
Design Goals
The design goals of the event delegation model are as following:
• It is easy to learn and implement
• It supports a clean separation between application and GUI code.
• It provides robust event handling program code which is less error-prone (strong compile-time
checking)
• It is Flexible, can enable different types of application models for event flow and propagation.
• It enables run-time discovery of both the component-generated events as well as observable
events.
• It provides support for the backward binary compatibility with the previous model.
MouseListener
The Java MouseListener is notified whenever you change the state of mouse. It is notified against
MouseEvent. The MouseListener interface is found in java.awt.event package. It has five methods.
Methods of MouseListener interface
The signature of 5 methods found in MouseListener interface are given below:
public abstract void mouseClicked(MouseEvent e);
public abstract void mouseEntered(MouseEvent e);
public abstract void mouseExited(MouseEvent e);
public abstract void mousePressed(MouseEvent e);
public abstract void mouseReleased(MouseEvent e);
Example
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
Java KeyListener Interface
The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in java.awt.event package, and it has three methods.
public abstract void keyPressed (KeyEvent e); It is invoked when a key has been pressed.
public abstract void keyReleased (KeyEvent e);It is invoked when a key has been released.
public abstract void keyTyped (KeyEvent e);It is invoked when a key has been typed.
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener {
Label l;
TextArea area;
KeyListenerExample() {
l = new Label();
l.setBounds (20, 50, 100, 20);
area = new TextArea();
area.setBounds (20, 80, 300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize (400, 400);
setLayout (null);
setVisible (true);
}
public void keyPressed (KeyEvent e) {
l.setText ("Key Pressed");
}
public void keyReleased (KeyEvent e) {
l.setText ("Key Released");
}
public void keyTyped (KeyEvent e) {
l.setText ("Key Typed");
}
public static void main(String[] args) {
new KeyListenerExample();
}
}
Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.
Pros of using Adapter classes:
• It assists the unrelated classes to work combinedly.
• It provides ways to use classes in different ways.
• It increases the transparency of classes.
• It provides a way to include related patterns in the class.
• It provides a pluggable kit for developing an application.
• It increases the reusability of the class.
• The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.
The Adapter classes with their corresponding listener interfaces are given below.