Professional Documents
Culture Documents
Lecture 12
Lecture 12
Lecture 12
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
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
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)
/**
* 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
}
}
/**
* 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
}
}
▪ 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>
view page in
</body> browser
</html>
HTML & applets
<html>
<!-- Hello2.html -->
an applet can be
<head>
<title>Hello World Page</title>
embedded within HTML
</head> elements just like any
<body> other element
<p>
<div align="center">
<table border=1>
<tr><td>
useful for formatting and
<applet code="HelloWorld.class" height=200 width=200>
You must use a Java-enabled browser to view this applet.
layout
</applet>
</td></tr>
</table>
</div>
</p>
</body>
</html>
<p>
<div align="center"> • each parameter must
<table border=1> have its own PARAM tag
<tr><td>
inside the APPLET
<applet code="HelloWorld1.class" height=35 width=300> element
<param name="name" value="Chris">
<param name="age" value=20>
You must use a Java-enabled browser to view this applet.
</applet> • specifies parameter
</td></tr>
name and value
</table>
</div>
</p>
</body>
</html>
/**
* 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"));
▪ by defining data structures that contain Objects, any reference type can be stored
(and even mixed)
Stack things = new Stack();
/**
* This class displays lots of "Hello world!"s on the applet window.
*/
public class HelloWorld1 extends Applet
{ Random class provides
private static final int NUM_WORDS=100;
private static Random randy; methods for generating
private int randomInRange(int low, int high) random values
{
return (Math.abs(randy.nextInt()) % (high-low+1)) + low;
}
▪ the paint method is called immediately after init, and whenever the applet needs to
be redrawn (e.g., after window resized or obscured)
recall:
▪ can specify parameters in the HTML document using <PARAM> tags
▪ access the parameter values (based on name) using getParameter method
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
Graphical applet
{
private static Random randy;
private int NUM_POINTS;
private int SIZE;
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
Buffered applet
{
. . .
private Image offScreenImage;
private Graphics offScreenGraphics;
. . .
public void init()
{
init method is called when
randy = new Random(); page is loaded
NUM_POINTS = Integer.parseInt(getParameter("points"));
Dimension dim = getSize();
SIZE = Math.min(dim.width, dim.height);
does drawing to a separate,
offScreenImage = createImage(SIZE, SIZE);
offScreenGraphics = offScreenImage.getGraphics();
off-screen Graphics object
offScreenGraphics.setColor(Color.red);
offScreenGraphics.fillOval(0, 0, SIZE, SIZE);
for (int i = 0; i < NUM_POINTS; i++) {
paint is called after
init
int x = RandomInRange(0, SIZE); and whenever the applet is
int y = RandomInRange(0, SIZE);
if (distance(x, y, SIZE/2, SIZE/2) < SIZE/2) {
revisited
offScreenGraphics.setColor(Color.white);
}
else { Note: don’t see image in
offScreenGraphics.setColor(Color.black);
} progress
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
}
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);
if want to see image as it is
} drawn, must be done in
public void paint(Graphics g) { paint
if (offScreenImage == null) {
offScreenImage = createImage(SIZE, SIZE);
offScreenGraphics = offScreenImage.getGraphics();
}
g.setColor(Color.white);
on subsequent repaints,
else {
offScreenGraphics.setColor(Color.black);
simply redraw the contents of
}
g.setColor(Color.black); the off-screen buffer
offScreenGraphics.drawLine(x, y, x, y);
g.drawLine(x, y, x, y);
}
}
else { <applet code="Monte3.class" height=300 width=300>
g.drawImage(offScreenImage, 0, 0, null); <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, …
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
{ public void paint(Graphics g)
. . . {
private Label insideLabel; . . .
private TextField insideField;
private Label outsideLabel; insideField.setText("0");
private TextField outsideField; outsideField.setText("0");
. . .
. . .
public void init()
{ if (distance(x, y, SIZE/2, SIZE/2) < SIZE/2) {
randy = new Random(); g.setColor(Color.white);
NUM_POINTS = int value =
Integer.parseInt(getParameter("points")); Integer.parseInt(insideField.getText())+1;
Dimension dim = getSize(); insideField.setText(""+value);
SIZE = Math.min(dim.width, dim.height); }
else {
insideLabel = new Label("Inside:"); g.setColor(Color.black);
add(insideLabel); int value =
insideField = new TextField(6); Integer.parseInt(outsideField.getText())+1;
add(insideField); outsideField.setText(""+value);
}
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>
The Java Boutique has lots of sample applets with source code
▪ Graphing Calculator
▪ Mandlebrot Set
▪ Email front-end
▪ Java Tetris
Combining Java & JavaScript
▪ 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
<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
document.appletName.methodCall(…)
import java.awt.*;
import java.applet.*;
import java.util.Random; MontePI revisited
public class Monte7 extends Applet
{ init creates the
private static Random randy;
private int SIZE;
private Image offScreenImage;
random number
private Graphics offScreenGraphics;
generator & gets
private int randomInRange(int low, int high) {…}
private double distance(int x1, int y1, int x2, int y2) {…} applet size
public void init()
{
randy = new Random();
Dimension dim = getSize();
SIZE = dim.width;
drawDots draws
}
drawCircle();
the dots on the
public void drawCircle() { screen and to the
// DRAWS CIRCLE ON BOTH getGraphics() AND
// offScreenGraphics off-screen buffer
}
<form name="MonteForm">
<input type="button" value="Generate points"
onClick="document.MonteApplet.drawDots(1000);">
</form>
</div>
</body>
</html>
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)
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;
change applet so that
public class Monte8 extends Applet
{
. . .
method only draws a
public int numInside, numOutside; single dot (repetition to be
. . . controlled by JavaScript)
public void clear()
{
numInside = 0; numOutside = 0;
. . .
} have applet keep track of
public void drawDot()
{
number inside & out
. . .
if (distance(x, y, SIZE/2, SIZE/2) < SIZE/2) {
(can access & display with
offScreenGraphics.setColor(Color.white); JavaScript)
g.setColor(Color.white);
numInside++;
}
else {
offScreenGraphics.setColor(Color.black);
g.setColor(Color.black);
numOutside++;
}
. . .
}
. . .
}
<html>
Example (cont.)
<!-- Monte8.html -->
<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()
{ Note: can utilize
document.MonteApplet.drawCircle();
document.MonteForm.numIn.value = 0; HTML table to
document.MonteForm.numOut.value = 0;
}
</script>
achieve desired
</head>
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>
</html> view page 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;
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
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