Download Java Applets

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
SEN 910 CSS/HTML Programming
Java Applets Overview
Java Overview
 Design goals & features
 platform independence, portable, secure, simple, object-oriented, …
 Programming models
 applications vs. applets vs. servlets
 intro to applets
 libraries, comments, classes, inheritance
 applet tag in HTML
 applet parameters
Java
Java was developed at Sun Microsystems, 1995
 originally designed for small, embedded systems in electronic appliances
 initial attempts used C++, but frustration at limitations/pitfalls
recall: C++ = C + OOP features
the desire for backward compatibility led to the retention of many bad features
desired features (from the Java white paper):
simple
platform independent
dynamic
distributed
object-oriented
architecture neutral
interpreted
multi-threaded
robust
portable
high-performance
secure
note: these are desirable features for any modern language
thus, Java has become very popular, especially when Internet related
also, Sun distributes free compilers (JDK) and open source
Language features
simple



syntax is based on C++ (familiarity  easier transition for programmers)
removed many confusing and/or rarely-used features
e.g., explicit pointers, operator overloading, automatic coercions
added memory management (reference count/garbage collection hybrid)
object-oriented


OOP facilities similar C++, all methods are dynamically bound
pure OOP – everything is a class, no independent functions*
robust


lack of pointers and memory management avoids many headaches/errors
libraries of useful, tested classes increases level of abstraction
 arrays & strings are ADTs, well-defined interfaces
Language features (cont.)
platform independence


want to be able to run Java code on multiple platforms
neutrality is achieved by mixing compilation & interpretation
1. Java programs are translated into byte code by a Java compiler
 byte code is a generic machine code
2. byte code is then executed by an interpreter (Java Virtual Machine)
 must have a byte code interpreter for each hardware platform

an Applet is a special form of Java application
 byte code is downloaded with page, JVM is embedded in browser
architecture-neutral

no implementation dependent features
 e.g., sizes of primitive types is set (unlike C++)
portable

byte code will run on any version of the Java Virtual Machine (JVM)
Language features (cont.)
dynamic


JVM links classes at run-time as they are needed
if supporting class is recompiled, don’t have to recompile entire project
interpreted


needed for platform independence
interpreted  faster code-test-debug cycle, better run-time error checking
high-performance


faster than traditional interpretation since byte code is "close" to native code
still somewhat slower than a compiled language (e.g., C++)
Language features (cont.)
distributed


extensive libraries for coping with TCP/IP protocols like HTTP & FTP
Java applications can access remote URL's the same as local files
multi-threaded



a thread is like a separate program, executing concurrently
can write Java programs that deal with many tasks at once by defining multiple
threads (same shared memory, but semi-independent execution)
threads are important for multi-media, Web applications
secure



Java applications do not have direct access to memory locations
 memory accesses are virtual, mapped by JVM to physical locations
 downloaded applets cannot open, read, or write local files
JVM also verifies authenticity of classes as they are loaded
Sun claim: execution model enables virus-free*, tamper-free* systems
Java programming models
Java applications are stand-alone programs
 must be compiled into Java byte code by Java compiler, then distributed
 executed by an interpreter (Java Virtual Machine)
Java applets provide for client-side programming
 compiled into Java byte code, then downloaded as part of a Web page
 executed by the JVM embedded within the Web browser
 unlike JavaScript, Java is full-featured with extensive library support
 Java and its APIs have become industry standards
 the language definition is controlled by Sun, ensures compatibility
 Applications Programming Interfaces standardize the behavior of useful classes
and libraries of routines
Java servlets provide similar capabilities on the server-side
 alternative to CGI programs, more fully integrated into Web server
Java applets
important point: Java applets & applications look different!
 if you want to define a stand-alone application, make an application
requires public static void main function, similar to C++ main
 if you want to embed the code in a Web page, make an applet
requires public void paint, public void init, …
 can define dual-purpose programs, but tricky
as with JavaScript, security is central
 when a Java applet is downloaded, the bytecode verifier of the JVM verifies to see if
it contains bytecodes that open, read, write to local disk
 a Java applet can open a new window but they have Java logo to prevent them from
being disguised as system window (for stealing password)
 a Java applet is not allowed to connect back to other servers except the host
 this secure execution environment is called sand box model
First Java applet
import java.awt.*;
import java.applet.*;
/**
* This class displays "Hello world!" on the applet window.
*/
public class HelloWorld extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello world!", 10, 10); // writes starting 10 pixels over & down
}
}
libraries
Java provides extensive library support in the form of classes
 libraries are loaded using import (similar to #include in C++)
java.awt: contains Abstract Window Toolkit (for GUI classes & routines)
java.applet: contains the applet class definition
First Java applet
import java.awt.*;
import java.applet.*;
/**
* This class displays "Hello world!" on the applet window.
*/
public class HelloWorld extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello world!", 10, 10); // writes starting 10 pixels over & down
}
}
comments in Java
//
and /* . . . */ work the same as in C++
/** . . . */ designate documentation comments
 can be used to automatically generate HTML documentation (javadoc)
First Java applet
import java.awt.*;
import java.applet.*;
/**
* This class displays "Hello world!" on the applet window.
*/
public class HelloWorld extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello world!", 10, 10); // writes starting 10 pixels over & down
}
}
class definitions in Java

similar to C++ (but no semi-colon at end)
can contain instance variables (data fields) & methods(member functions)
precede class & method definitions with public to make available to all programs


there are no stand-alone functions in Java*
must be stored in a file of same name with .java extension
e.g., HelloWorld.java
First Java applet
import java.awt.*;
import java.applet.*;
/**
* This class displays "Hello world!" on the applet window.
*/
public class HelloWorld extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello world!", 10, 10); // writes starting 10 pixels over & down
}
}
all applets inherit from the Applet class (in java.applet)
default methods include:
 init(): called when page is loaded to create/initialize variables
by default, does nothing
 paint(Graphics g): called to draw (after init) or redraw (after being obscured)
here, the paint method is overridden to display text on the applet window
Embedding an applet in HTML
to include an applet in a Web page, use either
 APPLET tag (deprecated)
CODE specifies applet name, HEIGHT and WIDTH specify window size
text between the APPLET tags is displayed if unable to execute (e.g., Java not enabled)
 OBJECT tag
preferred for HTML 4, but not universally supported
<html>
<!-- Hello1.html
-->
<head>
<title>Hello World Page</title>
</head>
<body>
<p>
<applet code="HelloWorld.class" height=100 width=100>
You must use a Java-enabled browser to view this applet.
</applet>
</p>
</body>
</html>
view page in
browser
HTML & applets
<html>
<!-- Hello2.html -->
<head>
<title>Hello World Page</title>
</head>
<body>
<p>
<div align="center">
<table border=1>
<tr><td>
<applet code="HelloWorld.class" height=200 width=200>
You must use a Java-enabled browser to view this applet.
</applet>
</td></tr>
</table>
</div>
</p>
</body>
</html>
view page in browser
an applet can be
embedded within HTML
elements just like any
other element
useful for formatting and
layout
Parameters in HTML
<html>
<!-- Hello3.html
-->
<head>
<title>Hello World Page</title>
</head>
can specify parameters
to the APPLET when it
is embedded in HTML
<body>
<p>
<div align="center">
<table border=1>
<tr><td>
<applet code="HelloWorld1.class" height=35 width=300>
<param name="name" value="Chris">
<param name="age" value=20>
You must use a Java-enabled browser to view this applet.
</applet>
</td></tr>
</table>
</div>
</p>
</body>
</html>
view page in browser
• each parameter must
have its own PARAM tag
inside the APPLET
element
• specifies parameter
name and value
Applet parameters
import java.awt.*;
import java.applet.*;
/**
* This class displays a message based on parameters.
*/
public class HelloWorld1 extends Applet
{
public void paint(Graphics g)
{
String userName = getParameter("name");
int userAge = Integer.parseInt(getParameter("age"));
String message1 = "Hello " + userName + ".";
String message2 = "On your next birthday, you will be " +
(userAge+1) + " years old.";
g.drawString(message1, 10, 10);
g.drawString(message2, 10, 30);
}
}
can access parameters passed in from the HTML document
getParameter accesses the value of the parameter (must know its name)
 if the parameter represents a number, must parseInt or parseFloat
Java vs. C++
in Java, every variable & method belongs to a class
 as in C++, by default each object has its own copies of data fields
thus, known as instance variables

as in C++, a variables declared static are shared by all class objects
thus, known as class variables

similarly, can have a static method (class method)
can only operate on class variables, accessible from the class itself
class Math
{
public static final double PI = 3.14159;
public static double sqrt(double num) { . . . }
. . .
}
// access as Math.PI
// access as in Math.sqrt(9.0)
Primitive vs. reference types
primitive types are handled exactly as in C++
 space for a primitive object is implicitly allocated
 variable refers to the actual data (stored on the stack)
reference types (classes) are handled differently
 space for a reference object must be explicitly allocated using new
 variable refers to a pointer to the data (which is stored in the heap)
Note: unlike with C++, programmer is not responsible for deleting dynamic objects
JVM performs automatic garbage collection to reclaim unused memory
Java only provides by-value parameter passing
 but reference objects are implemented as pointers to dynamic memory
 resulting behavior mimics by-reference
public void Init(int[] nums)
{
for (int i = 0; i < nums.length; i++) {
nums[i] = 0;
}
}
_____________________________
int nums[] = new int[10];
Init(nums);
_
Java libraries
String class (automatically loaded from java.lang)
int length()
char charAt(index)
int indexOf(substring)
String substring(start, end)
String toUpperCase()
boolean equals(Object)
...
String str = "foo"
String str = new String("foo");
Array class (automatically loaded from java.lang)
int length
instance variable
Type [](index)
operator
int[]
String toString()
...
int[]
nums = {1,2,3,4,5};
nums = new int[10];
Java provides extensive libraries of data structures & algorithms
java.util 
Vector
Dictionary
Calendar
Stack
HashTable
LinkedList
Random
Java & inheritance
Java does NOT have templates*
 generic functions/classes are obtained via inheritance (e.g, Applet)
with inheritance, can derive a new class from an existing class
– automatically inherit attributes & methods of the parent class
– object of derived class can be used wherever parent object is expected
 every reference type is implicitly derived from the Object class
 by defining data structures that contain Objects, any reference type can be stored
(and even mixed)
Stack things = new Stack();
String str = "foobar";
things.push(str);
// pushes String as an Object
Calendar today = Calendar.getDate();
things.push(today);
// pushes Calendar as an Object
…
Calendar value1 = (Calendar)things.pop();
String value2 = (String)things.pop();
// pops & coerces
// pops & coerces
Hello again
import java.awt.*;
import java.applet.*;
import java.util.Random;
/**
* This class displays lots of "Hello world!"s on the applet window.
*/
public class HelloWorld1 extends Applet
{
private static final int NUM_WORDS=100;
private static Random randy;
Random class provides
methods for generating
random values
private int randomInRange(int low, int high)
{
return (Math.abs(randy.nextInt()) % (high-low+1)) + low;
}
public void init()
{
randy = new Random();
}
public void paint(Graphics g)
{
for (int i = 0; i < NUM_WORDS; i++) {
int x = randomInRange(1, 200);
int y = randomInRange(1, 200);
g.drawString("Hello world!", x, y);
}
}
can override init method to
allocate & initialize (similar
to a constructor)
}
<applet code="HelloWorld1.class" height=200 width=200>
You must use a Java-enabled browser to view this applet.
</applet>
Applet behavior
recall
 the init method is called when the applet is first loaded
useful for initializing variables & objects
 the paint method is called immediately after init, and whenever the applet needs to
be redrawn (e.g., after window resized or obscured)
when paint is called, it is given the default Graphics object
 Graphics methods include
void drawString(String msg, int x, int y)
void setColor(Color color)
Color class is predefined, constants include:
Color.red, Color.blue, Color.black, . . .
import java.awt.*;
import java.applet.*;
import java.util.Random;
A colorful hello
/**
* This class displays lots of "Hello world!"s on the applet window.
*/
public class HelloWorld2 extends Applet
{
private static final int NUM_WORDS=100;
private static final Color[] colors =
{Color.black,Color.red,Color.blue,Color.green,Color.yellow};
private static Random randy;
private int RandomInRange(int low, int high)
{
return (Math.abs(randy.nextInt()) % (high-low+1)) + low;
}
public void init()
{
randy = new Random();
}
public void paint(Graphics g)
{
for (int i = 0; i < NUM_WORDS; i++) {
int x = RandomInRange(1, 140);
int y = RandomInRange(10, 200);
g.setColor(colors[RandomInRange(0,4)]);
g.drawString("Hello world!", x, y);
}
}
can store possible
colors in an array
change drawing color
using the setColor
method
}
<applet code="HelloWorld2.class" height=200 width=200>
You must use a Java-enabled browser to view this applet.
</applet>
view page in
browser
Parameters & applet dimensions
recall:
 can specify parameters in the HTML document using <PARAM> tags
 access the parameter values (based on name) using getParameter method
can also access the dimensions of an applet using a Dimension object
Dimension dim = getSize();
can then access applet height via
can then access applet width via
// stores applet dimensions
dim.height
dim.width
import java.awt.*;
import java.applet.*;
import java.util.Random;
Adaptive hello
/**
* This class displays lots of "Hello world!"s on the applet window.
*/
public class HelloWorld3 extends Applet
{
private static final Color[] colors =
{Color.black,Color.red,Color.blue,Color.green,Color.yellow};
private static Random randy;
private Dimension dim;
private int numReps;
private int RandomInRange(int low, int high)
{
return (Math.abs(randy.nextInt()) % (high-low+1)) + low;
}
public void init()
{
randy = new Random();
dim = getSize();
numReps = Integer.parseInt(getParameter("reps"));
}
}
getParameter
accesses the values of
the parameters
here, specify number of
reps in Web page
uses getSize to
get dimensions, pick
random coords for text
within the applet
public void paint(Graphics g)
{
for (int i = 0; i < numReps; i++) {
int x = RandomInRange(1, dim.width-65);
int y = RandomInRange(10, dim.height);
g.setColor(colors[RandomInRange(0,4)]);
g.drawString("Hello world!", x, y);
}
}
<applet code="HelloWorld3.class" height=300 width=400>
<param name="reps" value=200>
You must use a Java-enabled browser to view this applet.
</applet>
view page in
browser
Applet graphics
in addition to displaying text
 can also draw figures on a Graphics object
void drawLine(int x1, int y1, int x2, int y2)
void drawRect(int x, int y, int width, int height)
void fillRect(int x, int y, int width, int height)
void drawOval(int x, int y, int width, int height)
void fillOval(int x, int y, int width, int height)
EXAMPLE: draw a red circle inscribed in a square, then draw random dots
(dart pricks)
 by counting the number of dots inside vs. outside the circle, can estimate the value
of p
p = 4 * (area of circle/area of square)
public class Monte1 extends Applet
{
private static Random randy;
private int NUM_POINTS;
private int SIZE;
Graphical applet
private int RandomInRange(int low, int high) { CODE OMITTED }
private double distance(int x1, int y1, int x2, int y2) { CODE OMITTED }
public void init()
{
randy = new Random();
NUM_POINTS = Integer.parseInt(getParameter("points"));
Dimension dim = getSize();
SIZE = Math.min(dim.width, dim.height);
}
init method creates random
number generator & gets
parameters
method draws a circle
and a bunch of random points
public void paint(Graphics g)
paint
{
g.setColor(Color.red);
g.fillOval(0, 0, SIZE, SIZE);
for (int i = 0; i < NUM_POINTS; i++) {
int x = RandomInRange(0, SIZE);
int y = RandomInRange(0, SIZE);
if (distance(x, y, SIZE/2, SIZE/2) < SIZE/2) {
g.setColor(Color.white);
}
<applet code="Monte1.class" height=300 width=300>
else {
<param name="points" value=20000>
g.setColor(Color.black);
You must use a Java-enabled browser...
}
</applet>
g.drawLine(x, y, x, y);
}
view page in browser
}
}
Double buffering
note: paint is called every time the page is brought to the front
 in current version of Monte, this means new dots are drawn each time the page is
obscured and then brought back to the front
 wastes time redrawing
 dots are different each time the applet is redrawn
the double buffering approach works by keeping an off-screen image
 in the init method (which is called when the page loads):
draw the figures on a separate, off-screen Graphics object
 in the paint method (which is called whenever the page is brought forward):
simply display the off-screen image on the screen
public class Monte2 extends Applet
{
. . .
private Image offScreenImage;
private Graphics offScreenGraphics;
Buffered applet
. . .
public void init()
{
randy = new Random();
NUM_POINTS = Integer.parseInt(getParameter("points"));
Dimension dim = getSize();
SIZE = Math.min(dim.width, dim.height);
offScreenImage = createImage(SIZE, SIZE);
offScreenGraphics = offScreenImage.getGraphics();
init method is called when
page is loaded
does drawing to a separate,
off-screen Graphics object
offScreenGraphics.setColor(Color.red);
offScreenGraphics.fillOval(0, 0, SIZE, SIZE);
paint
init
for (int i = 0; i < NUM_POINTS; i++) {
int x = RandomInRange(0, SIZE);
int y = RandomInRange(0, SIZE);
if (distance(x, y, SIZE/2, SIZE/2) < SIZE/2) {
offScreenGraphics.setColor(Color.white);
}
else {
offScreenGraphics.setColor(Color.black);
}
offScreenGraphics.drawLine(x, y, x, y);
}
<applet code="Monte2.class" height=300 width=300>
}
<param name="points" value=20000>
You must use a Java-enabled browser...
public void paint(Graphics g)
</applet>
{
g.drawImage(offScreenImage, 0, 0, null);
view page in browser
}
is called after
and whenever the applet is
revisited
Note: don’t see image in
progress
}
public class Monte3 extends Applet
{
Better buffering
. . .
public void init() {
randy = new Random();
NUM_POINTS = Integer.parseInt(getParameter("points"));
Dimension dim = getSize();
SIZE = Math.min(dim.width, dim.height);
}
public void paint(Graphics g) {
if (offScreenImage == null) {
offScreenImage = createImage(SIZE, SIZE);
offScreenGraphics = offScreenImage.getGraphics();
offScreenGraphics.setColor(Color.red);
g.setColor(Color.red);
offScreenGraphics.fillOval(0, 0, SIZE, SIZE);
g.fillOval(0, 0, SIZE, SIZE);
for (int i = 0; i < NUM_POINTS; i++) {
int x = randomInRange(0, SIZE);
int y = randomInRange(0, SIZE);
if (distance(x, y, SIZE/2, SIZE/2) < SIZE/2) {
offScreenGraphics.setColor(Color.white);
g.setColor(Color.white);
}
else {
offScreenGraphics.setColor(Color.black);
g.setColor(Color.black);
}
offScreenGraphics.drawLine(x, y, x, y);
g.drawLine(x, y, x, y);
}
}
else {
g.drawImage(offScreenImage, 0, 0, null);
}
}
}
if want to see image as it is
drawn, must be done in
paint
when first loaded, have
paint draw on the graphics
screen and also to an offscreen buffer
on subsequent repaints,
simply redraw the contents of
the off-screen buffer
<applet code="Monte3.class" height=300 width=300>
<param name="points" value=20000>
</applet>
view page in browser
GUI elements in applets
Java has extensive library support for GUIs (Graphical User Interfaces)
 has elements corresponding to HTML buttons, text boxes, text areas, …
each element must be created and explicitly added to the applet
nameLabel = new Label("User's name");
add(nameLabel);
nameField = new TextField(20);
nameField.setValue("Dave Reed");
add(nameField);
by default, GUI elements are placed in the order they were added, with
elements moved to the next line as needed to fit
Text boxes
public class Monte4 extends Applet
{
. . .
private Label insideLabel;
private TextField insideField;
private Label outsideLabel;
private TextField outsideField;
. . .
public void paint(Graphics g)
{
. . .
insideField.setText("0");
outsideField.setText("0");
. . .
public void init()
{
randy = new Random();
NUM_POINTS =
Integer.parseInt(getParameter("points"));
Dimension dim = getSize();
SIZE = Math.min(dim.width, dim.height);
if (distance(x, y, SIZE/2, SIZE/2) < SIZE/2) {
g.setColor(Color.white);
int value =
Integer.parseInt(insideField.getText())+1;
insideField.setText(""+value);
}
else {
g.setColor(Color.black);
int value =
Integer.parseInt(outsideField.getText())+1;
outsideField.setText(""+value);
}
insideLabel = new Label("Inside:");
add(insideLabel);
insideField = new TextField(6);
add(insideField);
outsideLabel = new Label("Outside:");
add(outsideLabel);
outsideField = new TextField(6);
add(outsideField);
}
. . .
}
}
<applet code="Monte4.class" height=300 width=300>
<param name="points" value=20000>
</applet>
view page in browser
GUI layout
public class Monte5 extends Applet
{
. . .
public void init()
{
randy = new Random();
NUM_POINTS = Integer.parseInt(getParameter("points"));
Dimension dim = getSize();
SIZE = Math.min(dim.width, dim.height);
Java provides several classes
for controlling layout
FlowLayout is default
BorderLayout allows
setLayout(new BorderLayout());
Panel p = new Panel();
insideLabel = new Label("Inside:");
p.add(insideLabel);
insideField = new TextField(5);
p.add(insideField);
outsideLabel = new Label("Outside:");
p.add(outsideLabel);
outsideField = new TextField(5);
p.add(outsideField);
placement of elements around
the borders of the applet
screen
a Panel can contain
numerous elements
add(p, BorderLayout.SOUTH);
}
. . .
}
<applet code="Monte5.class" height=300 width=300>
<param name="points" value=20000>
</applet>
view page in browser
Event handling
in order to handle events (e.g., text changes, button clicks), can use the
event delegation model
 must specify that the class implements the ActionListener interface
public class Monte6 extends Applet implements ActionListener
 each source of events must be registered within the applet
dotButton = new Button("Click to generate dots");
dotButton.addActionListener();
 must have an actionPerformed method to handle events
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == dotButton) {
drawDots();
}
}
ActionListener
import
import
import
import
java.awt.*;
java.applet.*;
java.awt.event.*;
java.util.Random;
public void drawCircle()
{
CODE FOR DRAWING CIRCLE
}
public class Monte6 extends Applet
implements ActionListener
{
. . .
private Button dotButton;
public void drawDots()
{
drawCircle();
Graphics g = getGraphics();
for (int i = 0; i < NUM_POINTS; i++) {
CODE FOR DRAWING DOTS
}
public void init()
{
randy = new Random();
NUM_POINTS =
Integer.parseInt(getParameter("points"));
Dimension dim = getSize();
SIZE = dim.width;
}
public void paint(Graphics g)
{
g.drawImage(offScreenImage, 0, 0, null);
}
setLayout(new BorderLayout());
dotButton =
new Button("Click to generate dots");
dotButton.addActionListener(this);
add(dotButton, BorderLayout.SOUTH);
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == dotButton) {
drawDots();
}
}
drawCircle();
}
}
<applet code="Monte6.class" height=300 width=300>
<param name="points" value=20000>
</applet>
view page in browser
Applet examples
The Java Boutique has lots of sample applets with source code
 Graphing Calculator
 Mandlebrot Set
 Email front-end
 Web search front-end
 Java Tetris
Combining Java & JavaScript
 integrating Java with JavaScript
 calling Java routines from JavaScript
 controlling an applet from JavaScript
 accessing JavaScript & HTML elements from an applet
 related topics
 JavaBeans, Java archives (JARs)
JavaScript vs. Java
recall: JavaScript is very good for simple tasks, GUI layout
 flexible data typing, primitive object types fine for quick development
 integration with HTML makes layout & control of GUI elements easy
 not much library support, only primitive data structuring capabilities
 not well-suited to multi-file projects, OO approach
recall: Java is better at complex tasks, especially graphics
 full-featured, more robust, extensive libraries of classes/routines
 can support large projects, interacting objects
 GUI layout is difficult, integration with HTML not obvious
IDEAL: make use of the the strengths of each language
 include applets in a page when needed (e.g., graphics)
 allow communication between applet & JavaScript code
Calling Java routines from JavaScript
Netscape Communicator allows direct calls to Java routines
 specify full package name of routine, then call as in Java
useful for more esoteric routines that are not supported directly in JavaScript
 this feature is NOT supported by Internet Explorer
<html>
<!-- Note: works in Netscape only.
-->
<head>
<title>Java+JavaScript Demo</title>
</head>
<body>
<script language="JavaScript">
document.write(java.lang.Math.random());
</script>
</body>
</html>
Calling applet methods
more commonly, want to include an applet in a page,
control via HTML events & JavaScript
 want to draw dots inside a square (with an inscribed circle)
 could build GUI interface into applet, but required tricky layout manager
 instead, leave graphics up to the applet, controlled via JavaScript
to call a Java applet method from JavaScript
document.appletName.methodCall(…)
import java.awt.*;
import java.applet.*;
import java.util.Random;
public class Monte7 extends Applet
{
private static Random randy;
private int SIZE;
private Image offScreenImage;
private Graphics offScreenGraphics;
private int randomInRange(int low, int high) {…}
private double distance(int x1, int y1, int x2, int y2) {…}
public void init()
{
randy = new Random();
Dimension dim = getSize();
SIZE = dim.width;
drawCircle();
}
public void drawCircle() {
// DRAWS CIRCLE ON BOTH getGraphics() AND
// offScreenGraphics
MontePI revisited
init creates the
random number
generator & gets
applet size
drawDots draws
the dots on the
screen and to the
off-screen buffer
}
public void drawDots(int numPoints)
{
// DRAWS numPoints RANDOM DOTS ON BOTH getGraphics()
// AND offScreenGraphics
}
public void paint(Graphics g)
{
g.drawImage(offScreenImage, 0, 0, null);
}
}
paint redraws the
screen using the
buffer
MontePI example (cont.)
<html>
<!-- Monte7.html -->
<head>
<title>Monte Carlo Darts Page</title>
</head>
<body bgcolor="gray">
<div style="text-align:center">
<applet code="Monte7.class" name="MonteApplet"
height=300 width=300>
You must use a Java-enabled browser to view this applet.
</applet>
<br /><br />
<form name="MonteForm">
<input type="button" value="Generate points"
onClick="document.MonteApplet.drawDots(1000);">
</form>
</div>
</body>
</html>
view page in browser
here, HTML button
controls the applet
(via JavaScript)
Example (cont.)
better interface:
<html>
<!-- Monte7a.html
-->
<head>
<title>Monte Carlo Darts Page</title>
</head>
<body bgcolor="gray">
<div style="text-align:center">
<applet code="Monte7.class" name="MonteApplet"
height=300 width=300>
You must use a Java-enabled browser to view this applet.
</applet>
<br /><br />
allow user to specify
number of dots in text
box
each click adds new
dots, have separate
button to clear
<form name="MonteForm">
<input type="button" value="Generate"
onClick="numDots = parseFloat(document.MonteForm.numPoints.value);
document.MonteApplet.drawDots(numDots);">
<input type="text" name="numPoints" size=6 value=100> points
<br /><br />
<input type="button" value="Clear the screen"
onClick="document.MonteApplet.drawCircle();">
</form>
</div>
</body>
</html>
view page in browser
Dividing control
where the control lies affects the efficiency/usability of an applet


want the applet to be as self-contained as possible,
take advantage of speed advantage, more advanced features
but if GUI controls are in HTML, then JavaScript needs overall control
consider adding counters for number of dots inside & outside circle

have the applet keep track of the dots in instance variables
1. after drawing all dots, JavaScript could access counts & display
 can’t see counts in progress (in Netscape)
2. could have applet update the HTML text boxes itself
 tricky (example later)
3. could return more control to the page, applet draws one dot at a time
repetition is handled by JavaScript, can update boxes after each dot
 slower, but more flexible
JavaScript in control
import java.awt.*;
import java.applet.*;
import java.util.Random;
public class Monte8 extends Applet
{
. . .
public int numInside, numOutside;
. . .
public void clear()
{
numInside = 0; numOutside = 0;
. . .
}
public void drawDot()
{
. . .
if (distance(x, y, SIZE/2, SIZE/2) < SIZE/2) {
offScreenGraphics.setColor(Color.white);
g.setColor(Color.white);
numInside++;
}
else {
offScreenGraphics.setColor(Color.black);
g.setColor(Color.black);
numOutside++;
}
. . .
}
. . .
}
change applet so that
method only draws a
single dot (repetition to be
controlled by JavaScript)
have applet keep track of
number inside & out
(can access & display with
JavaScript)
<html>
<!-- Monte8.html
-->
Example (cont.)
<head>
<title>Monte Carlo Darts Page</title>
<script type="text/javascript">
function doAll()
{
var numDots = parseFloat(document.MonteForm.numPoints.value);
for (var i = 0; i < numDots; i++) {
document.MonteApplet.drawDot();
}
document.MonteForm.numIn.value = document.MonteApplet.numInside;
document.MonteForm.numOut.value = document.MonteApplet.numOutside;
}
function clearAll()
{
document.MonteApplet.drawCircle();
document.MonteForm.numIn.value = 0;
document.MonteForm.numOut.value = 0;
}
</script>
</head>
Note: can utilize
HTML table to
achieve desired
layout of elements
<body bgcolor="gray">
<form name="MonteForm">
<table align="center">
<tr><td><applet code="Monte8.class" name="MonteApplet" height=300 width=300>
You must use a Java-enabled browser to view this applet.
</applet>
<td><input type="button" value="Generate" onClick="doAll();">
<input type="text" name="numPoints" size=6 value=100> points
<p><hr>
<p><input type="text" name="numIn" size=6 value=0> points inside
<p><INPUT TYPE="text" name="numOut" size=6 value=0> points outside
<p><hr>
<p><input type="button" value="Clear the screen" onClick="clearAll()">
</table>
</form>
</body>
view page
</html>
in browser
Accessing HTML/JavaScript from the applet
it is possible for the applet to access elements in the page
 requires the JSObject class from the netscape.javascript package
import netscape.javascript.JSObject;
 use getWindow and getMember methods to access components
JSObject jsWin = JSObject.getWindow(this);
JSObject jsDoc = (JSObject) jsWin.getMember("document");
// GETS WINDOW
// GETS DOCUMENT
JSObject MonteForm = (JSObject) jsDoc.getMember("MonteForm");
numInside = (JSObject) MonteForm.getMember("numIn");
// GETS FORM
// GETS TEXT BOX
 use getMember and setMember methods to access component attributes
int num = Integer.parseInt( (String)numInside.getMember("value") );
numInside.setMember("value", ""+(num+1));
Related topics
JavaBeans
 reusable components (e.g., buttons, menus) that can be packaged and reused
 requires special tools for compiling and packaging (e.g., BDK)
 downloaded with an applet using the ARCHIVES attribute
<applet code="javaApp.class" archives="jarfile.jar">
JAR files
 for applets that are comprised of multiple classes, can bundle all necessary files into
a Java Archive (JAR) file
 uses the popular ZIP file format
 download using ARCHIVES attribute, automatically unzipped by browser
End of Java Applets