McGraw.Hill.How.to.Do.Everything.with.JavaScript.eBook-DDU

Page 338

CHAPTER 15: Use JavaScript to Manage Browser Plug-Ins

319

} public void paint(Graphics g) { g.drawString(displayString, 75, 75); } }

We can then use the HTML <param> tag inside the <applet> tag to pass a customized string to display to the applet, like so: <applet code="HelloWorld.class" width="250" height="150" id="myapplet"> <param name="display" value="This is my applet!"> </applet>

Using this new parameter, we can change the string our Java applet displays without having to recompile the code. An applet can accept multiple parameters, so your Java applet can be designed to be completely configurable from outside the compiled code.

Connect to Java Applets Using JavaScript As you would expect, JavaScript is able to call the public methods and set the public properties of any Java applet. The Java applet we created in the last section already has a number of public properties and methods, some of which are automatically provided by HelloWorld’s parent class—Applet. We can create a small JavaScript function that will modify the string being displayed and force the applet to refresh by calling the appropriate public properties and methods, as follows: <script language="JavaScript" type="text/javascript"> function displayString() { var applet = document.getElementById("myapplet"); applet.displayString = "String is set here"; applet.repaint(); } </script>

This JavaScript function starts by creating a variable that will point to the Java applet on our HTML web page using the familiar document.getElementById() function. We then modify the displayString property, which was defined inside the HelloWorld Java applet. In order to get Java to display our new string to the screen, we have to call the applet’s repaint() method.

15


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.