Java Applet


An applet is a java program that can be embedded in a web page.

Java applications are run by using a java interpreter.

Applets are run on any browser that supports java.

Applets can also be tested using the applet viewer tool included in the java development kit.

In order to run an applet it must be included in a web page, using html tags.

When a user browses a web page containing an applet, the browser downloads the applet from the web server and runs it on the users system.

Applets have certain restrictions put on them.

  1. They cannot read or write files on the user's system.
  2. They cannot load or run any programs stored on the users system.

All applets are subclasses of applet class in the java.applet package. Applets do not have main method. All applets must be declared public.

An applet displays information on the screen by using the paint()method.

This method is available in java.awt.component class. This method takes an instance of the class graphics as parameter. The browser creates an instance of graphic class and passes to the method paint(). Graphics class provides a method drawString() to display text. It also requires position to be specified as arguments.

Applets vs Applications

Applet

  • Java program that is referenced by a web page and runs inside a Java enabled web browser.
  • In order to run, must subclass from java.applet.Applet.

Application -

  • Java program which is explicitly run by starting a new copy of the Java Virtual Machine.
  • Must define a main() method in its top level class.

Creating an applet

  • Edit the applet class which inherits from the java.applet.Applet and save it with .java extension.
    public class MyApplet extends java.applet.Applet
    {
       ......
    }
       Save this as 'MyApplet.java'

  • Compile this to get bytecode file -
    MyApplet.class
    javac MyApplet.java

  • Write a test HTML page and embed this applet in it . Save this file as, say, testpage.html

  • <html>
    <head>
    <title>My First Applet</title>
    </head>
    <body>
    <applet code="MyApplet.class" width = 300 height = 100>
    </applet>
    </body>
    </html>

  • Browse this page with any Java enabled web browser, which runs this applet
             or
    Use the minimal web browser appletviewer to run this applet only: appletviewer testpage.html

Following is the java applet:

import java.awt.*;
import java.applet.*;
public class AppletTest extends Applet
{
	public void paint (Graphics g)
	{
		g.drawString ("Hello Dear friends of 3rd Sem",35,25);
	}
}

<html>
<head>
<title>First Page</title>
</head>
<body>
<h3>This page shows the applet<h3>
<applet code="AppletTest.class" width = 300 height = 100>
</applet>
<hr>
</body>
</html>

Steps for Execution

  1. Compile the java program. You will get the class file.
  2. Store the html program with the extension html.

The applet can be viewed by typing:
appletviewer NameOfHtmlFile.
appletviewer AppletTest.html.

Click here for .java code.

Click here for .html code.

Applet tag

  • To view an applet, an HTML code is written. This code contains <applet tag>
  • <applet> tag has different attributes and they are:
    • CODE-specifies the name of the applet's main class file
    • WIDTH-specifies the width of the applet windows on the web page
    • HEIGHT-specifies the height of the applet window
    • ALIGN-This could be set to LEFT, RIGHT, MIDDLE, TOP
    • HSPACE-Controls the horizontal space to the left and right of the applet
    • VSPACE-Controls the vertical space above and below the applet
    • CODEBASE-Indicates an alternate folder or alternate web site for the browser to locate the applet
    • ALT-specifies the text to be displayed if the browser understands the applet tag, but can't run Java Applets

Life Cycle of an Applet

There are 4 important phases in the life cycle of an Applet.

  1. Initialization occurs when the applet is loaded. This is implemented by the init() method.
  2. An applet is started after it is initialized. This is done by the start() method.
  3. Stopping occurs when the user leaves the page containing the applet or when an applet stops itself by calling stop() method.
  4. destroy() method is used for destructions. This method performs cleanup process when the browser exits.

Applet Initialization and Termination

When an applet begins, the AWT calls the following methods, in sequence

  • public void init()
  • public void start()
  • public void paint(Graphics g)

When an applet is terminated, the following methods calls take place

  • public void stop()
  • public void destroy()

Init() - This method is the first method to be called. This is where you should initialize variables. This method is called only once during the run time of your applet.

Start() - This is called after init(). It is also called to restart the applet after it has been stopped. That is if the user goes to another page and comes back, the applet resumes execution.

Paint() - This is called when each time your applet,s output must be redrawn. This may happen when u minimize the window and again restored, the paint() method is called.

Stop() - This method is called when a web browser leaves the HTML document containing the applet-when it goes another page.

Destroy() - This method is called when the environment determines that your applet needs to be removed completely from memory.

Passing parameters to applet

To pass parameter to applet

  1. Include appropriate <PARAM> tag in HTML document.
  2. Provide code in the applet to parse these parameters

Parameters are passed to an applet when it is loaded. We can use the init() method in the applet to get hold of the parameters defined in the <PARAM> tags. This is done using the getParameter() method, which takes one string argument representing the name of the parameter and returns a string containing the value of the parameter.

The values are passed to applets using attribute PARAM in the applet tag Param <applet ....><param name=paramName value=""></applet>

Applet's init()String
Pass=getParameter(paramName)

Example :

Click here for .java code.

Click here for .html code.

Positioning Text in Applet Window

Example:
g.drawString("Hello World",25,30);

Changing Font and Color

  • Create Font and Color objects

    Color col = new Color(int r,int g,int b); // 0 - 255

    Font f = new Font(String fontName, int fontStyle, int size)

  • Set this font and color to the graphics object.

    g.setColor(col);

    g.setFont(f);

Example :

Click here for .java code.

Click here for .html code.

Graphics class

The graphics class provides methods to draw various graphics and manage fonts and colors. Some of them are given

  • drawLine(x1,y1,x2,y2);
  • drawRect(x,y,width,height);
  • fillRect(x,y,width,height);
  • drawOval(x1,y1,width,height)
  • fillOval(x1,y1,width,height)
  • setBackground(c)
  • setColor( c)- sets color of text

Example :

Click here for .java code.

Click here for .html code.


Click here for .java code.

Click here for .html code.


Click here for .java code.

Click here for .html code.

User Interfaces for Applets

The abstract Windowing Toolkit, also called AWT is a set of classes, enabling the user to create a user friendly, GUI. It will also facilitate receiving user input from the mouse and keyboard. The AWT classes are part of the java.awt package.
The user interfaces consists of following three java.awt

  • Components:Anything that can be put on the user Interface. This includes buttons, check boxes, pop menus, text fields.
  • Containers:This is a component that can contain other components. This include applet window, dialog boxes etc.
  • Layout Managers:These define how the components will be arranged in a container.

Building GUI

GUI Components

  • Are visual objects with which the user may interact via the mouse or keyboard.
  • Are grouped in 'java.awt' package.

AWT supplies the following components

  • labels
  • Buttons
  • Check Boxes
  • Single-line Text fields
  • Text area
  • Lists
  • Scrollbars
  • Drawing areas etc.

Container class hierarchy

Adding components to user Interface

Because all applets are containers, components can be added directly to the applet windows

  • Create the component by creating an object of that class
  • Call the containers add method to add the component

Labels

Label display non editable text. To create a label use one of the following

  • Label()-creates an empty label
  • Label(string)- creates a label with the given string
  • Label(string, int)-creates a label with the given string and right, left or center alignment

Buttons

Clickable buttons can be created from the Button class. You can create a button by using either of the following

  • Button()- Creates a button without any label.
  • Button(string)-creates a button with the given string as the label.

Checkboxes

They are labeled or unlabeled boxes that can be either checked off or empty.
They are used for selecting some option. Use one of the following to create them.

  • Checkbox()-Creates a checkbox without any label.
  • Checkbox(string)- creates a labeled checkbox.

Check boxes can be organized into groups so that only one of them can be checked at a time. The following statement used for that
Checkbox Group mygroup = new CheckboxGroup();
To create a checkbox, belonging to this group, use the following statement
Checkbox c1=new Checkbox("Phnom Penh", mygroup, true);

Steps to create a GUI

  • Declare for the GUI component type.
  • Call the appropriate constructor with the suitable arguments.
  • Add these components to the container (Applet, Frame or Panel)
  • Add the appropriate listeners to these components.
  • Override the listener methods and handle the event generated by them

Examples :

Click here for .java code.

Click here for .html code.


Click here for .java code.

Click here for .html code.

Text Fields

Text field is an editable component. Text field can be created by using one of the following:

  • TextField()-creates an empty text field
  • TextField(string)-creates a text field with the specified string
  • TextField(string, int)-creates a text field with the specified string and specified width

The TextField() class has several useful methods

  • getText() method returns the text in the field
  • setText(string) method fills the field with the string
  • setEditable(boolean) method decides whether the field should be editable or not depending upon the boolean value
  • isEditable() method returns a boolean value indicating whether the field is editable or not

Text Areas

These are editable text fields having more than one line of input. Use one of the following to create a text area

  • TextArea()-creates an empty text area
  • TextArea(rows, characters)-creates a text area of rows specified and width to accommodate the characters specified
  • TextArea(string)
  • TextArea(string, rows, characters)

The methods available in case of Text field can also be used here

Example :

Click here for .java code.

Click here for .html code.


Click here for .java code.

Click here for .html code.


Click here for .java code.

Click here for .html code.

Choice lists

They are also called as pop up lists. They enable a single item to be chosen from a list of items Choice list is created and used as follows.

  • Create an object of the class Choice
  • Add items to the list by using the method additem(item) in the Choice class
  • Add the list as you do with any other component using the add(component) method

Methods of choice class

  • getItem(index)-Returns text of the list item at the index position specified in the argument
  • getItemCount()- returns the number of items in the list
  • getSelectIndex()- returns the index position of the currently selected item
  • getSelectedItem()-returns the text of the currently selected item
  • Select(pos)-selects the item at the indicated index position
  • Select(index)-select the first item in the list with the given text

Scrolling Lists

These are created from the List class. These are similar to choice list. But here you can choose more than one item at a time. Scrolling lists do not pop up. Multiple items are displayed at the same time. The list is created by choosing one of the following

  • List()-creates an empty scrolling list enabling only one item to be selected at a time
  • List (item, boolean)- creates a scrolling list with number of items equal to the first argument. The boolean argument allows multiple selection is set to true
  • Additem() method used to add items to the list

Example :

Click here for .java code.

Click here for .html code.

Arranging Components on User Interface

By using the layout managers, programmer can gain control over the layout of an Interface instead adding the components to applet window by a default lay out mechanism AWT has five basic layout manager

  1. FlowLayout
  2. GridLayout
  3. BorderLayout
  4. CardLayout
  5. GridbagLayout

Laying out Components

FlowLayout:

This is the default layout manager. Components are added to the container from left to right. When there is no space in a row, components get added in the next row from left to right and so on. By default the components on each row are centered.

FlowLayout f = new FlowLayout();
FlowLayout f = new FlowLayout(align);

The align could be any of the FlowLayout.LEFT, FlowLayout.RIGHT, FlowLayout.CENTER

FlowLayout f = new FlowLayout(align,hgap,vgap);
Hgap is the horizontal gap between the components in pixel
Vgap is the vertical gap between the components in pixel

GridLayout:

Arranges components in a regular grid; fills left - right and top - bottom.
Its created by
GridLayout g= new GridLayout (rows, cols);
GridLayout g= new GridLayout (rows, cols,hgap,vgap);
The default gap is zero between the components.

BorderLayout:

In this the container is divided into five sections CENTER, NORTH, SOUTH, EAST, WEST. Generally the central component is largest than the other. It is created using the zero argument constructor or one which takes hgap and vgap as arguments. One the layout manager is set the components are added using the statement add(place, component). Place specifies the region.

Card Layout

  • This is a group of containers or components that are displayed one at time. Each container in the group is called a card. You can use a panel to each card and each panel can have any number of components. A card layout can be created using: CardLayout c=new CardLayout();
  • setLayout() method used to assign this layout manager for the container.
  • Add(string, container) is used to add a specific container or component to the card. The card can be displyed by show() method.

Grid Bag Layout

  • This is the extension of the grid layout manager. A grid layout differs from grid layout as given below.
  • A component can occupy more than one cell in the grid.
  • The proportions between different rows and columns do not have to be equal.
  • Components inside grid cells can be arranged in different ways.


Frames

These are the subclaees of a class called window. The Frame class provides a window with the title bar, close boxes, and other window feature. Frames are containers similar to panels. The default layout for frames is Border Layout. Use resize() method to provide a size for the window and show() method to show the window.

Examples :

Click here for .java code.

Click here for .html code.


Click here for .java code.

Click here for .html code.


Click here for .java code.

Click here for .html code.

 


Interfaces << Previous

Next>> Events

Our aim is to provide information to the knowledge


comments powered by Disqus










Footer1