Java Applet Programming
What is Applet? |
What is an Applet?
According to Sun “An applet is a small program that is intended not to be run on its own, but rather to be embedded inside another application….The Applet class provides a standard interface between applets and their environment.”
Four definitions of applet:
- A small application
- A secure program that runs inside a web browser
- A subclass of java.applet.Applet
- An instance of a subclass of java.applet.Applet
public class Applet extends Panel
java.lang.Object
|
+----java.awt.Component
|
+----java.awt.Container
|
+----java.awt.Panel
|
+----java.applet.Applet
Hello World: The Applet
The reason people are excited about Java as more than just another OOP language is because it allows them to write interactive applets on the web. Hello World isn’t a very interactive program, but let’s look at a webbed version.
HelloWorldApplet.java
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25);
}
}
The applet version of HelloWorld is a little more complicated than the HelloWorld application, and it will take a little more effort to run it as well.
First type in the source code and save it into file called HelloWorldApplet.java. Compile this file in the usual way. If all is well a file called HelloWorldApplet.class will be created. Now you need to create an HTML file that will include your applet. The following simple HTML file will do.
HelloWorldApplet.html
<HTML>
<HEAD>
<TITLE> Hello World </TITLE>
</HEAD>
<BODY>
<applet code="HelloWorldApplet.class" width="150" height="50">
</applet>
</BODY>
<HTML>
- Save this file as HelloWorldApplet.html in the same directory as the HelloWorldApplet.class file. When you’ve done that, load the HTML file into a Java enabled browser like Internet Explorer 4.0 or Sun’s applet viewer included with the JDK.
- If the applet compiled without error and produced a HelloWorldApplet.class file, and yet you don’t see the string “Hello World” in your browser chances are that the .class file is in the wrong place. Make sure HelloWorldApplet.class is in the same directory as HelloWorld.html. Also make sure that you’re using a version of Netscape or Internet Explorer which supports Java. Not all versions do.
- In any case Netscape’s Java support is less than the perfect so if you have trouble with an applet, the first thing to try is loading it into Sun’s Applet Viewer instead. If the Applet Viewer has a problem, then chances are pretty good the problem is with the applet and not with the browser.
Applet Tag |
The APPLET Tag
-
Applets are embedded in web pages using the <applet> and </applet> tags. The <applet> tag is similar to the <IMG> tag. Like <IMG> <applet> references a source file that is not part of the HTML page on which it is embedded. IMG elements do this with the SRC attribute. APPLET elements do this with the CODE attribute. The CODE attribute tells the browser where to look for the compiled .class file.
It is relative to the location of the source document.
Thus if you’re browsing http://javaskool.com/java123/index.html and that page references an applet with CODE=”Animation.class”, then the file Animation.class should be at the URL http://javaskool.com/java123/Animation.class. -
For reasons that remain a mystery to HTML authors everywhere if the applet resides somewhere other than the same directory as the page it lives on, you don’t just give a URL to its location. Rather you point at the CODEBASE.
The CODEBASE attribute is a URL that points at the directory where the .class file is. The CODE attribute is the name of the .class file itself. For instance if on the HTML page of the previous section you had written
<applet code="HelloWorldApplet.class" CODEBASE="classes" width="150" height="50">
</applet>
then the browser would have tried to find HelloWorldApplet.class in the classes directory in the same directory as the HTML page that included the applet. On the other hand if you had written
<applet code="HelloWorldApplet.class" CODEBASE="http://www.foo123.com/classes" width="150" height="50">
</applet>
then the browser would try to retrieve the applet from http://www.foo.bar.com/classes/HelloWorldApplet.class regardless of where the HTML page was.
In short the applet viewer will try to retrieve the applet from the URL given by the formula (CODEBASE + “/” + code). Once this URL is formed all the usual rules about relative and absolute URLs apply.
You can leave off the .class extension and just use the class name in the CODE attribute. For example,
<APPLET CODE="HelloWorldApplet" CODEBASE="http://www.foo123.com/classes" WIDTH="200" HEIGHT="200">
</applet>
If the applet is in a non-default package, then the full package qualified name must be used. For example,
<APPLET CODE="com.javaskool.myapplets.HelloWorldApplet" CODEBASE="http://www.foo123.com/classes" WIDTH="200" HEIGHT="200">
</applet>
In this case the browser will look for http://www.foo.bar.com/classes/com/macfaq/greeting/HelloWorldApplet.class so the directory structure on the server should also mirror the package hierarchy.
The HEIGHT and WIDTH attributes work exactly as they do with IMG, specifying how big a rectangle the browser should set aside for the applet. These numbers are specified in pixels and are required
Spacing Preferences
- The <applet> tag has several attributes to define how it is positioned on the page.
- The ALIGN attribute defines how the applet’s rectangle is placed on the page relative to other elements. Possible values include LEFT, RIGHT, TOP, TEXTTOP, MIDDLE, ABSMIDDLE, BASELINE, BOTTOM and ABSBOTTOM. This attribute is optional.
- You can specify an HSPACE and a VSPACE in pixels to set the amount of blank space between an applet and the surrounding text. The HSPACE and VSPACE attributes are optional.
<applet code="HelloWorldApplet.class" CODEBASE="http://www.foo123.com/classes" width=200 height=200
ALIGN=RIGHT HSPACE=5 VSPACE=10>
</applet>
The ALIGN, HSPACE, and VSPACE attributes are identical to the attributes of the same name used by the <IMG> tag.
Alternate Text
The <applet> has an ALT attribute. An ALT attribute is used by a browser that understands the APPLET tag but for some reason cannot play the applet.
For instance, if you’ve turned off Java in Netscape Navigator 3.0, then the browser should display the ALT text. Note that I said it should, not that it does. The ALT tag is optional.
<applet code="HelloWorldApplet.class"
CODEBASE="http://www.foo123.com/classes" width=200 height=200 ALIGN=RIGHT HSPACE=5 VSPACE=10
ALT="Hello World!">
</applet>
ALT is not used by browsers that do not understand <applet> at all. For that purpose <applet> has been defined to require a closing tag, </applet>. All raw text between the opening and closing <applet> tags is ignored by a Java capable browser.
However a non-Java capable browser will ignore the <applet> tags instead and read the text between them.
For example the following HTML fragment says Hello to people both with and without Java capable browsers.
<applet code="HelloWorldApplet.class"
CODEBASE="http://www.foo123.com/classes" width=200 height=200 ALIGN=RIGHT HSPACE=5 VSPACE=10
ALT="Hello World!">
</applet>
Naming Applets
You can give an applet a name by using the NAME attribute of the APPLET tag. This allows communication between different applets on the same Web page.
<applet code="HelloWorldApplet.class" name="myapplet1"
CODEBASE="http://www.foo123.com/classes" width=200 height=200 ALIGN=RIGHT HSPACE=5 VSPACE=10
ALT="Hello World!">
</applet>
JAR Archives
- HTTP 1.0 uses a separate connection for each request. When you’re downloading many small files, the time required to set up and tear down the connections can be a significant fraction of the total amount of time needed to load a page. It would be better if you could load all the HTML documents, images, applets, and sounds a page needed in one connection.
- One way to do this without changing the HTTP protocol, is to pack all those different files into a single archive file, perhaps a zip archive, and just download that.
- We aren’t quite there yet. Browsers do not yet understand archive files, but in Java 1.1 applets do. You can pack all the images, sounds, and .class files an applet needs into one JAR archive and load that instead of the individual files. Applet classes do not have to be loaded directly. They can also be stored in JAR archives. To do this you use the ARCHIVES attribute of the APPLET tag
<APPLET CODE=HelloWorldApplet WIDTH=200 HEIGHT=100 ARCHIVES="HelloWorld.jar">
<hr>
Hello World!
<hr>
</applet>
In this example, the applet class is still HelloWorldApplet. However, there is no HelloWorldApplet.class file to be downloaded. Instead the class is stored inside the archive file HelloWorld.jar.
The OBJECT Tag
HTML 4.0 deprecates the <applet> tag. Instead you are supposed to use the <object> tag.
For the purposes of ewbedding applets, the <object> tag is used almost exactly like the <applet> tag except that the class attribute becomes the classid attribute.
For example,
<OBJECT classclass="nMyApplet.class"
CODEBASE="http://www.foo123.com/classes" width=200 height=200
ALIGN=RIGHT HSPACE=5 VSPACE=10>
</object>
The <object> tag is also used to embed ActiveX controls and other kinds of active content, and it has a few additional attributes to allow it to do that. However, for the purposes of Java you don’t need to know about these.
The <object> tag is supported by Netscape ???? and later and Internet Explorer ???? and later. It is not supported by earlier versions of those browsers so <applet> is unlikely to disappear anytime soon.
You can support both by placing an <applet> element inside an <object> element like this:
<object classclass="nMyApplet.class" width=200 height=200>
<APPLET code="MyApplet.class" width=200 height=200>
</applet>
</object>
Browsers that understand <object> will ignore its content while browsers that don’t will display its content.
PARAM elements are the same for <object> as for </applet>.
Passing Parameters to Applets
Parameters are passed to applets in NAME=VALUE pairs in <PARAM> tags between the opening and closing APPLET tags.
Inside the applet, you read the values passed through the PARAM tags with the getParameter() method of the java.applet.Applet class.
The program below demonstrates this with a generic string drawing applet. The applet parameter “Message” is the string to be drawn.
import java.applet.*;
import java.awt.*;
public class DrawStringAppletDemo extends Applet {
public void paint(Graphics g) {
String inputFromPage = this.getParameter("Message");
g.drawString(inputFromPage, 50, 25);
}
}
You also need an HTML file that references your applet. The following simple HTML file will do:
<HTML>
<HEAD>
<TITLE> Draw String </TITLE>
</HEAD>
<BODY>
This is the applet:
<APPLET code="DrawStringAppletDemo.class" width="300" height="50">
<PARAM name="Message" value="Howdy, there!">
This page will be very boring if your browser doesn't understand Java.
</applet>
</BODY>
<HTML>
Of course you are free to change “Howdy, there!” to a “message” of your choice. You only need to change the HTML, not the Java source code. PARAMs let you customize applets without changing or recompiling the code.
This applet is very similar to the HelloWorldApplet. However rather than hardcoding the message to be printed it’s read into the variable inputFromPage from a PARAM in the HTML.
You pass getParameter() a string that names the parameter you want. This string should match the name of a <PARAM> tag in the HTML page. getParameter() returns the value of the parameter. All values are passed as strings. If you want to get another type like an integer, then you’ll need to pass it as a string and convert it to the type you really want.
The <PARAM> HTML tag is also straightforward. It occurs between <applet> and </applet>. It has two attributes of its own, NAME and VALUE. NAME identifies which PARAM this is. VALUE is the value of the PARAM as a String. Both should be enclosed in double quote marks if they contain white space.
An applet is not limited to one PARAM. You can pass as many named PARAMs to an applet as you like. An applet does not necessarily need to use all the PARAMs that are in the HTML. Additional PARAMs can be safely ignored.
Processing An Unknown Number Of Parameters
Most of the time you have a fairly good idea of what parameters will and won’t be passed to your applet. However some of the time there will be an undetermined number of parameters. For instance Sun’s imagemap applet passes each “hot button” as a parameter. Different imagemaps have different numbers of hot buttons. Another applet might want to pass a series of URL’s to different sounds to be played in sequence. Each URL could be passed as a separate parameter.
Or perhaps you want to write an applet that displays several lines of text. While it would be possible to cram all this information into one long string, that’s not too friendly to authors who want to use your applet on their pages. It’s much more sensible to give each line its own <PARAM> tag. If this is the case, you should name the tags via some predictable and numeric scheme. For instance in the text example the following set of <PARAM> tags would be sensible:
<PARAM name="Line1" value="There once was a man from China">
<PARAM name="Line2" value="Whose poetry never would scan">
<PARAM name="Line3" value="When asked reasons why,">
<PARAM name="Line4" value="He replied, with a sigh:">
<PARAM name="Line5" value="I always try to get as many syllables into the last line as I can.">
The program below displays this limerick. Lines are accumulated into an array of strings called poem. A for loop fills the array with the different lines of poetry. There are 101 spaces in the array, but since you won’t normally need that many, an if clause tests to see whether the attempt to get a parameter was successful by checking to see if the line is null. As soon as one fails, the loop is broken. Once the loop is finished num_lines is decremented by one because the last line the loop tried to read wasn’t there.
The paint() method loops through the poem array and prints each String on the screen, incrementing the y position by fifteen pixels each step so you don’t draw one line on top of the other.
Processing An Unknown Number Of Parameters
import java.applet.*;
import java.awt.*;
public class PoetryAppletDemo extends Applet {
String[] poem = new String[101];
int numlines;
public void init() {
String nextline;
for (numlines = 1; numlines < poem.length; numlines++) {
nextline = this.getParameter("Line" + numlines);
if (nextline == null) break;
poem[numlines] = nextline;
}
numlines--;
}
public void paint(Graphics g) {
int y = 15;
for (int i=1; i <= numlines; i++) {
g.drawString(poem[i], 5, y);
y += 15;
}
}
}
You might think it would be useful to be able to process an arbitrary list of parameters without knowing their names in advance, if nothing else so you could return an error message to the page designer. Unfortunately there’s no way to do it in Java 1.0 or 1.1. It may appear in future versions.
Applet Security |
- The possibility of surfing the Net, wandering across a random page, playing an applet and catching a virus is a fear that has scared many uninformed people away from Java. This fear has also driven a lot of the development of Java in the direction it’s gone. Earlier I discussed various security features of Java including automatic garbage collection, the elimination of pointer arithmetic and the Java interpreter. These serve the dual purpose of making the language simple for programmers and secure for users. You can surf the web without worrying that a Java applet will format your hard disk or introduce a virus into your system.
- In fact both Java applets and applications are much safer in practice than code written in traditional languages. This is because even code from trusted sources is likely to have bugs. However Java programs are much less susceptible to common bugs involving memory access than are programs written in traditional languages like C. Furthermore the Java runtime environment provides a fairly robust means of trapping bugs before they bring down your system. Most users have many more problems with bugs than they do with deliberately malicious code. Although users of Java applications aren’t protected from out and out malicious code, they are largely protected from programmer errors.
- Applets implement additional security restrictions that protect users from malicious code too. This is accomplished through the java.lang.SecurityManager class. This class is subclassed to provide different security environments in different virtual machines. Regrettably implementing this additional level of protection does somewhat restrict the actions an applet can perform. Let’s explore exactly what an applet can and cannot do.
What Can an Applet Do?
An applet can:
- Draw pictures on a web page
- Create a new window and draw in it.
- Play sounds.
- Receive input from the user through the keyboard or the mouse.
- Make a network connection to the server from which it came and can send to and receive arbitrary data from that server.
- Anything you can do with these abilities you can do in an applet.
An applet cannot:
- Write data on any of the host’s disks.
- Read any data from the host’s disks without the user’s permission. In some environments, notably Netscape, an applet cannot read data from the user’s disks even with permission.
- Delete files
- Read from or write to arbitrary blocks of memory, even on a non-memory-protected operating system like the MacOS. All memory access is strictly controlled.
- Make a network connection to a host on the Internet other than the one from which it was downloaded.
- Call the native API directly (though Java API calls may eventually lead back to native API calls).
- Introduce a virus or trojan horse into the host system.
- An applet is not supposed to be able to crash the host system. However in practice Java isn’t quite stable enough to make this claim yet.
Who Can an Applet Talk To?
- By default an applet can only open network connections to the system from which the applet was downloaded. This system is called the codebase. An applet cannot talk to an arbitrary system on the Internet. Any communication between different client systems must be mediated through the server.
- The concern is that if connections to arbitrary hosts were allowed, then a malicious applet might be able to make connections to other systems and launch network based attacks on other machines in an organization’s internal network. This would be an especially large problem because the machine’s inside a firewall may be configured to trust each other more than they would trust any random machine from the Internet. If the internal network is properly protected by a firewall, this might be the only way an external machine could even talk to an internal machine. Furthermore arbitrary network connections would allow crackers to more easily hide their true location by passing their attacks through several applet intermediaries.
- HotJava, Sun’s applet viewer, and Internet Explorer (but not Netscape) let you grant applets permission to open connections to any system on the Internet, though this is not enabled by default.
How much CPU time does an applet get?
- One of the few legitimate concerns about hostile applets is excessive use of CPU time. It is possible on a non-preemptively multitasking system (specifically the Mac) to write an applet that uses so much CPU time in a tight loop that it effectively locks up the host system. This is not a problem on preemptively multitasking systems like Solaris and Windows NT. Even on those platforms, though, it is possible for an applet to force the user to kill their web browser, possibly losing accumulated bookmarks, email and other work.
- It’s also possible for an applet to use CPU time for purposes other than the apparent intent of the applet. For instance, a popular applet could launch a Chinese lottery attack on a Unix password file. A popular game applet could launch a thread in the background which tried a random assortment of keys to break a DES encrypted file. If the key was found, then a network connection could be opened to the applet server to send the decrypted key back. The more popular the applet was the faster the key would be found. The ease with which Java applets are decompiled would probably mean that any such applet would be discovered, but there really isn’t a way to prevent it from running in the first place.
User Security Issues and Social Engineering
- Contrary to popular belief most computer break-ins by external hackers don’t happen because of great knowledge of operating system internals and network protocols. They happen because a hacker went digging through a company’s garbage and found a piece of paper with a password written on it, or perhaps because they talked to a low-level bureaucrat on the phone, convinced this person they were from the local data processing department and that they needed him or her to change their password to “DEBUG.”
- This is sort of attack is called social engineering. Java applets introduce a new path for social engineering. For instance imagine an applet that pops up a dialog box that says, “You have lost your connection to the network. Please enter your username and password to reconnect.” How many people would blindly enter their username and password without thinking? Now what if the box didn’t really come from a lost network connection but from a hacker’s applet? And instead of reconnecting to the network (a connection that was never lost in the first place) the username and password was sent over the Internet to the cracker? See the problem?
Preventing Applet Based Social Engineering Attacks
- To help prevent this, Java applet windows are specifically labeled as such with an ugly bar that says: “Warning: Applet Window” or “Unsigned Java Applet Window.”
- The exact warning message varies from browser to browser but in any case should be enough to prevent the more obvious attacks on clueless users.
- It still assumes the user understands what “Unsigned Java Applet Window” means and that they shouldn’t type their password or any sensitive information in such a window. User education is the first part of any real security policy.
Applet Life Cycle |
The Basic Applet Life Cycle
- The browser reads the HTML page and finds any <applet> tags.
- The browser parses the <applet> tag to find the CODE and possibly CODEBASE attribute.
- The browser downloads the .class file for the applet from the URL found in the last step.
- The browser converts the raw bytes downloaded into a Java class, that is a java.lang.Class object.
- The browser instantiates the applet class to form an applet object. This requires the applet to have a noargs constructor.
- The browser calls the applet’s init() method.
- The browser calls the applet’s start() method.
- While the applet is running, the browser passes any events intended for the applet, e.g. mouse clicks, key presses, etc., to the applet’s handleEvent() method. Update events are used to tell the applet that it needs to repaint itself.
- The browser calls the applet’s stop() method.
- The browser calls the applet’s destroy() method.
All applets have the following four methods:
public void init();
public void start();
public void stop();
public void destroy();
They have these methods because their superclass, java.applet.Applet, has these methods. (It has others too, but right now I just want to talk about these four.)
In the superclass, these are simply do-nothing methods. For example,
public void init() {}
Subclasses may override these methods to accomplish certain tasks at certain times. For instance, the init() method is a good place to read parameters that were passed to the applet via <PARAM> tags because it’s called exactly once when the applet starts up. However, they do not have to override them. Since they’re declared in the superclass, the Web browser can invoke them when it needs to without knowing in advance whether the method is implemented in the superclass or the subclass. This is a good example of polymorphism.
init(), start(), stop(), and destroy()
- The init() method is called exactly once in an applet’s life, when the applet is first loaded. It’s normally used to read PARAM tags, start downloading any other images or media files you need, and set up the user interface. Most applets have init() methods.
- The start() method is called at least once in an applet’s life, when the applet is started or restarted. In some cases it may be called more than once. Many applets you write will not have explicit start()methods and will merely inherit one from their superclass. A start() method is often used to start any threads the applet will need while it runs.
- The stop() method is called at least once in an applet’s life, when the browser leaves the page in which the applet is embedded. The applet’s start() method will be called if at some later point the browser returns to the page containing the applet. In some cases the stop() method may be called multiple times in an applet’s life. Many applets you write will not have explicit stop()methods and will merely inherit one from their superclass. Your applet should use the stop() method to pause any running threads. When your applet is stopped, it should not use any CPU cycles.
- The destroy() method is called exactly once in an applet’s life, just before the browser unloads the applet. This method is generally used to perform any final clean-up. For example, an applet that stores state on the server might send some data back to the server before it’s terminated. many applets will not have explicit destroy() methods and just inherit one from their superclass.
- For example, in a video applet, the init() method might draw the controls and start loading the video file. The start() method would wait until the file was loaded, and then start playing it. The stop() method would pause the video, but not rewind it. If the start() method were called again, the video would pick up where it left off; it would not start over from the beginning. However, if destroy() were called and then init(), the video would start over from the beginning.
The Coordinate System
Java uses the standard, two-dimensional, computer graphics coordinate system. The first visible pixel in the upper left-hand corner of the applet canvas is (0, 0). Coordinates increase to the right and down.
Graphics Objects
- In Java all drawing takes place via a Graphics object. This is an instance of the class java.awt.Graphics.
- Initially the Graphics object you use will be the one passed as an argument to an applet’s paint() method. Later you’ll see other Graphics objects too. Everything you learn today about drawing in an applet transfers directly to drawing in other objects like Panels, Frames, Buttons, Canvases and more.
- Each Graphics object has its own coordinate system, and all the methods of Graphics including those for drawing Strings, lines, rectangles, circles, polygons and more. Drawing in Java starts with particular Graphics object. You get access to the Graphics object through the paint(Graphics g) method of your applet. Each draw method call will look like g.drawString(“Hello World”, 0, 50) where g is the particular Graphics object with which you’re drawing.
- For convenience’s sake in this lecture the variable g will always refer to a preexisting object of the Graphics class. As with any other method you are free to use some other name for the particular Graphics context, myGraphics or appletGraphics perhaps.
Applet Examples |
Drawing Lines
Drawing straight lines with Java is easy. Just call
g.drawLine(x1, y1, x2, y2)
where (x1, y1) and (x2, y2) are the endpoints of your lines and g is the Graphics object you’re drawing with.
This program draws a line diagonally across the applet.
Drawing Lines Example
import java.applet.*;
import java.awt.*;
public class SimpleLine extends Applet {
public void paint(Graphics g) {
g.drawLine(0, 0, this.getSize().width, this.getSize().height);
}
}
Drawing Rectangles
Drawing rectangles is simple. Start with a Graphics object g and call its drawRect() method:
public void drawRect(int x, int y, int width, int height)
As the variable names suggest, the first int is the left hand side of the rectangle, the second is the top of the rectangle, the third is the width and the fourth is the height. This is in contrast to some APIs where the four sides of the rectangle are given.
This uses drawRect() to draw a rectangle around the sides of an applet.
Drawing Rectangles Example
import java.applet.*;
import java.awt.*;
public class RectangleAppletDemo extends Applet {
public void paint(Graphics g) {
g.drawRect(0, 0, this.getSize().width - 1, this.getSize().height - 1);
}
}
Loading Images
- Polygons, ovals, lines and text cover a lot of ground. The remaining graphic object you need is an image. Images in Java are bitmapped GIF or JPEG files that can contain pictures of just about anything. You can use any program at all to create them as long as that program can save in GIF or JPEG format.
- Images displayed by Java applets are retrieved from the web via a URL that points to the image file. An applet that displays a picture must have a URL to the image its going to display. Images can be stored on a web server, a local hard drive or anywhere else the applet can point to via a URL. Make sure you put your images somewhere the person viewing the applet can access them. A file URL that points to your local hard drive may work while you’re developing an applet, but it won’t be of much use to someone who comes in over the web.
- Typically you’ll put images in the same directory as either the applet or the HTML file. Though it doesn’t absolutely have to be in one of these two locations, storing it there will probably be more convenient. Put the image with the applet .class file if the image will be used for all instances of the applet. Put the applet with the HTML file if different instances of the applet will use different images. A third alternative is to put all the images in a common location and use PARAMs in the HTML file to tell Java where the images are.
Loading Images Example
URL imageURL = new URL("http://www.prenhall.com/logo.gif");
java.awt.Image img = this.getImage(imageURL);
Code and Document Bases
If you don’t know the exact URL of the image, but you do know its name and that it’s in the same directory as the applet, you can use an alternate form of getImage() that takes a URL and a filename.
Use the applet’s getCodeBase() method to return the URL to the applet directory like this:
Image img = this.getImage(this.getCodeBase(), "test.gif");
The getCodeBase() method returns a URL object that points to the directory where the applet came from.
Finally if the image file is stored in the same directory as the HTML file, use the same getImage() method but pass it getDocumentBase() instead. This returns a URL that points at the directory which contains the HTML page in which the applet is embedded.
Image img = this.getImage(this.getDocumentBase(), "test.gif");
Drawing Images at Actual Size
Once the image is loaded draw it in the paint() method using the drawImage() method like this
g.drawImage(img, x, y, io)
img is a member of the Image class which you should have already loaded in your init() method. x is the x coordinate of the upper left hand corner of the image. y is the y coordinate of the upper left hand corner of the image. io is a member of a class which implements the ImageObserver interface. The ImageObserver interface is how Java handles the asynchronous updating of an Image when it’s loaded from a remote web site rather than directly from the hard drive. java.applet.Applet implements ImageObserver so for now just pass the keyword this to drawImage() to indicate that the current applet is the ImageObserver that should be used.
Scaling Images
- You can scale an image into a particular rectangle using this version of the drawImage() method:
public boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver io)
- width and height specify the size of the rectangle to scale the image into. All other arguments are the same as before. If the scale is not in proportion to the size of the image, it can end up looking quite squashed.
- To avoid disproportionate scaling use the image’s getHeight() and getWidth() methods to determine the actual size. Then scale appropriately. For instance this is how you would draw an Image scaled by one quarter in each dimension:
g.drawImage(img, 0, 0, img.getWidth(this)/4, img.getHeight(this)/4, this);
This program reads a GIF file in the same directory as the HTML file and displays it at a specified magnification. The name of the GIF file and the magnification factor are specified via PARAMs.
Scaling Images Example
import java.awt.*;
import java.applet.*;
public class MagnifyImage extends Applet {
private Image image;
private int scaleFactor;
public void init() {
String filename = this.getParameter("imagefile");
this.image = this.getImage(this.getDocumentBase(), filename);
this.scaleFactor = Integer.parseInt(this.getParameter("scalefactor"));
}
public void paint (Graphics g) {
int width = this.image.getWidth(this);
int height = this.image.getHeight(this);
scaledWidth = width * this.scaleFactor;
scaledHeight = height * this.scaleFactor;
g.drawImage(this.image, 0, 0, scaledWidth, scaledHeight, this);
}
}
This applet is straightforward. The init() method reads two PARAMs, one the name of the image file, the other the magnification factor. The paint() method calculates the scale and then draws the image.
Fonts
- You’ve already seen one example of drawing text in the HelloWorldApplet program of the last chapter. You call the drawString() method of the Graphics object. This method is passed the String you want to draw as well as an x and y coordinate. If g is a Graphics object, then the syntax is
g.drawString(String s, int x, int y)
- The String is simply the text you want to draw. The two integers are the x and y coordinates of the lower left-hand corner of the String. The String will be drawn above and to the right of this point. However letters with descenders like y and p may have their descenders drawn below the line.
- Until now all the applets have used the default font, probably some variation of Helvetica though this is platform dependent. However unlike HTML Java does allow you to choose your fonts. Java implementations are guaranteed to have a serif font like Times that can be accessed with the name “Serif”, a monospaced font like courier that can be accessed with the name “Mono”, and a sans serif font like Helvetica that can be accessed with the name “SansSerif”.
- The following applet lists the fonts available on the system it’s running on. It does this by using the getFontList() method from java.awt.Toolkit. This method returns an array of strings containing the names of the available fonts. These may or may not be the same as the fonts installed on your system. It’s implementation dependent whether or not all the fonts a system has are available to the applet.
Fonts Example
import java.awt.*;
import java.applet.*;
public class FontListDemo extends Applet {
String[] availableFonts;
public void init () {
Toolkit t = Toolkit.getDefaultToolkit();
availableFonts = t.getFontList();
}
public void paint(Graphics g) {
for (int i = 0; i < availableFonts.length; i++) {
g.drawString(availableFonts[i], 5, 15*(i+1));
}
}
}
Choosing Font Faces and Sizes
Choosing a font face is easy. First you create a new Font object. Then you call g.setFont(Font f). To instantiate a Font object use this constructor:/p>
public Font(String name, int style, int size)
- name is the name of the font family, e.g. “Serif”, “SansSerif”, or “Mono”.
- size is the size of the font in points. In computer graphics a point is considered to be equal to one pixel. 12 points is a normal size font. 14 points is probably better on most computer displays. Smaller point sizes look good on paper printed with a high resolution printer, but not in the lower resolutions of a computer monitor.
- style is an mnemonic constant from java.awt.Font that tells whether the text will be bold, italic or plain. The three constants are Font.PLAIN, Font.BOLD, and Font.ITALIC. The program below prints each font in its own face and 14 point bold.
Choosing Font Faces and Sizes Example
import java.applet.*;
import java.awt.*;
public class FancyFontListDemo extends Applet {
String[] availableFonts;
public void init () {
Toolkit t = Toolkit.getDefaultToolkit();
availableFonts = t.getFontList();
}
public void paint(Graphics g) {
for (int i = 0; i < availableFonts.length; i++) {
Font f = new Font(availableFonts[i], Font.BOLD, 14);
g.setFont(f);
g.drawString(availableFonts[i], 5, 15*i + 15);
}
}
}
Recent Comments