Download Week 10 lecture notes

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
Client Side Programming Using
Java Applet
• Outcomes:
You will be expected to know:
– Java Applets and HTML file;
– bytecode and platform independent programs;
– Java basics and java applet basics.
– Java applet events and graphics
programming.
Java basics, development, and
applets
•
Introduction
First section of today’s lecture describes the Java
language, the development process, and what an
applet is. After completing this section, you should
be able to:
1.
2.
3.
4.
What is Java? What are Java application and Java Applet?
Describe the syntax of a Java class
Code a simple Java source file
Understand the basic structure of an applet and how it
interacts with a Web browser
5. Code a simple Java applet source file
6. Write output to the system console
7. Code HTML to invoke an applet
What is Java?
• What is Java?
– The Java language and companion class libraries
provide a portable, interpreted, high-performance,
simple, object-oriented, development environment.
– There are two types of Java programs: applets and
applications.
• Applets are Java programs that are usually embedded in an
HTML Web page and downloaded from the Web to be run by
a browser on the user’s computer system.
• Applications are full-fledged programs written in Java. They
don’t require a Web browser to run, but they do require the
Java VM to be installed on the target platform.
• The Java Virtual Machine
– The high-level programming language such as C, C++,
Pascal must first be translated into an executable
machine-language program.
– Normally, there are two ways for translation:
• Using a complier to translate at once, in this case the compiled
program can only run on one type of computer with same type
of OS. (Such as C, C++, Pascal)
• Using a interpreter to translate instruction-by-instruction. (Such
as Basic, Perl)
– The designer of Java chose to use a combination of
compilation and interpretation.
• Programs written in Java are compiled into machine language,
but it is a machine language for a computer that doesn’t really
exist. This so-called “virtual” computer is known as the Java
virtual machine . The machine language for the Java VM is
called Java bytecode.
• A different Jave bytecode interpreter is needed for each
type of computer, but once a computer has a Java
bytecode interpreter, it can run any Java bytecode
program. And the same Java bytecode program can be
run on any computer that has such an interpreter. This is
one of the essential features of Java: the same compiled
program can be run on many different types of
computers.
Anatomy of a Java class
Any Java source file (.java) has this
physical structure:
import statements;
class definition {
instance variable definitions;
method definition (argumentList) {
local variable definitions
statements;
} // end of method definition
// more methods ...
} // end of class definition
A class is used to instantiate specific
objects (each with possibly different
values) in the heap. For example, the
figure right shows help as an instance of
class Button.
Primitive and object variables
• Variables are represented on the stack
as either:
– A built-in primitive type (byte, short, int,
long, char, float, double, or boolean) that
uses value semantics
int i = 42; /* i holds value (42) */
– An object type (extended from
java.lang.Object) that uses reference
semantics (like a pointer)
Button helpButton = new Button("Help");
/* helpButton is an object ref */
Primitive Data Types
Lifetime of a variable
A variable has a storage class, which sets its
lifetime.
– Local variables are local to a block of code, that is,
allocated at entry to a block and discarded at exit. (A
block of code can be either a class or a method.)
– Instance variables are local to an object, that is,
allocated when an object is instantiated and
discarded when it is garbage-collected.
– Class (static) variables are local to a class, that is,
allocated when a class is loaded and discarded when
it is unloaded.
An object (referred to by a variable) is marked for
garbage collection when there are no references to it.
C-like Java
Most of the C programming language statements are present in the Java
language:
float sqrt(float value) {
/* compute a square root badly! */
float guess;
int loops;
if (value <= 0)
return 0;
else
guess = value/2;
for (loops = 0; loops < 5; loops++) {
guess = (guess + value /guess) /2;
}
return guess;
}
As well as if/else, for, and return, the Java language has C's while,
do/while, and switch/case/default statements.
Messages and object
communication
• Objects use messages to communicate.
• Valid messages are represented by a public
interface.
• Messages in Java correspond to method calls
(invocations) in C.
• Messages must have a reference to the target
object to send a message.
/* Send help button a msg */
helpButton.setEnabled(false);
• If no object is specified, the current object (this)
is assumed, for example, f() implies this.f().
Java development process
• The javac command compiles
Java source code (.java) into
bytecode (.class). Syntax:
Javac YourJavaProgram.Java
• These bytecodes are loaded and
executed in the Java virtual
machine (JVM), which is
embeddable within other
environments, such as Web
browsers and operating
systems. Syntax:
Java YourJavaProgram(.class)
“Hello world” Java application
program(HelloWorlApp.java)
/**
* The HelloWorldApp class implements an application that
simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); //Display the string.
}
}
This program has three part:
1.
2.
3.
The enclosing class definition-In this case, it’s named HelloWorldApp
The body of the program, the main() method – for this application.
The main() method is the subroutine that is executed when this
application is run
The code that produces the actual output of the program.
Displaying applets
• An applet is a Java program
that is referenced by a Web
page and runs inside a Javaenabled Web browser.
• An applet begins execution
when an HTML page that
"contains" it is loaded.
• Either a Java-enabled Web
browser or the appletviewer is
required to run an applet.
• The browser detects an applet
by processing an Applet HTML
tag, for example:
<APPLET CODE=ImgJump
WIDTH=300 HEIGHT=200>
</APPLET>
Web browser-to-applet interface
This figure shows the browser-to-applet interface.
Structure of a simple applet
•
By inheriting from java.applet.Applet, the necessary structure is defined to
coordinate with a Web browser. Extends is the keyword in the Java language used
to inherit classes.
public class MyApplet extends java.applet.Applet {
public MyApplet( ) { //create applet
System.out.println("In ctor");
}
public void init( ) { // initialize
System.out.println("In init");
}
public void start( ) { // display page
System.out.println("In start");
}
public void stop( ) { // leave page
System.out.println("In stop");
}
public void destroy( ) {// clean up
System.out.println("In destroy");
}
}
•
Note that standard out (or output for the println command) is sent to the console
window if you are running within a browser or to a DOS window if you are running
your applet from appletviewer via a DOS window.
The applet methods
• The init() method is run only when the applet first starts.
• start() is executed when the applet is displayed or
refreshed.
• destroy() method will Dispose of any behind the scenes
resources this entire Applet is using (e.g. inside the
native GUI). This does not delete the current application
object, but it does dispose of all the children. This is
required because the Java garbage collection scheme
only can work on its own objects, not those inside the
native GUI.
• stop() method will temporarily shut down your Applet
The “Hello World” applet example
•
HelloWorld.java:
Import java.applet.Applet;
Import java.awt.Graphics;
Public class HelloWorld extends Applet{
public void paint(Graphics g){
g.DrawString(“Hello world!”,
50,25);
}
}
•
Hello.html:
<html><head>
<title> A Simple Program <title>
</head>
<body>
Here is the output of my program:
<applet code=“HelloWorld.class” width=150
height=25>
</applet>
</body></html>
Java applet basics, loading &
displaying images
After the second section of today’s lecture, you
should be able to :
–
–
–
–
–
–
–
–
–
Use the applet tag and applet parameters
Describe what a Java package is
Import a package containing additional Java types
Describe what the paint method do
Understand the function of Graphics class
Declare a reference to an image object
Load an image in an applet
Code a paint method
Draw an image into a Graphics object
The Applet tag and Applet
Parameters
• The <APPLET> tag is used to add a Java applet
to a Web page
<APPLET CODE="HelloWorldApplet.class" HEIGHT=50
WIDTH=150> </APPLET>
• Applets use applet parameters to customize
their behaviour. Applet parameters are specified
by using <PARAM> tags, which can only occur
between an <APPLET> tag and the closing
</APPLET>. The PARAM tag has required
modifiers named NAME and VALUE, and it
takes the form
<PARAM NAME="param-name" VALUE="param-value">
An example of an Applet tag with
PARAMs
<APPLET code="ShowMessage.class" WIDTH=200 HEIGHT=50> <PARAM
NAME="message" VALUE="Goodbye World!">
<PARAM NAME="font" VALUE="Serif">
<PARAM NAME="size" VALUE="36">
<p align=center>Sorry, but your browser doesn't support Java!</p>
</APPLET>
String display; // Instance variable: message to be displayed.
String fontName; // Instance variable: font to use for display.
public void init() {
String value;
value = getParameter("message"); // Get message PARAM, if any.
if (value == null) display = "Hello World!"; // default value
else display = value; // Value from PARAM tag.
value = getParameter("font");
if (value == null) fontName = "SansSerif"
else fontName = value;
……………………}
Packages
A package is a named group of classes for a
common domain: java.lang, java.awt, java.util,
java.io. Packages can be imported by other
source files making the names available:
import java.awt.*; // All classes
import java.awt.Image; // One class
Explicit type name: java.awt.Image i1;
Implicit type name: import java.awt.*; Image i2;
The java.lang package is automatically imported
by the compiler.
The java.lang package
The java.lang package contains more than 20 classes,
of which the most useful are System, String, and Math. It
also contains the Thread class, the Runnable interface,
and the various wrapping classes (such as Integer).
1. java.lang.System class provides the standard streams in, out,
and err as public class variables.
2. java.lang.String class contains methods that provide functions
similar to C's strxxx functions, including charAt, compareTo,
concat, endsWith equals, length, replace, startsWith,
subString, toLowerCase, and trim.
3. java.lang.Math class contains a number of mathematical
methods such as abs, sin, cos, atan, max, min, log, random,
and sqrt. It also contains E and PI as class constants (static
final).
Applet class
• The Applet class, defined in the package java.applet, is
really only useful as a basis for making subclasses.
• An object of type Applet has certain basic behaviours,
but doesn't actually do anything useful. It's just a blank
area on the screen that doesn't respond to any events.
To create a useful applet, a programmer must define a
subclass that extends the Applet class.
• There are several methods in the Applet class that are
defined to do nothing at all. The programmer must
override at least some of these methods and give them
something to do.
Paint method
• One of the methods that is defined in the Applet class to do nothing
is the paint() method.
• The paint() method is called by the system when the applet needs to
be drawn. In a subclass of Applet, the paint() method can be
redefined to draw various graphical elements such as rectangles,
lines, and text on the applet. The definition of this method must have
the form:
public void paint(Graphics g) {
// draw some stuff
}
The parameter g, of type Graphics, is provided by the system when
it calls the paint() method. In Java, all drawing of any kind is done
using methods provided by a Graphics object. There are many such
methods and I will introduce them to you soon
Something paint cannot do
• The paint() method of an applet does not
draw GUI components such as buttons
and text input boxes that the applet might
contain. Such GUI components are
objects in their own right, defined by other
classes. All component objects, not just
applets, have paint() methods. Each
component is responsible for drawing
itself, in its own paint() method.
Graphics class
• A Graphics object is usually only obtained as an
argument to update and paint methods:
public void update(Graphics g) {...}
public void paint(Graphics g) {...}
• The Graphics class provides a set of drawing tools that
include methods to draw:
•
•
•
•
•
•
•
rectangles (drawRect, fillRect)
ovals (drawOval, fillOval)
arcs (drawArc, fillArc)
polygons (drawPolygon, fillPolygon)
rounded rectangles (drawRoundRect, fillRoundRect)
strings (drawString)
images (drawImage)
For example:
g.drawImage(i, 0, 0, this);
“Hello World” applet example
import java.awt.*;
import java.applet.*;
public class HelloWorldApplet extends Applet {
// An applet that simply displays the string Hello World!
public void paint(Graphics g) {
g.drawString("Hello World!", 10, 30);
}
} // end of class HelloWorldApplet
Another “Hello World” applet
example
// An applet that says "Hello World" in a big bold font,
// with a button to change the color of the message.
import java.awt.*; // Defines basic classes for GUI programming.
import java.awt.event.*; // Defines classes for working with events.
import java.applet.*; // Defines the applet class.
public class ColoredHelloWorldApplet extends Applet
implements ActionListener {
// Defines a subclass of Applet. The "implements ActionListener"
// part says that objects of type ColoredHelloApplet are
// capable of listening for ActionEvents. This is necessary
// if the applet is to respond to events from the button.
int colorNum; // Keeps track of which color is displayed;
// 1 for red, 2 for blue, 3 for green.
Font textFont; // The font in which the message is displayed.
// A font object represent a certain size and
// style of text drawn on the screen.
public void init() {
// This routine is called by the system to initialize
// the applet. It sets up the font and initial colors
// the applet. It adds a button to the applet for
// changing the message color.
setBackground(Color.lightGray);
// The applet is filled with the background color before
// the paint method is called. The button and the message
// in this applet will appear on a light gray background.
colorNum = 1; // The color of the message is set to red.
textFont = new Font("Serif",Font.BOLD,24);
// Create a font object representing a big, bold font.
Button bttn = new Button("Change Color");
// Create a new button. "ChangeColor" is the text
// displayed on the button.
bttn.addActionListener(this);
// Set up bttn to send an "action event" to this applet
// when the user clicks the button. The parameter, this,
// is a name for the applet object that we are creating. add(bttn);
// Add the button to the applet, so that it
// will appear on the screen.
} // end init()
public void paint(Graphics g) {
// This routine is called by the system whenever the content
// of the applet needs to be drawn or redrawn. It displays
// the message "Hello World" in the proper color and font.
switch (colorNum) { // Set the color.
case 1: g.setColor(Color.red); break;
case 2: g.setColor(Color.blue); break;
case 3: g.setColor(Color.green); break; }
g.setFont(textFont); // Set the font.
g.drawString("Hello World!", 20,70);
// Draw the message.
} // end paint()
public void actionPerformed(ActionEvent evt) {
// This routine is called by the system when the user clicks
// on the button. The response is to change the colorNum
// which determines the color of the message, and to call
// repaint() to see that the applet is redrawn with the
// new color.
if (colorNum == 1) // Change colorNum.
colorNum = 2;
else if (colorNum == 2)
colorNum = 3;
else colorNum = 1;
repaint(); // Tell system that this applet needs to be redrawn
} // end init()
} // end class ColoredHelloWorldApplet
Loading and drawing images
The typical way to load images in Applets is via the getImage()
method.
Image getImage(URL) // Absolute URL
Image getImage(URL, String) // Relative URL
For example:
Image img = getImage(getDocumentBase(), "x.gif");
This example returns a reference to an image object that is being
asynchronously loaded. The getDocumentBase() method returns the
address of the current Web site where the applet is being executed.
The x.gif is the actual image being loaded
After the image is loaded, you would typically render it to the screen
in the Applet's paint method using the Graphics method. For
example:
g.drawImage(img, 0, 0, this); // img is the image that is drawn on the
// screen in the 0, 0 position.
Simple applet that loads and draws
Image
<applet code=ImgLoad width=300 height=200>
</applet>
import java.awt.*;
public class ImgLoad extends java.applet.Applet {
Image i;
public void init() {
System.out.println("In init");
i = getImage(getDocumentBase(), "Test.gif");
}
public void paint(Graphics g) {
System.out.println("In paint");
int x = (int)(Math.random() * size().width);
int y = (int)(Math.random() * size().height);
g.drawImage(i, x, y, this);
}
}