You are on page 1of 4

Applets

A fancy interface wins over


plain text any day

Copyright, 2001 © Ahmed Kamel

What is a Java Applet

| A Java applet is a graphical user interface


to some underlying code
| An applet is intended to be run from a web
browser as part of a web page
| To run an applet, we need 2 things:
z The code for the applet itself
z An html file with code to run the applet
| An applet can be run by either:
z Using an applet viewer
z Starting it from a web browser

Copyright, 2001 © Ahmed Kamel 2

Applets for Testing

| Applets can provide a nice


interface for testing a class
| An applet can provide a quick and
easy user interface to the different
methods

Copyright, 2001 © Ahmed Kamel 3


Sample Applet

Copyright, 2001 © Ahmed Kamel 4

Applet Definition
1. Import statements:
z import IntArrayBag;
z import java.applet.Applet;
z import java.awt.*;
z import java.awt.event.*;
2. Class Definition:
public class BagApplet extends Applet
{
//Declare an IntArrayBag for the applet to manipulate
IntArrayBag b = new IntArrayBag();

}

Copyright, 2001 © Ahmed Kamel 5

Applet Definition (cont.)

3. Declaration of the Applet Components:


Components are objects to display on the
applet’s window, e.g. Button, TextField,
TextArea, Label, Canvas

Sample code:
Button sizeButton = new Button (“size()”);
TextField elementText = new TextField (10);
TextArea feedback = new TextArea (7, 60);
Canvas line = new Canvas ( );

Copyright, 2001 © Ahmed Kamel 6


Applet Definition

4. init method:
z A method that will be run when the
applet is activated
z Similar to “main” in an application
z Note: “init” is not a static method

Copyright, 2001 © Ahmed Kamel 7

Sample init Method

Copyright, 2001 © Ahmed Kamel 8

Applet Definition
5. Implementation of action listeners:
Action listeners are methods to be activated
when actions occur (e.g. buttons are
pressed)
Sample:

Copyright, 2001 © Ahmed Kamel 9


Some Useful Methods for
Components

| setActionListener (ActionListener act)


| append (String message)
| getText ( )

| setEditable (boolean editable)

| requestfocus( )

| selectAll( )

| setSize int width, int height)

Copyright, 2001 © Ahmed Kamel 10

Applet Definition

6. Implementation of other necessary


methods
Sample:

Copyright, 2001 © Ahmed Kamel 11

Running a Java Applet

| Compile as usual
| Create an html file (in the same directory as the
applet) that looks like this:

<applet code=“Class file goes here” width=value1 height =value2>


</applet>

| Run the html file either through the applet viewer


or through your web browser

Copyright, 2001 © Ahmed Kamel 12

You might also like