Applets
Introduction
- An applet is a Java program embedded within a Web page and
run by a Web browser.
- An applet has a graphical user interface (GUI ).
- Java applet programming is event-driven programming.
- Applets are much like java applications with the following
exceptions:
- You use the Applet or JApplet classes instead of the
JFrame class to build your application.
- Like JFrame, Applet and JApplet already have a content
pane you may set its layout manager
- You don't have to setup the size of the applet in the java
code, instead, this is done in the HTML code.
- Applets are run within a web page by an Applet Plugin
- Creating an Applet in Netbeans
- Create your project as normal
- Right click on the package and select New File/Folder
- Select Java Gui forms and JApplet Form as the file type. This
will create a JApplet with the form designer enabled.
- (if you select Java class then JApplet under that, then you
won't get the form designer capability).
- Edit your JApplet like you would a JFrame.
- To test, right click on the applet file in the files
window and select "run file". This will start up the applet viewer and
allow you to test your applet.
- To test with an html, create a new html file with an
applet tag, use archive = "..\dist\projectname.jar" code =
"appletname.class". Right click on the html file and select view
Due to security ordinary Applets can't:
- read or write files on the user's system (without special
permission)
- communicate with an internet site other than the one they
originated on
- run or load any programs in the user's system
- You can read files from the server where the applet resides and
communicate with that server
Trusted Applets
- User must have a relatively new browser, and
have Java JDK 1.3 or higher installed (JDK 1.6 is the current version)
- Trusted applets are allowed access to the user's hard drive.
- To be a "true" trusted applet you have to pay money to a
certificate service and provide them with lots of information. You can
however, create your own key certificate and attach that to your
applet. When a user accesses the applet, they will be presented
with
a pop-up box asking if they want to trust you.
- There are two steps to making your applet a trusted applet
- first generate a key certificate (from a cmd window)
keytool
-genkey -alias TestApplet -validity 365
- Second, sign the applet. Signing the applet attached the
key certificate to the jar file. From a cmd window :
jarsigner TestApplet.jar
TestApplet
- Note: If you rebuild the jar file, then you will have to
run the jarsigner again
- To read more about trusted applets, click
here
- To read more about security and plugins, click
here
- Netbeans has the ability to sign
the applets for you. To create a trusted Applet in
Netbeans:
- Create your project with the JApplet inside it.
- In Netbeans, right click on the project name inside the
"projects" window (upper left), select "properties" from the popup menu
- Under the Application item, open WebStart
- Turn on the "Enable Web Start"
- Turn on the button labeled "Applet descriptor" and choose
your JApplet class from the list below the radion button
- Press the button labeled "Customize" under the "Signing" item
- Select the "Self signed by generated key" option (Netbeans
will create the key certificate)
- Select "Enable Software Projections" for the Mixed Code item
- The next time you do a clean and build, a signed Jar will be
created, also in the distr folder you will find a "bare bones" html
file for testing (launch.html) and a jnlp file that when double clicked
will launch your JAppet inside the applet tester. (You don't have
to turn on the signing to get the bare bones html and jnlp files)
- JNLP files are XML text files that tell your JRE how to run
your applet from the desktop. You'll probably need to edit the
file to set the width and height to make it look right. To run
using the JNLP you need both the JNLP file and the JAR file.
Other programming notes:
- you can add any of the following methods to control interaction
if needed:
- init() - is called when the browser creates the applet
object.
- start() - this is called whenever the applet begins (after the
init) and whenever the user leaves the applet page, then returns to it
in
the browser
- stop() - called whenever a user leaves the applet page
- destroy() - allows the applet to perform cleanup before it is
released from memory
- paint() is called whenever the applet needs to repaint itself,
this occurs if the browser is minimized then restored, during scrolling
and any other time the applet becomes visible. NOTE: you only have to
provide a paint method if you are doing graphics with a Canvas or
Graphics2D object. Buttons, lists, etc repaint themselves. For JApplet,
override the update method
instead.
- If you rebuild your applet you may have to exit the browser
then restart it to get the new version loaded. Pressing the reload
button on the browser may not due the trick.
The Applet HTML Tag
- The Applet tag was officially deprecated (made obsolete)
in
HTML version 4, and isn't supported in HTML version 5. But many
browsers still support it. Instead, you should use a the java
deployment toolkit script (see below).
<applet CODE = "TestApplet.class"
ARCHIVE = "TestApplet.jar"
WIDTH = 200
HEIGHT = 200
HSPACE = 0
VSPACE = 0
ALT = "alternate text to show if the applet cannot be run by the
browser"
ALIGN = Middle>
<PARAM NAME = "p1" VALUE="p1" />
<PARAM NAME = "p2" VALUE ="p2" />
</applet>
- The CODE parameter identifies the name of the Applet class
- The Archive parameter identifies the name of a JAR file that
holds all the class files, gifs, and jpgs associated with the applet.
This parameter is omitted if you do not create a jar file. Instead, be
sure to have all the
class files in the same directory as the one specified in the code
parameter.
- The Width and Height specify how big a space on the web page
to allocate for the applet. this is in pixels
- the HSPACE and VSPACE specify the amount of space around the
applet to separate from text on the web page
- the Align positions the applet window on the web page. This
works much the same way as aligning text and images on a web page.
- the text in the ALT parameter will be displayed if the applet
cannot be started (plugin not installed or other error like a bad class
name in the
applet tag).
- between the <applet> and </applet> tags can come
optional
parameter tags in the form of
<param NAME = "parametername" value =
"parametervalue" />
Deployment Toolkit Script:
- In the old Java Plug-in, applets always run with the latest
version of JRE installed on a client machine. With the next generation
Java Plug-in introduced in the Java SE
6 update 10 release, you can specify that the Java kernel (core set
of Java classes absolutely required by the JRE) or normal online
installer be automatically downloaded, if the specified minimum JRE
version is not already installed on the client. If the specified
minimum JRE version does not exist, the latest version of the JRE
is downloaded from
www.java.com
. In the case of a Java
kernel download, any additional packages
may also be specified for download as required by the applet.
- Use the
runApplet()
function in deployJava
to ensure that a minimum Java Runtime
Environment is available on a client machine before launching the
applet.
<script src="http://www.java.com/js/deployJava.js"></script>
<script>
var attributes = {codebase:applet url',
code:'Applet.class',
archive:'Applet.jar',
width:710, height:540} ;
var parameters = {fontSize:16} ;
var version = '1.6' ;
deployJava.runApplet(attributes, parameters, version);
</script>
- The above code will launch the Java 2D applet on JRE version
1.6.0 or higher with one parameter (fontSize). The bolded
items would be what you would customize for your applet.
- To trigger the installation of Java kernel and additional
packages, add the following before the
deployJava.runApplet() function:
deployJava.setInstallerType('kernel');
// include any required packages as shown below
deployJava.setAdditionalPackages('javax.swing, javax.xml');
<script src="http://www.java.com/js/deployJava.js"></script>
<script>
var attributes = {codebase:applet url',
code:'Applet.class',
archive:'Applet.jar',
width:710, height:540} ;
var parameters = {fontSize:16} ;
var version = '1.6' ;
deployJava.setInstallerType('kernel');
// include any required packages as shown below
deployJava.setAdditionalPackages('javax.swing, javax.xml');
deployJava.runApplet(attributes, parameters, version);
</script>
Example:
<script
src="http://www.java.com/js/deployJava.js"></script>
<script>
var attributes = {codebase:'.',
code:'Demo9_11.class',
archive:'Demo9_11.jar',
width:361, height:217} ;
var parameters = {fontSize:16} ;
var version = '1.6' ;
deployJava.setInstallerType('kernel');
// include any required packages as shown below
deployJava.setAdditionalPackages('javax.swing, javax.xml');
deployJava.runApplet(attributes, parameters, version);
</script>
JAR Files
- Creating JAR files
- A JAR file takes all the files needed for an applet and zips
them together into one file. This makes managing the files on the web
site easier and downloading by clients faster.
- Its good practice to package all your applet class files,
gif, jpgs, etc. in a JAR file, in Netbeans just select Run-Clean and
Build from the menu.
- The Jar file will be created in the dist sub folder of your
project
- This jar file will be the only file that needs to reside on the
web server.
Calculator Applet
Click here for a zip file with the
code
WebMenu Example
- This applet shows several new things: how to pass
parameters to an applet, how to put messages in the java console, and
how an applet can
interact with the browser.
- Passing parameters.
- first add <param ,,,> tags between your <applet>
and </applet> tags in the HTML file, e.g.
- name must be there and is referenced by your code when
getting the value. Value is a string passed to the
applet.
<APPLET code="MenuApplet.class"
archive="MenuApplet.jar" width="100%" height="30" hspace="0" vspace="0"
align="middle">
<PARAM NAME = "target" VALUE="_blank" />
<PARAM NAME = "Menu1" VALUE
="News,CNN,http://www.cnn.com,Fox,http://www.foxnews.com" />
<PARAM NAME = "Menu2" VALUE
="Sports,ESPN,http://www.espn.com,NFL,http://www.nfl.com,MLB,http://mlb.mlb.com"
/>
<PARAM NAME = "Menu3" VALUE
="Weather,TWC,http://www.weather.com,AccuWeather,http://www.accuweather.com/,Hurricane,http://www.myfoxhurricane.com/"
/>
</APPLET>
- Inside your applet code, add code to the init() method, and in
the init
method add calls to getParameter to retrieve the data. If getParameter
returns
nulll, then the HTMLdid not have a parameter by that name. getParameter
cannot be
called
in the constructor of the applet.
public void init()
{
....
if(getParameter("Target") != null)
target =
getParameter("Window");
}
- Java Console
- Java Console is a window built into most browsers that display
error messages from applets and allow a very limited amount of
debugging
of applets.
- In FireFox look under the Tools menu for "Web developer"
- In Chrome press the little wrench, the look for
the"Tools-Developer Tools" menu
- In Internet Explorer, look under the "Tools-Develop Tools" menu
- Loading Web pages. For an applet to tell the
browser to go to a different page you must first create a URL object,
then use the showDocument method of the applet context.
try{
URL
link = new URL("http://www.msnbc.com");
getAppletContext().showDocument(link,target); // link is a string that
has the URL
}
catch(MalformedURLException ex) {
showStatus("Bad URL: http://www.msnbc.com");
} - In order to create a URL object you
must import java.net.*;
- the second parameter on showDocument method is optional, if it
is there then it specifies where to show the document (similar to the
target parameter on an HTML a href tag). e.g.
getAppletContext().showDocument(link,"_blank"); // show the
document in a new browser window.
- "_self" Show in the window and frame
that contain the applet.
- "_parent" Show in the applet's parent frame. If
the applet's frame has no parent frame, acts the same as "_self".
- "_top" Show in the top-level frame of the
applet's window. If the applet's frame is the top-level
frame, acts the same as "_self".
- "_blank" Show in a new, unnamed top-level window.
- name Show in the frame or
window named name. If a target named name does not already exist,
a new top-level window with the specified name is created, and
the document is shown there.
Click here to see download the
MenuApplet project
Example: An Applet that Sketches
- This program provides basic sketching features for a web page.
- The toolbar has buttons that change the current color
- In the center area is a JPanel object with a white background
that is used to drawn on. The Graphics object is used to drawn
lines.
- New things:
- MouseListener - The MouseListener events let Sketcher
know when a button was pressed, when it was released, and when the
mouse entered and exited the Sketcher's boundaries.
- MousePressed - mouse button went down
- MouseReleased - mouse button went up
- MouseMotionListener The MouseMotionListener events let
Sketcher know when the mouse moved (with or without a button down).
- MouseMoved indicates the mouse is moving
- MouseDragged indicates the mouse is moving with a button
pressed
- MouseEvent - this object is generated and sent to
event handlers. It contains methods to determine the x,y location
of the mouse
at the time of the event and the state of the mouse buttons.
- getX() - returns X coordinate
- getY() - returns Y coordinate
- getClickCount() - returns number of clicks (used for
processing double clicks)
- getButton() - tells which button caused the event
- Graphics class - Sketcher creates a graphics class
whenever it needs to draw something on the screen. Graphics class
provides many functions to draw shapes, lines, and text. In this
case I used the setColor and drawLine functions. You
can draw on top of most objects. To do so you ask the component to
getGraphics this returns a Graphics object, then you tell the object to
perform graphics functions. In this case I am drawing on a JPanel. The
Color object is used to access common colors or to create specific
colors.
Graphics g =
sketchPanel.getGraphics(); //
create a graphics object
g.setColor(currentColor);
// set its color
g.drawLine(downX,downY, evt.getX(),
evt.getY()); // tell it to draw a line
click here to see the code for the
sketching
applet
Slide Viewer
Click here to download the code in zipped format