Building A Java Applet
Building A Java Applet
Building A Java Applet
Table of Contents
If you're viewing this document online, you can click any of the topics below to link directly to that section.
1. Tutorial tips 2. Java, development, and applets 3. Loading and displaying images 4. Exceptions and MediaTracker class 5. Offscreen image buffering 6. Image rotation algorithm using copyArea 7. Threading and animation 8. Graphic output methods and applet parameters 9. Wrapup
2 3 9 13 15 18 20 24 27
Page 1
ibm.com/developerWorks
Navigation
Navigating through the tutorial is easy: * * * Select Next and Previous to move forward and backward through the tutorial. When you're finished with a section, select the next section. You can also use the Main and Section Menus to navigate the tutorial. If you'd like to tell us what you think, or if you have a question for the author about the content of the tutorial, use the Feedback button.
Page 2
ibm.com/developerWorks
Anatomy of a 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 below shows help as an instance of class Button.
Page 3
ibm.com/developerWorks
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 */
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. Static variables are not associated with objects and the classes they are defined in cannot be instantiated.
An object (referred to by a variable) is marked for garbage collection when there are no references to it.
Page 4
ibm.com/developerWorks
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.
If no object is specified, the current object (this) is assumed, for example, f() implies this.f().
Page 5
ibm.com/developerWorks
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.
Displaying applets
An applet is a Java program that is referenced by a Web page and runs inside a Java-enabled 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>
Page 6
ibm.com/developerWorks
The init() method is run only when the applet first starts; start() is executed when the applet is displayed or refreshed. 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.
Page 7
ibm.com/developerWorks
4. 5.
Page 8
ibm.com/developerWorks
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.
Page 9
ibm.com/developerWorks
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.
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);
Page 10
ibm.com/developerWorks
Page 11
ibm.com/developerWorks
4. 5. 6. 7. 8.
Page 12
ibm.com/developerWorks
Exceptions
Run-time errors are called exceptions and are handled using try-catch:
int i, j; i = 0; try { j = 3/i; System.out.println("j=" +j); } catch (ArithmeticException e) { // handler e.printStackTrace(); System.out,println("Exception ' " + e + " 'raised - i must be zero"); }
At run time, this code will display and trace the message:
"Exception 'java.lang.Arithmetic: / by zero' raised - i must be zero"
Page 13
ibm.com/developerWorks
8.
Page 14
ibm.com/developerWorks
Page 15
ibm.com/developerWorks
Pre-render graphics into an offscreen image buffer and just draw it later as one operation:
// Set up the off-screen image (buf) for // double-buffering buf = createImage (100,100); Graphics bufg = buf.getGraphics( ); // Draw into the off-screen buffer for (int i = 0; i < 50; i += 5) { bufg.setColor(i % 10 == 0 ? Color.black : Color.white); bufg.fillRect(i, i, 100 -i * 2, 100 - i * 2) ; }
Page 16
ibm.com/developerWorks
2.
3.
4.
5.
6. 7. 8. 9.
Page 17
ibm.com/developerWorks
Page 18
ibm.com/developerWorks
Page 19
ibm.com/developerWorks
A process can have many threads. A thread embodies only the state (management) of an activity (aka lightweight processes). An activity is a sequence of operations (thread of control or flow of communication).
Page 20
ibm.com/developerWorks
Roles as interfaces
An interface encapsulates a coherent set of services and constants, for example, a role.
An object, in order to participate in various relationships, needs to state that it fulfills a particular role with the implements keyword.
public class X implements Runnable { ... }
All methods inherited from an interface must be implemented (or redeclared as abstract). The implementation does not necessarily have to have any body code.
public void run( ) { ... }
A class can both extend one class and implement one or more interfaces.
Page 21
ibm.com/developerWorks
An applet as runnable
Many times an applet will have one additional (usually continuous) activity, for example, an animation loop. In such cases it is quite likely the class will both extend Applet and implement Runnable:
class ImgJump extends Applet implements Runnable { private Thread t; // ...
Basic animation
Animation is the display of a series of pictures over time to give the illusion of motion. A basic computer animation loop consists of: * * * Advancing to the next picture (in an offscreen buffer) Updating the screen by repainting it Delaying for some period of time (typically 1/24 of a second for film or 1/30 of a second for video)
For example:
public void run( ) { while (true) { advance( ); // advance to the next frame repaint( ); // repaint the screen try { Thread.sleep(33); } // delay catch(InterruptedException e) { } } }
Page 22
ibm.com/developerWorks
Page 23
ibm.com/developerWorks
Page 24
ibm.com/developerWorks
String class
Strings are objects, defined using the Unicode 1.1.5 character set (16-bit international character set). Strings are constructed from literals, char arrays, and byte arrays. They are bounds checked with a length() method.
String s1 = "Testing"; int l = s1.length( )
Concatenation operations:
String s2 = s1 + " 1 "; s2 += "2 3";
Comparison operations:
if (s1 == s2) // Object reference check if (s1.equals(s2) ) // Contents check
Note, when you are comparing values, you should use the .equals() method.
An applet (in the init method) can access each PARAM tag by using the getParameter method. Specifying the NAME string returns the VALUE STRING. If the NAME string is not found, null is returned:
String imgName = getParameter("image"); if (imgName == null) ... // set default else ... // decode or convert
Page 25
ibm.com/developerWorks
3.
4. 5.
6. 7.
Page 26
ibm.com/developerWorks
Resources
Here are some other tutorials for you to try: * * Introduction to the Java Foundation Classes Java language essentials
This article provides a scenario for using Java applets in an educational setting: * A Walk in the Park
Your feedback
Please let us know whether this tutorial was helpful to you and how we could make it better. We'd also like to hear about other tutorial topics you'd like to see covered. Thanks!
Colophon
This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorial generator. The Toot-O-Matic tool is a short Java program that uses XSLT stylesheets to convert the XML source into a number of HTML pages, a zip file, JPEG heading graphics, and PDF files. Our ability to generate multiple text and binary formats from a single source file illustrates the power and flexibility of XML.
Page 27