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
o Plugin is required at client browser to execute applet.
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 [Link] class 4 life cycle methods and [Link]
class provides 1 life cycle methods for an applet.
[Link] class
For creating any applet [Link] 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.
[Link] 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.
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.
//[Link]
1. import [Link];
2. import [Link];
3. public class First extends Applet{
4.
5. public void paint(Graphics g){
6. [Link]("welcome",150,150);
7. }
8. }
[Link]
1. <html>
2. <body>
3. <applet code="[Link]" width="300" height="300">
4. </applet>
5. </body>
6. </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
[Link]. Now Html file is not required but it is for testing purpose only.
1. //[Link]
2. import [Link];
3. import [Link];
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. [Link]("welcome to applet",150,150);
8. }
9. }
10. /*
11. <applet code="[Link]" width="300" height="300">
12. </applet>
13. */
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac [Link]
c:\>appletviewer [Link]
Displaying Graphics in Applet
[Link] 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.
[Link] abstract void setColor(Color c): is used to set the graphics current
color to the specified color.
[Link] abstract void setFont(Font font): is used to set the graphics
current font to the specified font.
Example of Graphics in applet:
Write a java program for the example of different shapes in Graphics class
1. import [Link];
2. import [Link].*;
3. public class GraphicsDemo extends Applet{
4. public void paint(Graphics g){
5. [Link]([Link]);
6. [Link]("Welcome",50, 50);
7. [Link](20,30,20,300);
8. [Link](70,100,30,30);
9. [Link](170,100,30,30);
[Link](70,200,30,30);
11. [Link]([Link]);
12. [Link](170,200,30,30);
[Link](90,150,30,30,30,270);
14. [Link](270,150,30,30,0,180);
15. }
16.}
[Link]
1. <html>
2. <body>
3. <applet code="[Link]" width="300" height="300">
4. </applet>
5. </body>
6. </html>
Process of working with Color Classes:
Java supports color in a portable, device-independent fashion. The AWT color
system allows you to specify any color you want. It then finds the best match for
that color, given the limits of the display hardware currently executing your
program or applet. Thus, your code does not need to be concerned with the
differences in the way color is supported by various hardware devices. Color is
encapsulated by the Color class.
Color(int red, int green, int blue)
constructor takes three integers that specify the color as a mix of red, green, and blue. Thes
values must be between 0 and 255, as in this example:
new Color(255, 100, 100); // light red
Once you have created a color, you can use it to set the foreground and/or background color b
using the setForeground( ) and setBackground( ) methods described in Chapter 23. You can als
select it as the current drawing color.
Ex:
import [Link].*;
import [Link].*;
/* <applet code="ColorDemo" width=300 height=200> </applet>*/
public class ColorDemo extends Applet
{ // draw lines
public void paint(Graphics g) {
Color c1 = new Color(255, 100, 100);
Color c2 = new Color(100, 255, 100);
Color c3 = new Color(100, 100, 255);
[Link](c1); [Link](0, 0, 100, 100); [Link](0, 100, 100, 0);
[Link](c2); [Link](40, 25, 250, 180); [Link](75, 90, 400, 400);
[Link](c3); [Link](20, 150, 400, 40); [Link](5, 290, 80, 19);
[Link]([Link]); [Link](10, 10, 50, 50);
[Link](70, 90, 140, 100);
[Link]([Link]); [Link](190, 10, 90, 30); [Link](10, 10, 60, 50);
[Link]([Link]); [Link](100, 10, 60, 50);
[Link](190, 10, 60, 50, 15, 15);
Process of working with Font Classes:
The Font class provides a method of specifying and using fonts. The Font class
constructor constructs font objects using the font’s name, style (PLAIN, BOLD, ITALIC,
or BOLD + ITALIC), and point size. Java’s fonts are named in a platform independent
manner and then mapped to local fonts that are supported by the operating system on
which it executes. The getName() method returns the logical Java font name of a
particular font and the getFamily() method returns the operating system-specific name
of the font. The standard Java font names are Courier, Helvetica, TimesRoman etc.
The font can be set for a graphics context and for a component.
Font getFont() It is a method of Graphics class used to get the font property
setFont(Font f) is used to set a font in the graphics context. There are so many
methods are there for the Font class.
getSize(),getStyle(),isBold(),isItalic(),isPlain().
There are following logical font names which are standard on all platforms and are
mapped to actual fonts on a particular platform:
“Serif” variable pitch font with serifs
“SansSerif” variable pitch font without serifs
“Monospaced” fixed pitch font
“Dialog” font for dialogs
“DialogInput” font for dialog input
“Symbol” mapped to the Symbol font
Font style is specified using constants from the Font class:
[Link]
[Link]
Ex:
import [Link];
import [Link].*;
import [Link].*;
/* <APPLET CODE ="[Link]" WIDTH=300 HEIGHT=200> </APPLET> */
public class FontClass extends [Link]
{
Font f;
String m;
public void init()
{
f=new Font("Arial",[Link],20);
m="Welcome to Java";
setFont(f);
}
public void paint(Graphics g)
{
Color c=new Color(0,255,0);
[Link](c);
[Link](m,4,20);
}
}
Java AWT
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 [Link] package provides classes for AWT API such
as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.
Features of AWT in Java
AWT is a set of native user interface components
It is based upon a robust event-handling model
It provides Graphics and imaging tools, such as shape, color, and font classes
AWT also avails layout managers which helps in increasing the flexibility of
the window layouts
Data transfer classes are also a part of AWT that helps in cut-and-paste
through the native platform clipboard
Supports a wide range of libraries that are necessary for creating graphics for
gaming products, banking services, educational purposes, etc.
Now that you are aware of the various features of AWT let me now introduce
the aspects of GUI in the next section of this Java AWT tutorial.
AWT UI Aspects
Any UI will be made of three entities:
UI elements: These refers to the core visual elements which are visible to
the user and used for interacting with the application. AWT in Java provides a
comprehensive list of widely used and common elements.
Layouts: These define how UI elements will be organized on the screen and
provide the final look and feel to the GUI.
Behavior: These define the events which should occur when a user interacts
with UI elements.
I hope, by now you have a brief idea about AWT and what is its role in any
application. In the next section of this Java AWT Tutorial, I will be throwing
some light on the complete AWT hierarchy.
Hierarchy Of AWT
As you can see in the above diagram, Component is the superclass of all the
GUI controls. It is an abstract class which encapsulates all the attributes of a
visual component and represents an object with graphical representation. A
component class instance is basically responsible for the look and feel of the
current interface.
AWT Components
1. Containers
Container in Java AWT is a component that is used to hold other components
such as text fields, buttons, etc. It is a subclass of [Link] and is
responsible for keeping a track of components being added. There are four
types of containers provided by AWT in Java.
Types of Containers
1. Window: It is an instance of the Window class having neither border nor title.
It is used for creating a top-level window.
2. Frame: Frame is a subclass of Window and contains title, border and menu
bars. It comes with a resizing canvas and is the most widely used container
for developing AWT applications. It is capable of holding various components
such as buttons, text fields, scrollbars, etc. You can create a Java AWT Frame
in two ways:
i. By Instantiating Frame class
ii. By extending Frame class
3. Dialog: Dialog class is also a subclass of Window and comes with the border
as well as the title. Dialog class’s instance always needs an associated Frame
class instance to exist.
4. Panel: Panel is the concrete subclass of Container and doesn’t contain any
title bar, menu bar or border. Panel class is a generic container for holding the
GUI components. You need the instance of the Panel class in order to add the
components.
That was all about the container and its types let us now move further in this
Java AWT Tutorial article and learn about the rest of the components.
2. Button
[Link] class is used to create a labeled button. GUI component that
triggers a certain programmed action upon clicking it. The Button class has
two constructors:
/Construct a Button with the given label
public Button(String btnLabel);
//Construct a Button with empty label
public Button();
A few of the methods provided by this class have been listed below:
//Get the label of this Button instance
public String getLabel();
//Set the label of this Button instance
public void setLabel(String btnLabel);
//Enable or disable this Button. Disabled Button cannot be clicked
public void setEnable(boolean enable);
3. Text Field
A [Link] class creates a single-line text box for users to enter
texts. The TextField class has three constructors which are:
//Construct a TextField instance with the given initial text string with the
number of columns.
public TextField(String initialText, int columns);
//Construct a TextField instance with the given initial text string.
public TextField(String initialText);
//Construct a TextField instance with the number of columns.
public TextField(int columns);
A few of the methods provided by TextField class are:
// Get the current text on this TextField instance
public String getText();
// Set the display text on this TextField instance
public void setText(String strText);
//Set this TextField to editable (read/write) or non-editable (read-only)
public void setEditable(boolean editable);
4. Label
The [Link] class provides a descriptive text string that is visible on
GUI. An AWT Label object is a component for placing text in a container.
Label class has three constructors which are:
// Construct a Label with the given text String, of the text alignment
public Label(String strLabel, int alignment);
//Construct a Label with the given text String
public Label(String strLabel);
//Construct an initially empty Label
public Label();
This class also provides 3 constants which are:
public static final LEFT; // [Link]
public static final RIGHT; // [Link]
public static final CENTER; // [Link]
Below I have listed down the public methods provided by this class:
public String getText();
public void setText(String strLabel);
public int getAlignment();
//[Link], [Link], [Link]
public void setAlignment(int alignment);
5. Canvas
A Canvas class represents the rectangular area where you can draw in an
application or receive inputs created by the user.
6. Choice
Choice class is used to represent a pop-up menu of choices. The selected
choice is shown on the top of the given menu.
7. Scroll Bar
The Scrollbar class object is used to add horizontal and vertical scrollbar in
the GUI. It enables a user to see the invisible number of rows and columns.
8. List
The object of List class represents a list of text items. Using the List class a
user can choose either one item or multiple items.
9. CheckBox
The Checkbox is a class is a graphical component that is used to create a
checkbox. It has two state options; true and false. At any point in time, it can
have either of the two.
So, that was all you need to know about the AWT components. Now, I hope
you are ready to get your feet wet with Java AWT application.
In the next section of this Java AWT tutorial, I will show you how to build a
calculator using AWT components.
Developing a Calculator with Java AWT
Here I will show you how to create a calculator using AWT, where you will be
able to perform basic mathematical operations. Below is a screenshot of how
your Calculator will look like:
Now in order to build this, you need to type in the following code:
import [Link].*;
import [Link];
import [Link];
class Calculator extends Frame implements ActionListener
{
Label lb1,lb2,lb3;
TextField txt1,txt2,txt3;
Button btn1,btn2,btn3,btn4,btn5,btn6,btn7;
public Calculator()
{
lb1 = new Label("Var 1");
lb2 = new Label("Var 2");
lb3 = new Label("Result");
txt1 = new TextField(10);
txt2 = new TextField(10);
txt3 = new TextField(10);
btn1 = new Button("Add");
btn2 = new Button("Sub");
btn3 = new Button("Multi");
btn4 = new Button("Div");
btn5 = new Button("Mod");
btn6 = new Button("Reset");
btn7 = new Button("Close");
add(lb1);
add(txt1);
add(lb2);
add(txt2);
add(lb3);
add(txt3);
add(btn1);
add(btn2);
add(btn3);
add(btn4);
add(btn5);
add(btn6);
add(btn7);
setSize(200,200);
setTitle("Calculator");
setLayout(new FlowLayout());
//setLayout(new FlowLayout([Link]));
//setLayout(new FlowLayout([Link]));
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae) {
double a=0,b=0,c=0;
try
{
a = [Link]([Link]());
}
catch (NumberFormatException e) {
[Link]("Invalid input");
}
try
{
b = [Link]([Link]());
}
catch (NumberFormatException e) {
[Link]("Invalid input");
}
if([Link]()==btn1)
{
c = a + b;
[Link]([Link](c));
}
if([Link]()==btn2)
{
c = a - b;
[Link]([Link](c));
}
if([Link]()==btn3)
{
c = a * b;
[Link]([Link](c));
}
if([Link]()==btn4)
{
c = a / b;
[Link]([Link](c));
}
if([Link]()==btn5)
{
c = a % b;
[Link]([Link](c));
}
if([Link]()==btn6)
{
[Link]("0");
[Link]("0");
[Link]("0");
}
if([Link]()==btn7)
{
[Link](0);
}
}
public static void main(String[] args)
{
Calculator calC = new Calculator();
[Link](true);
[Link](300,300);
}
}
A program To demonstrate text fields, button, scrollbar,
choice, list, check box using applet in java:
Source Code | Java program
import [Link].*;
import [Link].*;
/* <applet code="GUIExample" width=250 height=200> </applet> */
public class GUIExample extends Frame implements ActionListener, ItemListener, AdjustmentListener {
private Button button;
private Checkbox checkbox;
private Scrollbar scrollbar;
private Choice choice;
public GUIExample() {
setTitle("Java GUI Example");
setSize(400, 300);
setLayout(new FlowLayout());
button = new Button("Click me");
[Link](this);
checkbox = new Checkbox("Check me");
[Link](this);
scrollbar = new Scrollbar([Link], 0, 1, 0, 100);
[Link](this);
choice = new Choice();
[Link]("Option 1");
[Link]("Option 2");
[Link]("Option 3");
[Link](this);
add(button);
add(checkbox);
add(scrollbar);
add(choice);
setVisible(true);
public void actionPerformed(ActionEvent e) {
if ([Link]() == button) {
[Link]("Button clicked");
public void itemStateChanged(ItemEvent e) {
if ([Link]() == checkbox) {
if ([Link]()) {
[Link]("Checkbox checked");
} else {
[Link]("Checkbox unchecked");
} else if ([Link]() == choice) {
[Link]("Selected option: " + [Link]());
public void adjustmentValueChanged(AdjustmentEvent e) {
[Link]("Scrollbar value: " + [Link]());
public static void main(String[] args) {
new GUIExample();
Design Frame window with example:
Types of events:
Sources of events:
Event Handling:
Handling keyboard events:
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="Key" width=300 height=400>
</applet>
*/
public class Key extends Applet implements KeyListener
{
String msg="";
public void init()
{
addKeyListener(this);
public void keyPressed(KeyEvent k)
{
showStatus("Keypressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyReleased");
}
public void keyTyped(KeyEvent k)
{
showStatus("KeyTyped");
msg=msg+[Link]();
repaint();
}
public void paint(Graphics g)
{
[Link](msg,20,40);
}
}
Write a Java program for handling mouse
events.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
public class MouseEvents extends Applet implements
MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
// Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
// Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint();
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = [Link]();
mouseY = [Link]();
msg = "Down";
repaint();
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = [Link]();
mouseY = [Link]();
msg = "Up";
repaint();
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = [Link]();
mouseY = [Link]();
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " +
mouseY);
repaint();
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + [Link]() + ", " +
[Link]());
}
// Display msg in applet window at current X,Y
location.
public void paint(Graphics g) {
[Link](msg, mouseX, mouseY);
OUTPUT