Chapter 5 - Java Applets
Applets vs. Applications
The Java language can be used to create applets that are small programs embedded in HTML pages or full fledge applications that run on their own. All the examples provided thus far have been Java applets which this book concentrates on but it is worth while to give you a glimpse of the differences between them and Java applications.
As you have seen, applets extend the provided applet class. You write classes that add onto the applet class and modify its behavior. Applications stand on their own but the code is very similar. Instead of extending an existing class, you write a main method that is executed on start up and which calls other classes and functions (much like C or C++).
public static void main (String arguments[]) { }The arguments array is the arguments that are passed to the Java application on the command line. Macintosh computers do not have a command line interface so you are unable to pass along command line arguments. This means the arguments array will always be empty. To get values from a user you should prompt the user with a dialog that allows them to input values into your program.
Applets have restrictions placed on them for security reasons. They cannot read or write files on the users machine without the explicit consent of that user. Similarly, applets cannot call or run any programs on the users machine. Applets can only communicate with the server that it originated from (unless overridden by the user). Java, in general, also has many security and checking features that make sure nothing inappropriate is done on the users machine which make it unlikely that anything harmful could be distributed.
Applet anatomy and behavior
Applets extend on the existing applet class which contains methods for various events and actions that occur during the life of an applet. To provide functionality, your code should override the appropriate methods and create the behavior you wish. There are six important methods that you will frequently want to override.
The init() method runs when the applet is first loaded onto the page. This is the common method that provides things you wish to happen once at the very beginning of your applet such as object creation, variable definitions, or loading media. The init class is also called when the applet is reloaded on the page.
public void init() { }The start() method is called directly after the init() method, but unlike the init() method it can be called more than once. For instance when a user leaves the page (by following a link) the applet is stopped. If that user returned to the page containing your applet, the start() method would be called again. Common actions inside the start() method are messages to other objects and thread starting.
public void start() { }The paint() method does the drawing in the window for your applet and, unlike the other provided methods, it contains an argument from the Graphics class. This object is created and passed automatically by the encompassing browser so you do not need to anything for it to work. You just need to remember to import the Graphics class at the beginning of your applet. Painting may occur as many times as needed during the applets life. It happens after the initialization, if the window has been hidden then brought to the front, or if the browser window is moved.
import java.awt.Graphics; public void paint(Graphics g) { }The update() method is run every time the repaint() method is called. The default action is to clear the screen and then call the paint() method which can often cause flickering in applets. Often you will override update() to help reduce flickering and update certain variables. Again, this method has one argument from the Graphics class that is automatically created and passed by the browser.
import java.awt.Graphics; public void update(Graphics g) { }The stop() method is called when the user exits the page that contained the applet. The default action of stop() actually lets the applet continue to run which you may want to change by overriding this method.
public void stop() { }The destroy() method is called to release any resources the applet was using. Usually you will only want to override this class if there are threads that you wish to dispose of when the browser exits or the applet is reloaded.
public void destroy() { }There are other commonly used methods that you will want to override and provide functionality for your applet. For example you will override methods such as mouseDown(Event e, int x, int y), mouseDrag(Event e, int x, int y), or keyDown(Event e, int key) to capture and act upon user actions and events.
The
HTML tag The
tag allows you to include Java applets in your HTML web pages and serve them to other people on the internet. It is an extension to the HTML language and will simply be ignored by browsers that do not support it. <applet code="ArrayDemo2.class" height=100 width=300> Text for browsers that do not support the applet tag goes here. </applet>The minimal applet tag must include the name of the Java class file you wish to include and its dimensions. The code attribute assumes the class file is in the same directory as the HTML file. If you place the class file in a subdirectory you need to also use the codebase attribute which specifies the path separated by /'s. In the example below the ArrayDemo2 class file is in a folder called arrays which is in a folder called classfolder.
The height and width attributes tell the browser how much space to allocate to the applet in pixels on the HTML page (standard displays have about 72 pixels per inch). If you applet is larger than the specified values it will be clipped and only partially visible. Remember that you specify the size of your applet in Java using the resize method during the initialization process.
The text or HTML that appears between the <applet...> and </applet> tags is only displayed by browsers who do not support Java and the applet tags. It is a good idea to include some content here so that people who view your pages without a Java-capable browser will see more than just a blank space. For instance, if you have a Java animation applet you should include an image from the animation for people who cannot view the actual Java animation.
<applet code="ArrayDemo2.class" codebase="classfolder/arrays" align="right" height=100 width=300 hspace=10 vspace=10 name="applet2"> <param name="x" value=10> <param name="y" value=15> Text for browsers that do not support the applet tag goes here. </applet>The align attribute accepts nine values that allow you to position the applet more effectively on the HTML page (much like the <img> tag). The first two allow text to flow around the applet while the following seven are useful in including small applets in a line of text.
left placed at left margin with text flow on right right placed at right margin with text flow on left texttop top of applet is aligned with top of text top top of applet is aligned with top of tallest element in that line absmiddle middle of applet is aligned with middle of tallest element in that line middle middle of applet is aligned with middle of baseline text baseline aligns bottom of the applet with the bottom of the baseline text bottom aligns bottom of applet with bottom of that line absbottom aligns the bottom of the applet with the bottom of the lowest element in that lineThe values of bottom and baseline produce the same results. The difference between top and texttop is that top will align it with the tallest element which could be text or something else, like an image or another applet.
The hspace and vspace attributes allow you to create margins around the applet in pixels when it is displayed on the page. This is often helpful because you may not want text or other objects to run up against the applet and make it hard to view.
The name attribute lets you distinguish between applets if you have more than one included in an HTML page. This is useful when you want the applets to be able to communicate with each other. If you do not need interapplet communication but just want multiple copies of an applet to occur just copy and paste the <applet..> tag.
Finally, the <param...> tags allow you to pass arguments and values to your applet from within the HTML page. Each parameter is given a name and a value. These values can be retrieved by your Java applet by calling the getParameter("name") method with the name of the parameter you wish to get.
String colorName = getParameter("color"); String numberText = getParameter("number"); int numberInt = Integer.parseInt(numberText); String cityName = getParameter("city"); if (city == null) city = "Los Angeles";It is important to remember that only strings can be passed to the applet in this manner so integers, and other types, must be converted before use. Also, if you fail to give the parameter a value in the HTML page and you call getParameter() in your Java applet, a null (empty) value will be passed by the method. This means you should check for this condition and possibly supply a default value.
Simple applet example
The applet tag allows you to pass arguments and values to your applets when you embed them into your page by using the <param...> tag. This means you do not need to code for different situations or values. You can just read those parameters in and then act on them which allows to create just one applet.
import java.applet.*; import java.awt.Graphics; public class AdditionDemo extends Applet { int x; int y; int answer; public void init() { resize(80, 30); String xText = getParameter("xvalue"); x = Integer.parseInt(xText); String yText = getParameter("yvalue"); y = Integer.parseInt(yText); answer = x * y; } public void paint(Graphics g) { String answerText = java.lang.Integer.toString(answer); g.drawString("x * y = " + answerText, 10, 10); } }This applet is just a simple demonstration of addition. The difference here is that the applet does not know the values of x and y until it is called by the applet tag and passed these values. Therefore I do not need to code for different applet with different values.
<applet code=AdditionDemo height=30 width=80> <param name="xvalue" value=10> <param name="yvalue" value=16> </applet> <applet code=AdditionDemo height=30 width=80> <param name="xvalue" value=4> <param name="yvalue" value=19> </applet> <applet code=AdditionDemo height=30 width=80> <param name="xvalue" value=22> <param name="yvalue" value=3> </applet> <applet code=AdditionDemo height=30 width=80> <param name="xvalue" value=13> <param name="yvalue" value=17> </applet>This HTML code in the web page calls the same applet four times but with different values of x and y each time. Thus I have created a general integer addition applet.
Provided classes and libraries
Distributed with the Java development kit is a set of predefined classes and libraries that perform various functions for your applet without requiring you to provide the code. You simply need to call the method with the correct arguments and the action is done for you. This is one aspect that makes most applets a simple chore in Java.
You have seen many examples of this already in the Apple Flavored Java Tutorial. For instance, the methods start(). stop(), destroy(), init(), paint(), and update() are predefined and only if you want to change their behavior do you need to override them.
Java also provides classes for playing audio files, displaying graphics, communicating over a network, creating a user interface, and more. A detailed list of the classes that are a part of the Java API is included with the Sun Java developers kit.