Java Reference
In-Depth Information
As an alternative to using method
getDocumentBase
(which returns a
URL
refer-
ence), we may create our own
URL
object directly from the image fi le's path and use
this as the fi rst argument to method
getImage
. For example:
image =
getImage(new URL("http://somesite/pics/"),"pic.gif");
(Note that the '/' at the end of the URL path is mandatory.)
The above syntax may be abbreviated slightly by concatenating the path and fi le
name into one string and then using an overloaded form of
getImage
that simply
takes a
URL
argument:
image =
getImage(new URL("http://somesite/pics/pic.gif"));
In practice, though, most sites have fi rewalls that prohibit applets from having
such open access to their fi le systems and exceptions of type
java.security.
AccessControlException
will be generated if such access is attempted.
Yet another variation in the syntax for accessing the image fi le is to use the
fi l e
protocol in the argument to the
URL
constructor. For example:
image =
getImage(new URL("fi le:///c:/webfi les/pics/pic.gif"));
As might be expected, this also does not allow free access to a site's fi le system.
In fact, trying to access any directory other than the one containing the applet is
likely to generate a security exception. The above syntax (stipulating the directory
containing the associated applet) will be demonstrated in the next example. Firstly,
though, it needs to be pointed out that our code:
should import package
java.net
;
must deal with exceptions of type
MalformedURLException
.
The latter requirement means that we must introduce a
try
block and associated
catch
clause (since we cannot change the signature of inherited method
init
to
make it throw this exception).
Example (Pre-Swing)
This applet is very similar to the previous one, but now the image fi le is in a speci-
fi ed directory. The required code changes are shown in emboldened type. Just for a
change, the image fi le used is an animated GIF. As usual, of course, a simple HTML
page will be required to access the applet.
import.java.awt.*;
import java.applet.*;
import java.net.*;
public class ImageTest1
b
extends Applet
{
private Image image;
public void init()
Search WWH ::
Custom Search