Monday, March 13, 2006

Applets in your webapps

WARNING: This blog entry was imported from my old blog on blogs.sun.com (which used different blogging software), so formatting and links may not be correct.


A question that has
come up
a number of times is how to use Applets in Creator web apps. Since we don't ship an Applet component (which renders an applet tag) out of the box, what can you do? Obviously, you can switch to the JSP view and manually enter an <applet> tag. But what if you need to provide dynamically computed parameters to the applet?



There's an extremely powerful technique you can use that I've
written it up before,
but it's useful enough that it bears repeating. And perhaps it helps to apply it to our specific scenario -- applets.



Briefly stated, the technique is to use the Output Text component to emit arbitrary HTML into the page. The Output Text can be value bound to a property in your page bean (in other words, you get a write a Java method that returns a String which is output by the output text), and you can turn off the Escape property on the Output Text to get the HTML to pass straight through, thus letting you emit HTML instead of just normal text.



First try this: Drop an output text. Find its Escape property and turn it off. Then go edit the Text property and set it to <applet />. Hit Return. Voila! You should see the Output Text immediately replaced by a large box (300 by 150 pixels, the same as the default applet size in Mozilla) as well as a Java icon. This is how the designer shows the applet tag at designtime. It does not execute applets at designtime.



Then go and put an actual applet .class file in your web directory, and set the code= property to point to the applet, e.g. code="ArcTest.class" and width="200" and height="200", where ArcTest is the sample applet
found on java.sun.com.



If you now run, you'll see the applet successfully deployed and running. Here's a side-by-side view:






Now you just need to make the code dynamic instead. The code modeller won't always be able to evaluate the string at designtime, so you may not get the applet rendering you see above. In any case, go and change the Text property to something like #{Page1.foo} instead (where Page1 is the page you're editing). Switch to the Java file, and add something like this:



public String getFoo() {
return "<applet code=\"ArcTest.class\" width=\"300\" height=\"300\"/>";
}


P.S. You actually should put text inside the applet tag telling the user that they need to go and download the JRE for their browser. For more details on the applet tag, see for example this resource. Remember that your HTML needs to be XHTML -- lowercased and well formed.


1 comment:

  1. it's really simple solution, but... a little funny ;)
    Thanks for help!
    Michael

    ReplyDelete