A346/A348 Java Applets |
A Java applet is a Java program that can be executed on the browser client. Java is a modern language with C++ style syntax, supporting object-oriented programming, dynamic memory management, light-weight threads, GUI design, and is designed for networked applications. Java programs are compiled into machine code for the Java Virtual Machine rather than Intel or Apple or other machine code, browsers implement an interpreter that simulates the JVM. A Java applet is then a Java program running on the JVM implemented by the browser. Since the JVM can be implemented on any browser (NetScape and IE do), this offers the potential for a write once/run anywhere programming language. In reality the JVM implementation differs slightly from one browser to another (my own experience with a serious applet is that it runs differently on every operating system just using Netscape, IE explodes on some machines and works fine on others), or as some wag said, applets create a write once/debug everywhere programming language.
The reality is that for implementing highly interactive Web GUIs on clients that are comparable to Windows, Linux, Apple, etc. the choices are limited to plug-ins, ActiveX on IE only that are not secure, or Java applets that can in theory run anywhere safely. Java applets offer a choice of portability (runs on most browsers), security (restricted from accessing local hardware), and ease of delivery (does not require registration as does ActiveX or installation as do plug-ins such as Flash!).
Applets tend to be useful where:
The code of an applet is stored in a file on the server and is automatically loaded by the browser whenever it encounters an <Applet> tag in the HTML. For example the following applet was loaded because this HTML contains <applet code=Box.class width=150 height=150></applet>. The Box.class file contains the code for the applet, other class files used by the Box applet would automatically be loaded by the browser also.
Below are several demonstration applets.
The simplest applet. Draws the string "Hello World" in the applet window area. Points of note are:
| HelloWorld.HTM
<applet code="HelloWorldApp.class" width=150 height=150></applet>
import java.awt.*; public class HelloWorldApp extends Applet { public void
paint(Graphics g) { |
A simple applet that can draw a fixed size box or erase it. Demonstrates user interface design using buttons and line graphics. Java has a built in set of buttons, list, etc. for implementing a user interface. Points of note are:
| HTML
<applet code="Box.class" width=150 height=150></applet>
import java.awt.*; |
Buttons generate events when clicked. All user interface object events execute the action method. To demultiplex which object generated the event, the button caption can be examined as in:
if (o.equals("Draw Box")
To use graphics with drawLine or drawString methods requires a Graphics object. One way to get the Graphics object representing the applet is using method getGraphics. For example, to write Hello World:
Graphics g = getGraphics( );
g.drawString("Hello World", 50, 50);
Demonstrates interaction with user via the mouse.
| HTML
<h2>Sketch</h2><br> SketchApp.java import java.awt.*;
import java.applet.*;
public class SketchApp extends Applet {
private int startx, starty, endx, endy;
public void init() {
setBackground(Color.yellow);
}
public boolean mouseDown(Event evt, int x, int y) {
startx = x;
starty = y;
return true;
}
public boolean mouseUp(Event evt, int x, int y) {
startx = x;
starty = y;
return true;
}
public boolean mouseDrag(Event evt, int x, int y) {
endx = x;
endy = y;
repaint();
return true;
}
public void update(Graphics g) {
paint(g);
startx = endx;
starty = endy;
}
public void paint(Graphics g) {
g.drawLine(startx, starty, endx, endy);
}
}
|
Demonstrates nothing special other than an application that you implemented for Homework 2.
| HTML
<applet
import java.awt.*; public class Calculator extends Applet public void init() p = new Panel(); for(int i=0; i<=9; i++) p.add(new Button("+")); add("Center", p); |
One useful and interesting model supported by Java is that of light-weight threads that run within the environment of the main application thread. This allows multi-threaded applications to operate with relatively low overhead and corresponding good performance, since threads are part of the language design rather than being implemented by the operating system, threaded applications are portable at the code level. Java threads can execute within the same environment scope so that data can be shared between threads. Synchronization of threads is achieved using the monitor model (versus tasks in Ada or semaphores in languages such as C and C++ that rely on operating system calls).
A key use of threads is to handle blocking method invocations. When a method is invoked it normally does not return until completed (unless an event such as a mouse clieck occurs) implying that any other program execution is temporarily stopped. By using individual threads to handle methods that may block for an unknown (possibly long) period of time, other program functions can continue.
A working definition of a thread is an execution. All programs have at
least one thread of execution control, Java supports multiple, light-weight
threads of execution. An example of a heavy-weight thread is a single program in
execution where the internal environments of other heavy-weight threads are
isolated from one another. A heavy-weight program can have multiple light-weight
threads, each being switched to execute for a time but then temporarily
suspended while another thread executes. The prime distinction between heavy and
light weight threads are that light weight threads can share a common program
environment, when thread switching occurs between light weight threads there is
less individual thread information to switch since much is common to all. The
key advantages of Java thread support are: 1) thread communication is relatively
easy to program since part of the language, 2) inexpensive in execution since
light weight, and 3) allows a program to handle multiple, concurrent operations
in a relatively platform independent fashion.
We'll use a bouncing ball to illustrate differences in multi-threaded execution. Our first thread example uses a single heavy weight thread to bounce a single ball off the sides of the display window. The Ball class implements the ball bouncing, since a single thread is used, only one ball can be bounced at a time. The most important part of the program is:
public void bounce()
{
for (int i = 1; i <= 1000; i++)
{ move();
try { Thread.sleep(5); } catch(InterruptedException e) {}
}
}
which is invoked once as a normal function call from action() function by clicking the Toss button. The button click:
| HTML
<applet code="Bounce.class" WIDTH="641" height="100"></applet> Bounce.java
|
basicBall.java
import java.awt.*; public class basicBall static final int XSIZE = 10; int x = 0; public basicBall(Applet a) public int x() { return x; } public void draw() public void move() { |
With only minor changes to the previous example, multiple light-weight threads can control many simultaneously bouncing balls. The key changes are:
public void bounce()
{ for (int i = 1; i <= 1000; i++)
{ move();
try { Thread.sleep(5); } catch(InterruptedException e) {}
}
}
Now the bounce() constructs a new thread then calls the start() function which in turn invokes the thread's run() function, which controls the thread execution. The thread usually executes until the run() function completes executing.
public void bounce()
{ new Thread(this).start();
}
public void run()
{ for (int i = 1; i <= 1000; i++)
{ move();
try { Thread.sleep(5); } catch(InterruptedException e) {}
}
}
Click the Toss button rapidly and notice that all the balls appear to move at the same rate. This is due to the Thread.sleep(5); which suspends the running thread giving the others a chance to run. The threads are in effect taking turns running so that each thread makes progress, so that one ball moves then the next, etc.
BounceThread.java
|
Java applet methods that take 0 or more String parameters can be called by JavaScript. This is useful for extending the capability of JavaScript to the level of Java, within the usual security restrictions enforced on applets. In some ways, this provides much of the same potential as ActiveX for extending the scripting language within the limitations and safety of applet security. In addition to applets generally accepted as safe, JavaScript and Java applets are supported by most browsers making applications more portable.
Simple example - The first example is the HelloWorld applet
that can have a different greeting based upon user form input. The applet has a
public method setGreeting that takes a String parameter, the HTML
supplies the parameter through a method call. The parameter is the value of a
form variable supplied in the HTML. The applet method is invoked through an
onClick event in the user form.
NewHelloWorld.htm
<applet name = "Greeter" code="NewHelloWorldApp.class" width=150 height=150></applet>
<form name=formGreeter>
Enter new greeting <input type=text size=40 name="theGreeting">
<input type=button value="Change"
onClick="document.Greeter.setGreeting(theGreeting.value)"><br>
</form>
// NewHelloWorldApp.java import java.awt.*;
import java.applet.*;
public class NewHelloWorldApp extends Applet {
String greeting = "Hello World";
public void paint(Graphics g) {
g.drawString(greeting, 50, 50);
}
public void setGreeting(String greeting) {
this.greeting = greeting;
repaint();
}
}
|
Complex example - The following is an example of JavaScript calling a Java applet method that plots X-Y data. Click Plot to plot the data in the text boxes. To plot new data, change the text boxes and click Plot.
Seperate data with spaces.
| xyPlot.htm
<Title>xyPlot</Title> |
Java - The xyPlot Java method must be public, and as far as I can determine, the parameters must be of class String. Due to the program length it is not given but is available for downloading. The prototype is:
public void xyPlot(String x, String y, String xAxis, String yAxis)
JavaScript/HTML
| <Body onload='document.DataPlot.xyPlot("1 2 3 4 5", "1 4 9 16 25",
"X", "Y") '> <Applet code="Plot/DataPlot.class" name='DataPlot' WIDTH=300 HEIGHT=300> </Applet> |
Document last modified: