0% found this document useful (0 votes)
13 views

Unit-5_notes

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

Unit-5_notes

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

Dept.

of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

UNIT – V
Introduction:
Java applications can be classified as

1) CUI
2) GUI

CUI: CUI stands for Character User Interface. Take help of a keyboard to type
commands to interact with the computer.

GUI: It is made up of graphical components (e.g., buttons, labels, windows) through


which the user can interact with the application.

Containers and Components

There are two types of GUI elements:


1. Component: Components are elementary GUI entities, such as Button, Label,
and TextField.
2. Container: Containers, such as Frame and Panel, are used to hold components in
a specific layout (such as FlowLayout or GridLayout). A container can also hold
sub-containers.
In the above figure, there are three containers: a Frame and two Panels. A Frame is
the top-level container of an AWT program. A Frame has a title bar (containing an icon,
a title, and the minimize/maximize/close buttons), an optional menu bar and the content
display area. A Panel is a rectangular area used to group related GUI components in a
certain layout. In the above figure, the top-level Frame contains two Panels. There are
five components: a Label (providing description), a TextField (for users to enter text),
and three Buttons (for user to trigger certain programmed actions).
In a GUI program, a component must be kept in a container. You need to identify a
container to hold the components. Every container has a method called add(Component
c). A container (say c) can invoke c.add(aComponent) to add aComponent into itself.
For example,

Panel pnl = new Panel(); // Panel is a container

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 1


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Button btn = new Button("Press"); // Button is a component

pnl.add(btn); // The Panel container adds a Button component

GUI components are also called controls which allow users to interact with (or
control) the application.

AWT Container Classes


Top-Level Containers: Frame, Dialog and Applet
Each GUI program has a top-level container. The commonly-used top-level containers
in AWT are Frame, Dialog and Applet:

 A Frame pr
ovides the "main window" for your GUI application. It has a title bar (containing an
icon, a title, the minimize, maximize/restore-down and close buttons), an optional
menu bar, and the content display area. To write a GUI program, we typically start
with a subclass extending from java.awt.Frame to inherit the main window as
follows:

 AWT Component Classes


AWT provides many ready-made and reusable GUI components in package java.awt.
The frequently-used are: Button, TextField, Label, Checkbox, CheckboxGroup (radio
buttons), List, and Choice, as illustrated below.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 2


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

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.

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.

Panel

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 3


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

The Panel is the container that doesn't contain title bar and menu bars. It can have
other components like button, textfield etc.

Frame

The Frame is the container that contain title bar and can have menu bars. It can have
other components like button, textfield etc.

Useful Methods of Component class

Method Description

public void add(Component c) inserts a component on this component.

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

public void setLayout(LayoutManager m) defines the layout manager for the


component.

public void setVisible(boolean status) changes the visibility of the component, by


default false.

Java AWT Label

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. Take note that System.out.println() prints to
the system console, NOT to the graphics screen. You could use a Label to label another
component (such as text field) to provide a text description.

Constructors

public Label(); // Construct an initially empty Label

public Label(String strLabel); // Construct a Label with the given

//text String

public Label(String strLabel, int alignment); // Construct a Label with

//the given text String, of the text alignment

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 4


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

The Label class has three constructors:

1. The first constructor constructs a Label object with the given text string in the
given alignment. Note that three static constants Label.LEFT, Label.RIGHT,
and Label.CENTER are defined in the class for you to specify the alignment
(rather than asking you to memorize arbitrary integer values).
2. The second constructor constructs a Label object with the given text string in
default of left-aligned.
3. The third constructor constructs a Label object with an initially empty string. You
could set the label text via the setText() method later.

Public Methods

// Examples

public String getText();

public void setText(String strLabel);

public intgetAlignment();

public void setAlignment(int alignment); // Label.LEFT, Label.RIGHT, Label.CENTER

Example Program to display WELCOME AND VANDEMATARAM ON the screen.

import java.awt.*;

class LabelDemo extends Frame

LabelDemo()

Label l1,l2;

setLayout(new FlowLayout());

l1=new Label("WELCOME");

l2=new Label("VANDEMATARAM");

add(l1);

add(l2);

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 5


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

setSize(400,400);

setVisible(true);

public static void main(String args[])

LabelDemo l= new LabelDemo();

output

TextField

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 6


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

A java.awt.TextField is single-line text box for users to enter texts. (There is a multiple-
line text box called TextArea.) Hitting the "ENTER" key on a TextField object fires
an ActionEvent.
Constructors

public TextField(String initialText, int columns);

// Construct a TextField instance with the given initial text string with the number of
columns.

public TextField(String initialText);

// Construct a TextField instance with the given initial text string.

public TextField(int columns);

// Construct a TextField instance with the number of columns.

Public Methods

public String getText();

// Get the current text on this TextField instance

public void setText(String strText);

// Set the display text on this TextField instance

public void setEditable(boolean editable);

// Set this TextField to editable (read/write) or non-editable (read-only)

EventHitting the "ENTER" key on a TextField fires a ActionEvent, and triggers a certain
programmed action.

TextArea

Java TextArea Multiple Lines Text

Java TextArea overcomes the limitation of TextField and is used to display or take input
in multiple lines of text. Following list illustrates the limitations.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 7


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

DIFFERENCES BETWEEN TEXTFIELD AND TEXTAREA

1. TextField displays only one line of text of any length. TextArea displays multiple
lines of text of any length.
2. TextField generates ActionEvent handled by ActionListener and TextArea
generates TextEvent handled by TextListener.

Following is the hierarchy of TextArea component

THE FOLLOWING PROGRAM CREATES TWO JAVA TEXTAREA MULTIPLE LINES


TEXT. WHAT IS TYPED IN ONE TEXT AREA IS DISPLAYED IN THE OTHER.

import java.awt.*;
import java.awt.event.TextListener;
import java.awt.event.TextEvent;

public class TADemo extends Frame implements TextListener


{
TextAreatypeText, displayText;
public TADemo()
{
super("Practicing Text Area");
// default BorderLayot is used
typeText = new TextArea("Type Here", 10, 20);
displayText = new TextArea();
displayText.setRows(10);
displayText.setColumns(20);

typeText.addTextListener(this);

add(typeText, BorderLayout.NORTH);
add(displayText, BorderLayout.SOUTH);

setSize(300, 350);
setVisible(true);
}
public void textValueChanged(TextEvent e)
{
Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 8
Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

String str= typeText.getText();


displayText.setText(str);
}
public static void main(String args[])
{
new TADemo();
}
}

Button:

Button is a GUI component that triggers a certain programmed action upon clicking

Constructors: The Button class has two constructors

The first constructor creates a Button object with no label.

The second constructor creates a Button object with the given label painted over the
button.

1) public Button();

// Construct a Button with empty label

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 9


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

1) public Button(String btnLabel);

// Construct a Button with the given label

public Methods

public String getLabel();

// Get the label of this Button instance

public void setLabel(String btnLabel);

// Set the label of this Button instance

public void setEnable(boolean enable);

// Enable or disable this Button. Disabled Button cannot be clicked.

The getLabel() and setLabel() methods can be used to read the current label and
modify the label of a button, respectively.

Layout management

To display a component, it is inevitable to add it to a container. Container is an area on


the monitor that can hold and display the components. The frequently used containers
are Frame and Panel.

To place a component inside a container, there exist two styles – pixel


format and position format.

1. Pixel Format
In pixel format we add the component to the container in terms of pixels. The method
used is setBounds().

2. Position Format
To give the position, Java comes with a set of classes from java.awt package known
as layout managers. The Layout Managers
1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
5. GridBagLayout
Each layout comes with its own style of laying the components in the container.
Thorough knowledge of layout managers is very essential for component technology.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 10


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Following figure gives the hierarchy of layout managers.

FlowLayout Manager Example: It is the mostly used along with panels and is the default
manager for Applets and Panels.
1. It arranges the components on the north (top) side of the container.
2. The components, by default, centered on the north side. The alignment can be
changed to left or right.
3. The default gap between the components, either horizontally or vertically, is 5
pixels which can be changed.
4. It is the default manager for panels and applets.
5. This layout gives the minimum size to the component known as preferred size.
Example : program on FlowLayout Manager Example, 10 anonymous objects of buttons
are created and added to the frame that is set to flow layout.
import java.awt.*;
class FlowLayoutDemo extends Frame
{
public FlowLayoutDemo()
{
setLayout(new FlowLayout());
// create 10 anonymous button objects and add them to frame
for(inti = 0; i< 10; i++)
{
add(new Button("OK " + i));
}

setSize(300, 300);
setVisible(true);
}
public static void main(String args[])
{
new FlowLayoutDemo();
}

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 11


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

}
Output

Java AWT GridLayout Manager

As the name indicates the container is divided into a grid of cells dictated
by rows and columns. Each cell accommodates one component. Like with FlowLayout,
in GridLayout also, the possition need not be mentioned. As the rows and columns are
fixed, components addition goes one after another automatically. Following is an
example of GridLayout of 3 rows and 4 columns (12 cells).

Following are the properties of GridLayout.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 12


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

1. The grid layout size (no. of cells) is given by rows and columns.
2. The default gap between the components is 0 pixels which can be changed
explicitly.
3. Components should be added continuously. It is not possible to avoid some cells
addition in the middle, and add to later cells.
Example :program illustrates the use of GridLayout.

import java.awt.*;

public class GridLayoutDemo extends Frame

public GridLayoutDemo()

setLayout(new GridLayout(3, 4));

setBackground(Color.red);

// create 12 anonymous button objects and add them

for(inti = 0; i< 12; i++)

add(new Button("OK " + i));

setSize(350, 300);

setVisible(true);

public static void main(String args[])

new GridLayoutDemo(); }}

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 13


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Output

Border layout manager

AS THE NAME INDICATES THE CONTAINER IS DIVIDED INTO 5 REGIONS – 4


BORDERS (NORTH, SOUTH, EAST, WEST) AND 1 CENTER.

Following are the properties of BorderLayout manager.

1. Components are added at borders and center. The position should be specified
while adding the component like North or East etc.; else the default is Center.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 14


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

2. When added, say south or north, the component occupies complete width of the
container and when added, say east or west, the component occupies complete
height of the container. Center occupies complete remaining space.
3. When it occupies complete width or height, another component cannot be added to
the same side and if added, it is not an error, but overrides the earlier; that is,
earlier goes out and the latest comes.
4. Using BorderLayout, we can add maximum 5 components only to a container; 4 at
the borders and one at the center.
5. The default gap between the components, either horizontally or vertically, is 0 pixels
which can be changed explicitly.
6. It is the default layout manager for Frame, Dialog, FileDialog, Window and
Container.
7. It is best suitable for adding scroll bars.
EXAMPLE :PROGRAM ON BORDERLAYOUT MANAGER

import java.awt.*;

public class BorderLayoutDemo extends Frame

public BorderLayoutDemo()

{ // set the layout

setLayout(new BorderLayout());

setBackground(Color.red);

// create the components

Button btn1 = new Button("Himalayas");

Button btn2 = new Button("Indian Ocean");

Button btn3 = new Button("Bay of Bengal");

Button btn4 = new Button("Arabian Sea");

Button btn5 = new Button("India");

// place the components, position should be specified

add(btn1, "North");

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 15


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

add(btn2, "South");

add(btn3, "East");

add(btn4, "West");

add(btn5, "Center");

// frame creation methods

setTitle("Learning BorderLayout");

setSize(350, 300);

setVisible(true);

public static void main(String args[])

{ // just call constructor to execute the whole code

new BorderLayoutDemo();

Output

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 16


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Event Delegation Model

When we create a component, the component is displayed on the screen but it is not
capable of performing any actions. For example, a button is created can be displayed
on the screen cannot perform any action, even when someone clicks on it.

A user wants the push button to perform some action, when he clicks the button.

Clicking like this is called event. An event represents a specific action done on a
component. Examples of events are clicking, double clicking, typing data inside the
component etc.

When an event is generated on the component, the component will not know about it
because it cannot listen to the event. To make the component to understand that an
event is generated, add some listener to the component.

A listener is an interface which listens which listens to an event coming from the
component. A listener will have some abstract methods which needed to be
implemented by the implemented by the programmer.

When an event is generated by the user on the component, the event is not handled by
the component. On the other hand, the component sends or delegates that event to the
listener attached to it. The listener will not handle the event; it hands over that is
delegates the event to an appropriate method. Finally, the method is executed and the
event is handled. This is called event delegation model.

Fig shows event delegation model

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 17


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Any GUI component with event handling can be broadly divided into 8 steps.

1) Import java.awt and java.awt.event packages


2) Extending frame or applet and implementing appropriate listener interface that
can handle the events of the component successfully.
3) Set the layout.
4) Create components
5) Register or link the component with the listener interface
6) Beautification of the components (optional)
7) Adding the components to the frame or applet
8) Override all the abstract methods of the listener interface

By using the above 8 steps, let us develop a simple button program with 4 buttons with
labels RED, GREEN, BLUE and CLOSE. The action is, the background of the frame
should change as per the button clicked. When CLOSE is clicked, the frame should
close.

Example Program to create three buttons Red, green and white accept user choice and
change the back ground colors accordingly.

import java.awt.*;

import java.awt.event.*;

class ButtonDemo extends Frame implements ActionListener

Button red,green,white;

ButtonDemo()

red=new Button("red");

green=new Button("green");

white=new Button("white");

setSize(200,200);

setVisible(true);

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 18


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

setLayout(new FlowLayout());

red.addActionListener(this);

green.addActionListener(this);

white.addActionListener(this);

add(red);

add(green);

add(white);

public void actionPerformed(ActionEvent e)

if(e.getSource()==red)

setBackground(Color.red);

if(e.getSource()==green)

setBackground(Color.green);

if(e.getSource()==white)

setBackground(Color.white);

public static void main(String args[])

ButtonDemo b =new ButtonDemo();

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 19


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Example to find sum of two numbers by using AWT,

import java.awt.*;

import java.awt.event.*;

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 20


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

class Addition extends Frame implements ActionListener

TextField t1,t2,t3; Label l1,l2,l3; Button b1;

Addition()

setVisible(true);

setSize(200,200);

setLayout(new FlowLayout());

t1= new TextField(10);

t2= new TextField(10);

t3= new TextField(10);

l1= new Label("First Number");

l2= new Label("Second Number");

l3= new Label("Sum");

b1= new Button("Add");

setLayout(new FlowLayout());

add(l1);

add(t1);

add(l2);

add(t2);

add(l3);

add(t3);

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 21


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

add(b1);

b1.addActionListener(this);

public void actionPerformed(ActionEvent e)

if (e. getSource()==b1)

int a= Integer.parseInt(t1.getText());

int b= Integer.parseInt(t2.getText());

int c= a+b;

t3.setText(String.valueOf(c));

public static void main(String args[])

Addition a= new Addition();

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 22


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Output

Limitation of AWT:

Java AWT

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based


applications in java.

Java AWT components are platform-dependent i.e. components are displayed


according to the view of operating system.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 23


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

AWT is huge! It consists of 12 packages of 370 classes (Swing is even bigger, with 18
packages of 737 classes as of JDK 8). Fortunately, only 2 packages
- java.awt and java.awt.event - are commonly-used.
1. The java.awt package contains the core AWT graphics classes:
o GUI Component classes, such as Button, TextField, and Label.
o GUI Container classes, such as Frame and Panel.
o Layout managers, such
o as FlowLayout, BorderLayout and GridLayout.
o Custom graphics classes, such as Graphics, Color and Font.

2. The java.awt.event package supports event handling:


o Event classes, such
o as ActionEvent, MouseEvent, KeyEvent and WindowEvent,
o Event Listener Interfaces, such
o as ActionListener, MouseListener, MouseMotionListener, KeyListener and Wi
ndowListener,
o Event Listener Adapter classes, such
o as MouseAdapter, KeyAdapter, and WindowAdapter.

AWT provides a platform-independent and device-independent interface to develop


graphic programs that runs on all platforms, including Windows, Mac OS X, and Unixes.

MVC Architecture

Model designs based on MVC architecture follow the MVC design pattern and
they separate the application logic from the user interface when designing
software. As the name implies MVC pattern has three layers, which are:

Model – Represents the business layer of the application


View – Defines the presentation of the application
Controller – Manages the flow of the application

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 24


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

This separation results in user requests being processed as follows:

1. The browser on the client sends a request for a page to the controller present on
the server
2. The controller performs the action of invoking the model, thereby, retrieving the
data it needs in response to the request
3. The controller then gives the retrieved data to the view
4. The view is rendered and sent back to the client for the browser to display

Advantages of MVC Architecture in Java


MVC architecture offers a lot of advantages for a programmer when developing
applications, which include:

 Multiple developers can work with the three layers (Model, View, and Controller)
simultaneously
 Offers improved scalability, that supplements the ability of the application to grow
 As components have a low dependency on each other, they are easy to maintain
 A model can be reused by multiple views which provides reusability of code
 Adoption of MVC makes an application more expressive and easy to understand
 Extending and testing of the application becomes easy

WindowListener

The frame created by the programmer and displayed on the monitor comes with a title
bar and three icons(buttons) on the title bar – Minimize, Maximize and Close. `The first
two works implicitly and the Close does not work and requires extra code to close the
frame.

Example: To close the window by using WindowListener

import java.awt.event.*;

import java.awt.*;

public class FrameClosing1 extends Frame implements WindowListener

public FrameClosing1()

addWindowListener(this);

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 25


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

setTitle("Frame closing Style 1");

setSize(300, 300);

setVisible(true);

// override the 7 abstract methods of WindowListener

public void windowClosing(WindowEvent e)

System.exit(0);

public void windowOpened(WindowEvent e) { }

public void windowClosed(WindowEvent e) { }

public void windowActivated(WindowEvent e) { }

public void windowDeactivated(WindowEvent e) { }

public void windowIconified(WindowEvent e) { }

public void windowDeiconified(WindowEvent e) { }

public static void main(String args[])

new FrameClosing1();

output

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 26


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Handling mouse events

The user may click, release, drag or move a mouse while interacting with the
application. If the programmer knows what the user has done, he can write the code
according to the mouse events. To trap the mouse events, the interfaces MouseListener
and MouseMotionListener interfaces of java.awt.event package are used.

Mouse Event

Method Description

void mouseClicked (MouseEvent e) Invoked when the mouse button has


been clicked (pressed and released) on
a component

void mouseEntered (MouseEvent e) Invoked when the mouse pointer enters


a component

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 27


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

void mouseExited (MouseEvent e) Invoked when the mouse pointer exits


a component

void mousePressed (MouseEvent e) Invoked when a mouse button has


been pressed on a component

void mouseReleased (MouseEvent e) Invoked when a mouse button has


been released on a component

void mouseDragged (MouseEvent e) Invoked when a mouse button is


pressed on a component and then
dragged

void mouseMoved (MouseEvent e) Invoked when the mouse pointer has


been moved onto a component but no
buttons have been pressed

All the above five methods take MouseEvent as parameter. When the mouse is entering
or exiting a notepad file, a MS Word file or an Excel file, the mouse arrow changes
a double-arrow symbol. These actions are represented by two methods
mouseEntered() and mouseExited().
The event generated by the Mouse is known as MouseEvent.
Following program illustrates the way of using the MouseListener with simple event-
handling. For a bigger program refer MouseMotionListener.

import java.awt.*;

import java.awt.event.*;

public class MouseDemo extends Frame implements MouseListener

public MouseDemo( )

addMouseListener(this); // link the frame with ML

setSize(300,300);

setVisible(true);

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 28


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

// override the 5 abstract methods of ML

public void mousePressed(MouseEvent e)

// do some action to distinguish from other methods

setBackground(Color.red);

System.out.println("Mouse is Pressed");

public void mouseReleased(MouseEvent e)

setBackground(Color.blue);

System.out.println("Mouse is Released");

public void mouseClicked(MouseEvent e)

setBackground(Color.green);

System.out.println("Mouse is Clicked");

public void mouseEntered(MouseEvent e)

setBackground(Color.cyan);

System.out.println("Mouse is Entered");

public void mouseExited(MouseEvent e)

setBackground(Color.magenta);

System.out.println("Mouse is Exited");

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 29


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

public static void main(String args[])

MouseDemo m=new MouseDemo();

Output

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 30


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Mouse Motion Listener

Two types of actions can be generated when the mouse is in motion

1) just moving the mouse


2) while dragging (moving the mouse while mouse the key is being pressed).
These two actions are handled by the two abstract methods of
MouseMotionListener – mouseMoved() and mouseDragged(); both take
MouseEvent as parameter.
Example Program to demonstrate MouseMotion
import java.awt.*;
import java.awt.event.*;

public class MouseMotionDemo extends Frame implements


MouseMotionListener
{
public MouseMotionDemo()
{
addMouseMotionListener(this); // link the frame with MML
setSize(300,300);
setVisible(true);
}
// override the 2 abstract methods of MML

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 31


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

public void mouseMoved(MouseEvent e)


{
setBackground(Color.red);
System.out.println("Mouse is Moved");
}
public void mouseDragged(MouseEvent e)
{
setBackground(Color.blue);
System.out.println("Mouse is Dragged");
}
public static void main(String args[])
{
new MouseMotionDemo();
}
}

Java AWT Adapters

Adapter classes make event handling simple and easy. Adapters usage replaces
the listeners; adapters make event handling easy to the programmer. Every
listener that includes more than one abstract method has got a corresponding
adapter class. The advantage of adapter is that we can override any one or two
methods we like instead of all. But in case of a listener, we must override all the
abstract methods. For example, to close the window, all the 7 abstract methods
of WindowListener should be overridden at least with empty bodies. But is not

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 32


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

the case with WindowAdapter. With WindowAdapter only one


method windowClosing() is enough to override.

FOLLOWING TABLE GIVES THE LIST OF IMPORTANT JAVA AWT LISTENERS AND
THEIR CORRESPONDING JAVA AWT ADAPTERS CLASSES.
ActionListener, ItemListener and TextListener do not have a corresponding adapter
class as they contain only one abstract method.
Note: When an adapter is used, a separate class is to be created as the main class
already extends Frame (Java does not support multiple inheritance).
Following table gives some important listeners and their corresponding adapter classes.

LISTENER INTERFACE CORRESPONDING ADAPTER

WindowListener (7) WindowAdapter

MouseListener (5) MouseAdapter

MouseMotionListener (2) MouseMotionAdapter

KeyListener (3) KeyAdapter

FocusListener (2) FocusAdapter


The values in the parentheses indicate the abstract methods available in the listener
interface.

Window adapter classes

Java Frame Closing WindowAdapter


The frame created by the programmer and displayed on the monitor comes with a title
bar and three icons(buttons) on the title bar – Minimize, Maximize and Close. The first
two works implicitly and the Close does not work and requires extra code to close the
frame.

In the following program, WindowAdapter is used instead of WindowListener to close


the frame.

import java.awt.*;

import java.awt.event.*;

public class FrameClosing extends Frame

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 33


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

public FrameClosing()

CloseMe cm = new CloseMe();

addWindowListener(cm);

setTitle("Frame closing Style 2");

setSize(300, 300);

setVisible(true);

public static void main(String args[])

new FrameClosing();

class CloseMe extends WindowAdapter

public void windowClosing(WindowEvent e)

System.exit(0);

Output

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 34


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Swing

Java Swing tutorial is a part of Java Foundation Classes (JFC).Swing


Overview: The classes used to create GUI components of the
following list are part of the Swing GUI components from
package javax.swing. These are the latest GUI components of
the Java2 platform. Swing components (as they are commonly called)
are written, manipulated and displayed completely in Java language.

Unlike AWT, Java Swing provides platform-independent and lightweight


components.

DIFFERENCE BETWEEN AWT AND SWING

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 35


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

THERE ARE MANY DIFFERENCES BETWEEN JAVA AWT AND SWING


THAT ARE GIVEN BELOW.

NO. JAVA AWT JAVA SWING


1) AWT COMPONENTS ARE PLATFORM-DEPENDENT.
1) JAVA SWING COMPONENTS ARE PLATFORM-INDEPENDENT.
2) AWT COMPONENTS ARE HEAVYWEIGHT.
2) SWING COMPONENTS ARE LIGHTWEIGHT.
3) AWT PROVIDES LESS COMPONENTS THAN SWING.
3) SWING PROVIDES MORE POWERFUL COMPONENTS SUCH AS
TABLES, LISTS, SCROLLPANES, COLORCHOOSER,
TABBEDPANE ETC.
4) AWT DOESN'T FOLLOWS MVC(MODEL VIEW CONTROLLER)
WHERE MODEL REPRESENTS DATA, VIEW REPRESENTS
PRESENTATION AND CONTROLLER ACTS AS AN INTERFACE
BETWEEN MODEL AND VIEW.
4)SWING FOLLOWS MVC

What is JFC

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

What is heavyweight component?

Whenever you create a AWT GUI component like a button, a call to the
underlying OS to get the design of the button. AWT does not maintain
the structure and appearance of a button. It depends on the OS where
the Java program is being executed. Java copies the look of the
button and displays to the user. It is a very time consuming process.
For this reason, AWT components are known as "heavyweight
components".

What is lightweight component?

Contrary to AWT components, the swing components maintain their


own design, appearance, look and feel. They do not depend on the
underlying OS. That is, a swing button program executed on any OS

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 36


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

gets you the same design of button. For this reason, swing
components are known as "lightweight components

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.

All components in swing are JComponent which can be added to container


classes.

What is a container class?

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 37


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Container classes are classes that can have other components on it. So for
creating a GUI, we need at least one container object. There are 3 types of
containers.

1. Panel: It is a pure container and is not a window in itself. The sole


purpose of a Panel is to organize the components on to a window.
2. Frame: It is a fully functioning window with its title and icons.
3. Dialog: It can be thought of like a pop-up window that pops out when
a message has to be displayed. It is not a fully functioning window
like the Frame.

COMPONENT DESCRIPTION

An area where uneditable text or icons can be


JLabel displayed.

An area in which the user inputs data from the


JTextField keyboard. The area can also display information.

JButton An area that triggers an event when clicked.

JTextArea

Example to create a window by using Swing

import javax.swing.*;
class Swing1 extends JFrame
{
Swing1()
{

setVisible(true);
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 38


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

{
Swing1 f= new Swing1();
}
}
EXIT_ON_CLOSE
exits the application. This option will exit the application.
Window Pane

A window pane represents a free area of a window where some text or


components can be displayed.

Content pane: Individual components are attached to this pane. To reach


this pane, call getContentPane() method of JFrame class which returns
Container class Object

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.

Commonly used Constructors:

Constructor Description

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


string for the title.

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


s)

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 39


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Commonly used Methods:

Methods Description

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

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

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

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

intgetHorizontalAlignment() It returns the alignment of the label's contents along


the X axis.

import javax.swing.*;

import java.awt.*;

class LabelExample extends JFrame

JLabel l1,l2;

LabelExample()

setSize(300,300);

setLayout(new FlowLayout());

setForeground(Color.red);

setVisible(true);

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 40


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

l1=new JLabel("Vandemataram");

l2=new JLabel("OK");

add(l1);

add(l2);

// To close the frame

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public static void main(String args[])

LabelExample l =new LabelExample();

output

JTextField: JTextField is a lightweight component that allows the editing of


a single line of text. For information on and examples of using text fields.
Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 41
Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

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

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

JTextField(int columns) Creates a new empty TextField with the specified number o
next →← prev
Java JTextField

The object of a JTextField class is a text component that allows the editing of a single l
JTextComponent class.

JTextField class declaration

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

1. public class JTextField extends JTextComponent implements SwingConstants

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

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

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

JTextField(int columns) Creates a new empty TextField with the specif


columns.

Commonly used Methods:


Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 42
Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Methods Description

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


action events from this textfield.

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

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

void It is used to remove the specified action listener so


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

Example for JTextField


import javax.swing.*;
import java.awt.*;
class SwingTextField extends Frame
{
SwingTextField()
{
setSize(500,500);
setVisible(true);
setLayout(new FlowLayout());
JTextField t1,t2;
t1=new JTextField("Welcome to Java Swing");
t2=new JTextField("AWT Tutorial");
add(t1);
add(t2);
}
public static void main(String args[])
{
new SwingTextField();

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 43


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

}
}

Java JButton
The JButton class is used to create a labeled button that has platform
independent implementation. The application result in some action when
the button is pushed.

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(boolean b) It is used to enable or disable the button.

Icon getIcon() It is used to get the Icon of the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Example Program to tocreate a button and press it a message should be


displayed in the JTextField.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 44


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class SwingButtonExample extends JFrame implements
ActionListener
{
JTextField t;
JButton b;
SwingButtonExample()
{
t=new JTextField(25);
b=new JButton("Click Here");
b.addActionListener(this);
setVisible(true);
setSize(500,500);
setLayout(new FlowLayout());
add(t);
add(b);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
t.setText("Welcome JButton");
}
public static void main(String[] args)
{
new SwingButtonExample();
}
}

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 45


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

TextArea
Java AWT TextArea. The object of a TextArea class is a multi line region that displays
text. It allows the editing of multiple line text. It inherits TextComponent class.
import javax.swing.*;

public class TextAreaExample {

public static void main(String[] args){


JFrame frame= new JFrame("TextArea frame");
JPanel panel=new JPanel();
JTextAreajt= new JTextArea("Welcome TextArea",5,20);
frame.add(panel);
panel.add(jt);
frame.setSize(250,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 46


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Applets:
Applets Vs Applications Java
Applets

1) Generating dynamic content


2) Works at client side
3) Response time is fast.

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 47


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Applets can be implemented in two ways

1) Using HTML File


2) Appletviewer tool
Life cycle of applet

The life cycle of an applet is as shown in the figure below:

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 48


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

As shown in the above diagram, the life cycle of an applet starts


with init() method and ends with destroy() method. Other life cycle
methods are start(), stop() and paint(). The methods to execute only
once in the applet life cycle are init() and destroy(). Other methods
execute multiple times.

Below is the description of each applet life cycle method:


init(): The init() method is the first method to execute when the applet
is executed. Variable declaration and initialization operations are
performed in this method.
start(): The start() method contains the actual code of the applet that
should run. The start() method executes immediately after
the init() method. It also executes whenever the applet is restored,
maximized or moving from one tab to another tab in the browser.
stop(): The stop() method stops the execution of the applet. The
stop() method executes when the applet is minimized or when moving
from one tab to another in the browser.
destroy(): The destroy() method executes when the applet window is
closed or when the tab containing the webpage is closed.
Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 49
Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

stop() method executes just before when destroy() method is invoked.


The destroy() method removes the applet object from memory.

paint(): The paint() method is used to redraw the output on the applet
display area. The paint() method executes after the execution
of start() method and whenever the applet or browser is resized.

The method execution sequence when an applet is executed is:

 init()
 start()
 paint()

The method execution sequence when an applet is closed is:

 stop()
 destroy()

Example of paint() method


Within the method paint() we will call the drawString() method to print a text
message in the applet window.

when the paint() method is invoked?


The method paint() is automatically called whenever there is a need to display
an applet window, this need could arise in certain situations -
 When an applet window is brought up on the screen for the first time.
 When an applet window is brought up on the screen from a minimized state,
this leads the redrawing of the applet window and hence the paint() method
is automatically called.
 When an applet window is stretched to a new size, this leads to redrawing of
the applet window to a new size and hence the paint() method is
automatically called.

Signature of paint() method

publicvoiddrawString(String, intx, inty)

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 50


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

The method paint() gives us access to an object of type Graphics class. Using
the object of the Graphics class, we can call the drawString() method of the
Graphics class to write a text message in the applet window.

signature of drawString() method

public void drawString(String, int x, int y)

The method drawString() takes a String which will be printed in the applet
window, starting from left-top corner at the coordinates x and y.

Example

Writing a message on the applet window.

we are implementing the paint() method in our applet class.

Within the paint() method, the drawString() method is called to write a


message in the applet window.

import java.awt.*;

import java.applet.*;

/*

<applet code="Applet1" width=400 height=200>

</applet>

*/

public class Applet1 extends Applet

String str ="";


Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 51
Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

public void init()

str="init-";

public void start()

str=str+"start-";

public void stop()

str=str+"stop-";

public void paint(Graphics g)

str=str+"paint-";;

g.drawString(str,40,100);

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 52


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

g.drawString("Hello from the Applet.", 40,40);

g.drawString("How are you doing?", 40, 60);

g.drawString("We wish you a pleasant day today.", 40, 80);

To run this program at command prompt type: appletviewer Applet1.java

Output

example
import java.applet.*;
import java.awt.*;
class Myapplet extends Applet
{
String str;
public void init()
{

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 53


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

str = "This is my first applet";


}
public void paint(Graphics g)
{
g.drawString(str, 50,50);
}
}
Html file name: MyApplet.html
<HTML>
<BODY>
<applet code="Myapplet",height="200" width="200">
</applet>
</BODY>
</HTML>
To execute the program
c:\>appletviewer MyApplet.html

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 54


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

example
file name: HelloWorld.java
import java.applet.Applet;
import java.awt.*;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World!", 50, 25);
}
}
html file name:
<html>

<head>

<TITLE> A Simple Program </TITLE>

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 55


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

</head>

<body>

Here is the output of my program:

<applet code="HelloWorld.class" width="150" height="25"></applet>

</body>

</html>

To run the program

E:\vva\java2020>appletviewer HelloWorld.html

Passing Parameters to Applets

How to pass some parameters to an applet and how to read those


parameters in an applet to display their values in the output.
Steps to accomplish this task -:
 To pass the parameters to the Applet we need to use
the param attribute of <applet> tag.
 To retrieve a parameter's value, we need to use
the getParameter() method of Applet class
 Steps to accomplish this task -:
 To pass the parameters to the Applet we need to use the param
attribute of <applet> tag.
 To retrieve a parameter's value, we need to use the
getParameter() method of Applet class

getParameter(String name)
Method takes a String argument name, which represents the name
of the parameter
Example: java applet program filename :
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 56


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
To compile program at command prompt type :javac MyApplet.java
To run the program at command prompt type :appletviewer
MyApplet.java
Output

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 57


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Example Java applet program: file name DemoApplet.java

import java.applet.Applet;

import java.awt.Graphics;

public class DemoApplet extends Applet

String message;

intfirstNumber;

double secondNumber;

public void init()

{ // reading from HTML param tag

message = getParameter("displayMessage");

String num1 = getParameter("number1");

String num2 = getParameter("number2");

// do parsing (if needed) after reading HTML param

firstNumber = Integer.parseInt(num1);

secondNumber = Double.parseDouble(num2);

public void paint(Graphics g)

{ // print HTML param values

g.drawString(message, 50, 60);

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 58


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

g.drawString("Flexible code: Product of two numbers: " + firstNumber *


secondNumber, 50, 80);

}
html file: file name appletparameter.html

<applet code="DemoApplet.class" width="300" height="200">

<param name="displayMessage" value="Hello World">

<param name="number1" value="10">

<param name="number2" value="20.5">

</applet>

Output

 Example pass a few parameters like Name, Age, Sport, Food, Fruit,
Destination to the applet using param attribute in <applet>
 Next, retrieve the values of these parameters using getParameter() method
of Applet class.
File Name: Applet8.java

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 59


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

import java.awt.*;

import java.applet.*;

/*

<applet code="Applet8" width="400" height="200">

<param name="Name" value="Roger">

<param name="Age" value="26">

<param name="Sport" value="Tennis">

<param name="Food" value="Pasta">

<param name="Fruit" value="Apple">

<param name="Destination" value="California">

</applet>

*/

public class Applet8 extends Applet

String name;

String age;

String sport;

String food;

String fruit;

String destination;

public void init()

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 60


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

name = getParameter("Name");

age = getParameter("Age");

food = getParameter("Food");

fruit = getParameter("Fruit");

destination = getParameter("Destination");

sport = getParameter("Sport");

public void paint(Graphics g)

g.drawString("Reading parameters passed to this applet -", 20, 20);

g.drawString("Name -" + name, 20, 40);

g.drawString("Age -" + age, 20, 60);

g.drawString("Favorite fruit -" + fruit, 20, 80);

g.drawString("Favorite food -" + food, 20, 100);

g.drawString("Favorite destination -" + name, 20, 120);

g.drawString("Favorite sport -" + sport, 20, 140);

Compile the program as : java Applet8.java

To run this program: appletviewer Applet8.java

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 61


Dept. of Computer Science Engineering,KESHAV MEMORIAL INSTITUTE OF TECHNOLOGY

Output

Academic Dairy Handbook : JAVA PROGRAMMING II CSE II SEM 62

You might also like