| Home > Core Java FAQ
> Applets FAQ |
| Applets |
| Applets
Vs Applications(04) * Installing
Applets(10) * User Interface(12)
* Program Structure(10) * Applet
Communication(05) * Exceptions(06) * Miscellaneous(08) |
| |
|
Q . Several applet methods seem special, in that I need to define them even if my own code doesn't invoke them--what are the methods, and when (and by whom) are they invoked?
|
Ans :
The applet
context (for instance, a Java-enabled browser), invokes init,
start, stop,
and destroy to control the applet's
life cycle; and the Abstract Window Toolkit (AWT) invokes update
and paint for on-screen rendering as
well as a whole family of event-handling methods.
It
is easy to think of an applet as a separate entity, but applets
execute within a larger context provided by a Java-enabled browser
and the AWT. This context impinges on the applet significantly, in
the form of method invocations signaling stages in the applet's
life and events that the applet can respond to.
The creation, initialization,
running, stopping, and destruction of an applet are all managed by
the browser that loads the applet. Four methods control the
applet's life cycle, as shown in Table 4.4.
Table
4.4: Methods that Control an Applet's Life Cycle
| Method |
When
invoked |
init |
after
the applet is loaded (this invocation is guaranteed to
precede invocation of start) |
start |
after
init |
| each
time the applet's page is revisited |
stop |
each
time the applet's page is exited |
one
final time before invocation of destroy |
destroy |
just
before the applet is garbage collected (this invocation
is guaranteed to follow all invocations of stop) |
Keeping
the applet's on-screen appearance up to date is controlled in part
by the AWT, with two methods, shown in Table 4.5.
Table
4.5: Methods that Control an Applet's On-Screen Appearance
| Method |
When
invoked |
update |
in
response to repaint; should invoke paint
in turn |
paint |
when
the applet needs to be redrawn:
- when
first brought on screen
- when
re-exposed after being covered or miniaturized
- when
scrolled
|
when
needed by update |
Finally,
the applet receives its events from the AWT, in the form of calls
to a range of event-handler methods.
|
|
Q . Should applets have constructors?
|
Ans :
No; use the
init
method to initialize your applet.
A
Java-enabled web browser creates an instance of your applet class
as part of loading the applet over the network. The browser
essentially uses a default constructor on your behalf and then
invokes your applet's init method. Any constructor
you provide will simply be ignored.
Your applet should therefore define
its own version of the init method. An applet's init
method typically performs initialization tasks such as reading
APPLET tag parameter values, initializing instance variables, and
building the applet's interface.
|
|
Q . How can my applet tell when a user leaves or returns to the web page containing my applet?
|
Ans :
The browser
invokes your applet's stop
method each time the user leaves the page (either by visiting
another page or by iconifying the browser) and invokes your
applet's start method each time the
user returns.
It
is important for browser performance that you restrain your
applet's activity while the user is visiting other web pages. Your
applet should either be completely idle or consume a bare minimum
of resources when it's not on center stage. The start and
stop methods give you the necessary control points;
you override them to define the behavior you need at those
critical times. Common uses for the stop method are:
- to stop
animations
- to pause other
computation-intensive activity
Typical corresponding
uses for the start method are to restart animations
and resume the activities stopped by stop.
|
|
Q . How do I read number information from my applet's parameters, given that Applet's getParameter method returns a String?
|
Ans :
Use the parseInt
method in the Integer class, the Float(String)
constructor in class Float, or the Double(String)
constructor in class Double.
The
getParameter method in the Applet class
is an all-purpose tool for requesting a named parameter and
getting back its value as a string. It leaves to you the task of
converting the string into an appropriate value.
The java.lang package
(in the JDK 1.1) provides classes corresponding to each of the
floating point and integral types: Double, Float, Long,
Integer, Short, and Byte. (The JDK 1.0.2 lacks the Short
and Byte classes.) Each of these classes provides a
means of converting from a String instance to an
appropriate numerical value and vice versa.
Extracting integer values is the
simpler case. All four integral classes provide a parseX
method for extracting a numerical value from a string
representation: parseLong in class Long,
parseInt in class Integer, parseShort
in class Short, and parseByte in class Byte.
Consider the parseInt method in the Integer
class, for example. If the method can successfully interpret the
string as an integer value, it returns that value as an int;
otherwise, it throws a NumberFormatException. The
following code fragment shows a typical pattern for using parseInt:
/* code in an Applet subclass: */
int anIntValue = 10; // some default value
String param = getParameter("myInt");
if (param != null) {
try {
anIntValue = Integer.parseInt(param);
} catch (NumberFormatException e) {
// ... recover from malformed parameter value
}
}
The
floating point classes of the JDK (1.0.2 and 1.1) lack an
analogous parseFloat or parseDouble
method, so you have to do a little more work. You can construct a
floating point object from the string and then ask it for its
value as a primitive floating point type:
float aFloatValue = 1.0f; // some default value
double aDoubleValue = 2.0; // some default value
String param = getParameter("myFloat");
if (param != null) {
try {
aFloatValue = new Float(param).floatValue();
} catch (NumberFormatException e) {
// ... recover from malformed parameter value
}
}
param = getParameter("myDouble");
if (param != null) {
try {
aDoubleValue = new Double(param).doubleValue();
} catch (NumberFormatException e) { /* ... */ }
}
|
|
Q . When I subclass Applet, why should I put setup code in the init() method? Why not just a constructor for my class?
|
Ans :
The browser invokes your constructor, then setStub, then init().
Hence when your constructor is invoked, the AppletStub (and through it the
AppletContext) is not yet available. Although in principle you can
do things in the constructor that don't rely (even indirectly) on the
AppletStub or AppletContext, it is less error-prone to simply defer all setup to the init() method. That way you know that anything that needs
the stub/context will have it available.
|
|
Q . Can I use an http URL to write to a file on the server from an applet?
|
Ans :
No. You will have to implement some sort of control on the server side to allow that, using a server-side programming method like CGI or servlets. Think about it - if you could do it, couldn't anyone on the net? Be careful implementing this!
|
|
Q . Can applets launch programs on the server?
|
Ans :
Yes, using CGI. Any other implementation would be server dependent. Of course this requires a lot of coding and is non-trivial. A simple way to do this is not built into Java because that would require a special server. One of Java's strengths is that it is web server independent.
A number of organizations have developed special http servers that allow applets or other clients to run Java programs on the server in a secure environment. Most notably Sun's Java Web Server implements a servlet interface for this purpose. The W3C's JigSaw implements a similar idea called resource objects.
|
|
Q .
Can applets launch programs on the client?
|
Ans
: Absolutely not. This would be a security hole big enough to walk three herds of elephants, two marching bands and at least one quarter of the people AT&T laid off through.
|
|
Q . How do you do file I/O from an applet?
|
Ans
: For security reasons, untrusted applets accessed across the network
are restricted from doing certain operations, including I/O. This prevents rogue applets from sending out your private data, or deleting
it. A trusted (signed) applet can perform these operations (JDK 1.1
on).
The simplest approach for server-side I/O is to use the Linlyn class available from http://www.afu.com. This is free software under the GNU
license, and uses FTP to move files between an applet and the server.
It is suitable for low-volume non-critical use like keeping a high-score file. The Linlyn class has a very simple application
programmer interface.
o The following suggestion is for server-side input.
You can read a file on the server if you can create a URL referencing the file. Then open a stream, then use any of the
stream-based methods to read.
This allows reading but not writing. It requires an http daemon running on the server, which will usually be the case.
try{
URL url = new URL("http://somewhere.com/test.txt");
// or URL url = new URL( getDocumentBase(), filename);
BufferedReader in = new BufferedReader(
new InputStreamReader(
url.openStream() ) );
String s = in.readLine(); //read till you get a null line.
} catch(MalformedURLException e){
System.out.println("URLException:"+e);
} catch(IOException e){
System.out.println("IOException:"+e);
}
}
You cannot write a file on the server this way.
o The following suggestions are for server-side output.
It absolutely requires the cooperation of the server to allow an applet to write a file to the server. This cooperation may take
any of several forms:
+ FTP server
+ File server (webnfs or custom written)
+ Listening on a socket for data from applets
+ CGI script
+ Java RMI (remote method invocation)
+ JDBC process
In particular:
+ FTP code. Use the Linlyn class mentioned above.
+ WebNFS. This is an evolution of the NFS (Network File System) to make file resources visible in browsers. More information
at http://www.sun.com/webnfs
+ Open a socket back to the server and read/write the data. Have a process on the server that listens for socket
connections from applets and does the requisite I/O. This does I/O on the server.
+ Or use a CGI script or servlet on the server to write when
browsed.
o The following suggestions are for client-side I/O. Use a trusted applet (see section on security). This will permit local I/O
without any of the restraints mentioned above. In this regard, the
appletviewer and many other browsers regard applets loaded from a local filesystem (rather than across the net) as being more
trustworthy, and perhaps even allowed to do I/O.
o The simplest form of output is probably for the applet to connect to the mailserver port on the server, and prompt the user to enter
his email address. Then email him the data to save locally if he
wishes. If a small amount of data he can later enter it by cut-and-paste into the applet when he next invokes it.
o Or use a browser that has a security policy that is configured to
allow file I/O (such as Sun's appletviewer).
o Read this article
http://www.javareport.com/html/features/archive/9802/somers.shtml
for an introduction to the basics.
|
|
Q . How do I access remote machine's file system through Java Applet?
|
Ans
:
The only way to do this is to run a file server
daemon process on the remote machine and contact
this server from the applet. That server could be based on RMI or sockets. However if the files
on the system other than the applet's origin needs to be contacted, the applets needs to be
signed too as it cannot open a socket connection to an url other than its origin.
|
|
|