a partial Java application program designed to run inside the womb of a web browser, with help from some predefined support classes. Everything I say here about Applets also applies to JApplets since JApplet is a subclass of Applet.
java.applet.Applets must run inside a web browser (or AppletViewer). You can also run them in Java Web Start to avoid the peculiarities of individual browsers. You cannot run them from the java.exe command line, unless you add some code to make them into a hybrid. To spawn a web browser from within an application to get it to display an Applet, see the tips under HTML rendering. Applets are typically automatically downloaded over the web freshly every time they are executed. They can also be run from local hard disk. In contrast, applications cannot be run inside a browser, though it is possible to make a dual mode program that can run either as an Applet or application. Applets run on the client’s machine. In contrast, Servlets run on the host webserver.
Applets are harder to write than applications. I would recommend that beginners start with applications. With Applets you have the following complications:
The easiest way to write an Applet is to start with a working one, perhaps one of mine. Write it as a hybrid and debug it as an application. Once you have it working as an application, test it as an Applet in a browser. If you have an IDE (Integrated Development Environment) like Intellij Idea, you can run it in the IDE as an Applet as an intermediate phase between testing as an application and as an Applet in a browser.
To make Applets very safe to run, even when they were composed by teens with the morals or skill of Beavis and Butthead, Applets are severely restricted. Unsigned Applets (without special permission to bypass security) are not permitted to:
If your Applet needs to do any of the above things, it must be signed.
Now that IE (Internet Explorer) has dropped its own version of Java, it is reasonable to ask your clients to upgrade to the latest Oracle Java, understanding that some will not. For them, you must develop or at least test on earlier versions. Don’t just assume that just because you did not use any new features that you are home free.
Standalone Java applications are not so limited. Exactly what the limitations are is controlled by the security manager in the browser. If the user installs an alternate security class, the Applet may have more powers. The security restrictions are controlled entirely by the browser. There is nothing to stop you from writing a non-conforming browser that has quite different security restrictions for Applets. However, in practice, you write code to sign your jars and bypass each of the five different security schemes used in browsers.
Programmers bitterly complain about these restrictions. The restrictions protect the end user from malicious web Applets they might encounter on the web. Without such protection, vicious Applets could destroy the user’s hard disk, print reams of paper, phone out on a spare serial port and rack up long distance bills, go sniffing on the LAN (Local Area Network) for the company books… You don’t want to give those powers to psychotic strangers — those same people who stay up late at night writing viruses.
Windows has a feature whereby the user can increase the size of the default system font. Let’s say you increase it to 125%. Now, when you use an Applet in Internet Explorer, IE will give you Applet region to paint 25% bigger than you asked for on your <APPLET tag. Windows/IE is inviting you as an Applet programmer to use a 25% bigger font inside your Applet and to magnify your images by 25% to make them easier for the user to see. If you ignore the extra space, your Applet will appear with small fonts, small icons and a big wide empty border.
Usually HTML tags are in lower case, but I often show them in this document all upper case to help distinguish them from Java source code.
Here is tip to find the optimal size parameters. Run the Applet as an application. Drag the frame to the optimum size. Use PaintShop Pro to capture a screen snapshot of the frame, excluding the menu bar. Then look in the lower right corner of the PSP window (or use Mioplanet Pixel Ruler) to discover the size for the <APPLET height and width tags. Then measure including the menu bar to discover the size for the Frame. setSize( width, height ) when running as an application. It will need about 24 pixels extra height. This trick saves a lot of guesswork and experimentation to home in on the optimal values.
When debugging Applets, remember to click Shift-Reload in your browser, not just plain Reload to attempt re-running with your new version. Shift-Reload supposedly flushes the cache of class files. This usually does not work. You have to exit the browser and restart. It is a good idea to put something unique in every incarnation of your code so you can tell if you are running the old or new code. I do it by flipping a background colour or setting a micro version number. It is safest to stop and restart the browser for each test.
You can go crazy debugging Applets because the browser sometimes caches old copies of jars, classes, html… It is best to start each test with at least a fresh loading of your browser, preferably with all its caches deleted using a bat file before each test. I often start different a different browser for each test to get a clean start, e.g. Opera, Firefox, SeaMonkey,, IE.
It is best to debug as an application, then at the last minute convert to an Applet.
HTML Tag | Comments |
---|---|
<APPLET | |
code=com.mydomain.mypackage.MyClass | The name of the class file for the Applet. You are not allowed to specify an absolute URL (Uniform Resource Locator) or absolute fully qualified hard disk filename. Strange as it sounds, Oracle originally said you must specify the trailing .class, but now they suggest you leave it out. Some some browsers let you do it either way. The new Oracle tutorials shows it without the .class. If you do it the way different from the way the browser likes, you will just get a gray square with no error message, even if you have manifest Main-Class entry. All the recommended browsers will handle it either way. |
width=330 | width of entire Applet display in pixels. There is nothing the Applet can do itself to change this. If you needed variable size you would have to resort to JavaScript or a server-side technology to generate HTML pages with the appropriate size. This can be specified as a percentage e.g. width=100% or with CSS (Cascading Style Sheets) commands. Then the Applet will grow and shrink with the enclosing window. |
height=240 | height of entire Applet display in pixels. There is nothing the Applet can do itself to change this. |
archive=Everything.jar,Sub/MoreStuff.zip | Resource file, classes etc. Your ARCHIVE parameter must have a list of the absolute or relative jar files, separated by commas (no spaces). (Watch out! The ARCHIVE tag in <OBJECT is space-separated!) If you have too little or too much qualification, or if you fail to use the file naming conventions of your server, you will be in trouble. You are probably best to use absolute URLs or fully qualified hard disk file names. Whether the archive is supposed to be relative to the current HTML directory, the CODEBASE, or all elements of the classpath is unclear. The forms of archive I use most are archive=myapp.jar archive=../myapp.jar and archive=somedir/myapp.jar. |
codebase=http://mydomain.com/ | I suspect CODEBASE is simply broken in the current implementations. Theoretically it is the absolute or relative URL/directory where class files are, like a one-element classpath. Normally the class files are in the same directory as the html, so you don’t need it. In practice, I have found your CODEBASE parameter must have an absolute http:// -style reference to the base directory where the code is stored. The codebase is only needed when your code resides somewhere other than where the html page was loaded from. For a local hard disk, the only thing I could get to work on NT with all browsers and AppletViewers is leaving the CODEBASE out entirely which causes the CODEBASE to default to the same directory as where the enclosing HTML page was loaded from. You may find for your platform you have to code it something like this: file://localhost/C|//MyDir/ or C:\MyDir\. I also further suspect that some browsers will take the a relative CODEBASE as relative to each element of the CLASSPATH, not relative to the current HTML directory. If the user of the signed Applet is behind a firewall, for some strange reason, if he invokes the Applet using the IP (Internet Protocol) rather than the DNS (Domain Name Service) name of the website in the codebase e.g CODEBASE= "http:// 65.110.21.43 /" instead of CODEBASE=mindprod.com, all works. Otherwise you get a trustProxy Property error message. |
vspace=10 | pixel width of border above and below the Applet |
hspace=10 | pixel width of border left and right of the Applet |
align=left | how this Applet aligns, treated like an image |
alt=You need Java to run this Applet | what to display if no Java interpreter available. Normally this would be the same text that appears just before the </applet> tag. This optional attribute specifies any text that should be displayed if the browser understands the APPLET tag but can’t run Java Applets. |
name="receiver" | Name for this Applet so that other Applets can communicate with it. Other Applets would do an Applet Applet.this.getAppletContext() . getApplet( receiver ) to get a handle on this Applet. You don’t need this parameter if you use Enumeration<Applet> otherApplets = Applet.this.getAppletContext() which gets you a list of all the Applets running on the page (including yourself). |
mayscript | Lets Applet read/write cookies and peek at the page it is embedded in using JavaScript DOM (Document Object Model). |
> | All that stuff above has to be inside the <APPLET… >, but the params may not be. |
<!-- simple parameter --> <param name="favouriteColour" value="orange"> <!-- note you CANNOT say, as any sane person would expect: --> <param favouriteColour="orange"> |
The param statements are Java’s ode to
verbosity. They pass information to the Applet.
There can be as many param statements as you like. Beware of params with
decimal points. <param name =cost value=10.00 > When your Applet
runs in Europe, it may be expecting a comma instead unless you take special
precautions.
Param values cannot contain embedded " or newline characters. You can encode the parameters using HTML entities such as ", > or &#nn;. The browser should automatically convert them for you to the equivalent character when you do your getParam. If the browser does not convert them for you, you can convert the entities back to characters with my free entities package. I tested recent versions of Chrome, Firefox, Opera, and IE and they call converted entities to characters automatically. Unfortunately, there is no & entity for \n. and 
 do not work. You will have to roll your own convention, perhaps using the character pair \n or some rarely used character such as ~ or ` to stand in for newline. You can’t use <br> because < and > are awkward characters in their own right. Awkward characters are defined as ones that have be specially escaped/quoted/represented to use them literally because they have special meaning as commands/delimiters. This encoding is natural. Fussing with entities only kicks in when you have awkward characters. Further, the way you encode parameters is completely familiar — almost the same way you encode awkward characters in HTML body text. Watch out for &#xnnnn; and &#nnnn; style entities. What they mean depends on the enclosing HTML document encoding. Alternatively, you could write a little utility to use java.net.URLEncoder to encode the String, then manually include it as the param value, then use java.net.URLDecoder inside the Applet to make sense of the parameter. URLEncoder encodes space as + and special characters as %xx hex, so you can do the encoding in your head once you see a few examples. The catch is, once you hook up URLDecoder to a param, you can’t use that param anymore for plain text, at least not completely transparently. Neither java.net.URLEncoder.encode nor java.net.URLDecoder.decode are for encoding/decoding URLs. They are for encoding/decoding application/x-www-form-urlencoded form data. If you wanted to disguise the value, you could encode it with base64 or base64u armouring. Applet parameter names are case insensitive (Case does not matter. Names can be upper or lower case). Applet parameter values are case-sensitive (passed exactly as written to your Applet’s getParameter. If you want lower case, use parmValue.) toLowerCase(). |
<img src=image/NoJava4U.jpg > | image to display if no Java interpreter available. |
You need Java to run this Applet | Text that will display on a really stupid browser that has no idea what an Applet tag is. |
</applet> | and finally the ending tag for the |
Here is an example of minimalist markup.
<applet code="MyApplet.class" width="330" height="240"> </applet>
Make sure you get your <s s ‘s ’s s and >s in the right places.
A more typical Applet invocation might look like this:
<applet archive="../mypackage.jar" code="com.mindprod.mypackage.MyClass.class" width="565" height="46" alt="Java needed to display this Applet."> <param name="flavour" value="strawberry"> Java needed to display this Applet. </applet>
<APPLET, from a CSS point of view, is just another tag. In your CSS style sheet, you can apply properties to it, adjust the margin spacing, put borders around it… In your HTML markup you can give it a class or id. Unfortunately Chrome and Firefox have a common bug and don’t display a border around Applets even when you ask them to. Opera and IE work properly.
In theory, <APPLET has been deprecated and you should use the more generic, verbose, error-prone <OBJECT tag. In HTML5 (Hypertext Markup Language v 5) <APPLET no longer works, but thankfully HTML5 uses a greatly simplified <OBJECT syntax. This is what you should be using for all new work.
HTML4 <OBJECT has some minor nice features, like a standby message and a way of providing alternate implementations if the user’s browser does not support Java. It can work with serialised Applets. It works for languages and plug-ins other than Java. However, <OBJECT is still not as widely supported as <APPLET, so it is probably wiser to stick with <APPLET. See the HTML spec for details.
Starting with JDK 1.4.2, you can arranged that jars be cached at the client site using the EMBED tag cache_archive parameter.
That was the polite version, but here is what I really think of <OBJECT> and <OBJECT> tags. Anti-Java, rather corrupt people launched a successful attempt to derail Java by somehow convincing some weak minded folk at the W3C to deprecate the <APPLET tags. Browser makers have all sensibly resisted this foul play and all continue to support <APPLET. The replacement is an utterly preposterous and verbose scheme using <OBJECT> and <OBJECT> tags that works in different ways in different browsers. The scheme is beyond ridiculous. It is so baroque, you can’t even hand code it. You have to use an automated tool C:\Program Files\java\jre1.8.0_131\jre\lib\ext\htmlconverter.jar to convert <APPLET tags into pages and pages of gobbledegook. Don’t use them! If you ignore my advice, you might as well add to the flakiness by using the Java Deployment Toolkit to generate the tags with JavaScript.
Tell the W3C (World Wide Web Consortium) and Microsoft to shove their <OBJECT> and <EMBED> and lunatic classids to a foul-smelling place. Please, do not use these tags!
It is possible to interleave Microsoft and Mozilla markup cleverly so that each ignore’s the other’s markup.
HTML 5 no longer supports APPLET. There are five standards.
OBJECT is a meaningless keyword. It is like calling it THING. It should have been called PLUGIN.
Many websites tell you to use non-conforming parameters with OBJECT in HTML5. Check with the spec to see which ones are still supported. Some have been converted to PARAMs. One of the strange features of HTML5 OBJECT is you must specify the jar twice.
You can use a simple Jump to Java Button to handle a missing JRE (Java Runtime Environment).
HTML5 <OBJECT is much more reasonable than its predecessors, but has fewer features. Here is an example of how you invoke an Applet.
It is almost the same as the old <APPLET tag with the addition of MIME type type="application/x-java-applet" and a redundant reference to the jar. data="canadiantax.jar".
What if you already have an application? How do you allow it to run also as an Applet? An Applet is just a Panel with init, start, stop and destroy methods. Write an Applet shell that does a this.add to add your application into the Applet in its init method, just as you would any other Panel.
Though it is possible to create transparent and translucent components using colours with the alpha channel ( the fourth number in new Color ( red, green, blue, alpha )) set to something other than 0xff, I have found no way to make the Applet or JApplet itself transparent. You could pass the colour of the web page’s background in as an Applet param or have JavaScript communicate that information to Java. This would only give true transparency only when the browser were using a plain untextured background.
Often you want to display some other web page. You can trick the browser into doing that for you with:
Applet.this.getAppletContext().showDocument( url, window );
Your Applet does not get to see the web page. It goes straight to the browser for rendering. Because this feature can be so easily abused to wallpaper the user’s screen with popups, it is now often blocked.
Communication between Applets running on the same page, it turns out, is much simpler than you might imagine. First, there is one instance of your Applet class running per APPLET tag on a web page running, with a common static region. Applets are just a bunch of ordinary objects. Applets from the same class share the same static variables! Objects can call each other’s methods. They are all in the same address space. There is thus almost zero problem with inter-Applet communications. Your only problem is finding the other Applet objects on your page to talk to. There are two mechanisms for that:
In Applet propagates information around by putting it in static variables, or by passing parameters to the methods of other objects to get them to do something with the information. There is only one thread, not one per Applet. You can’t just deposit information and expect the other Applets to notice the change.
The browser may decide to kill (forget) Applets not on the current page and then again it may not. Presumably, if you held onto a reference to offscreen Applets in your onscreen Applet, or in a common doubly linked object, those offscreen objects would have to stay alive.
AppletContext.getApplets will get all the Applets on the page, not just other instances of the current class. Further, usually this instance is included, but don’t count on it.
Normally, all Applets run in the same JVM instance. This allows instances of an Applet on a page to share information via static variables and calling each other’s instance methods. As of JRE1.8.0_131 you can no longer count on this. The plug-in may run Applets in separate JVMs (Java Virtual Machines). Applets in different JVMs will not be visible to each other when calling AppletContext.getApplets()even if they are within the same document, which would seem to contradict the Java API :
Apparently it is possible to encourage the plug-in to start Applets in the same VM if the <APPLET> tag has a 'java_arguments' param with an identical set of arguments, regardless of what these options actually specify. However, it is explicitly not guaranteed that this will work. Also, according to Oracle, there is no way to name a JVM instance used to launch a particular Applet and force subsequent Applets into that JVM instance. Phhht!
This all works fine for 11 or fewer instances of your Applet on the screen. Above that, the browser will put each Applet in its own airtight JVM where it cannot see any of the other Applets. Enumeration<Applet> otherApplets = Applet.this.getAppletContext().getApplets() then no longer works. Neither do shared static variables.The following SSCCE demonstrates the problem with getApplets().
I have reported it to Oracle. I doubt they will fix the problem, but they might add a warning to the AppletContex.getApplets () method.
Some have chastised me that this is not a bug. If you read the documentation like lawyer, this behaviour is considered within spec. I respond, it violates the principle of least astonishment. The actual behaviour is highly unexpected and should be documented.
Applets without jars use the ordinary local classpath. This can cause trouble since the developer’s classpath and the end user’s classpath won’t usually match. There are two sorts of trouble that ensue:
I advice you to ignore the classpath and put all the classes you need into the jar. With a jar, the classpath is ignored. That way the code will work the same on your machine as an your customer’s machines.
When you are starting a project, which should it be, an Applet or application or both? The advantages of using an Applet are:
The current fashion is to use Servlets exclusively for all web based applications. I think this is idiotic. It has made data entry even more primitive than it was on the keypunch. The advantages of using Applets over Servlets are:
The advantage of using an Applet over Java Webstart are:
In Java version 1.5 or later there is a splash logo that comes up as your Applet loads. It sort of a radiant Sun-like image. You can modify that with a magic <param tag that provides an alternate scalable image.
Applet.audioClip can play *.au, *.aiff, *.wav and *.midi files. Old Javas supported only *.au 8 bit, μlaw, 8000 Hz (Hertz), one-channel.
You can control the browser’s JVM runtime parameters (see java.exe) that control stack and heap sizes etc. from the Java Control Panel. click Start ⇒ Control Panel ⇒ Java ⇒ Java ⇒ Java Applet Settings ⇒ View. Add the required parameters in the 4th column, next to the JVM. It does not look like it is editable, but it is.
This page is posted |
http://mindprod.com/jgloss/applet.html | |
Optional Replicator mirror
|
J:\mindprod\jgloss\applet.html | |
Please read the feedback from other visitors,
or send your own feedback about the site. Contact Roedy. Please feel free to link to this page without explicit permission. | ||
Canadian
Mind
Products
IP:[65.110.21.43] Your face IP:[18.226.87.168] |
| |
Feedback |
You are visitor number | |