Javascript and Applet interaction

This is part of a series of articles written circa 2005, on the topic of interactions between Java applets and Javasacripts

So we want our javascripts to make use of Java objects. In the previous page we discussed the HTML tags that signal our intent to the browser. Now we will look at the code that actually does the job.

The applet from the previous page has been modified so that it will listen to javascript calls. In actual fact several modifications have been made but the only one that matters is the addition of a public method that will update the JTextArea of the applet when called. It's a one liner but only because we have not considered factors like thread safety for the sake of simplicity and clarity.

    public void setText(String s)
    {
        txt.setText(s);
    }

The applet is compiled and embedded into this web page, along with a simple HTML form.

 

Online Demo
Applet
JavaScript

We have added a onClick event listener to the HTML button above. When it is clicked, the updateApplet() method will be called. It will result in the setText() method of the applet that we have just defined being called. Again we have a one liner.

    function updateApplet()
    {
	document.jsap.setText(document.forms[0].txt1.value);
    }

You will see all this in action when you hit the 'Update applet' button. In the next step, (which will also be the last step,) we will look at how we can do the opposite; that is use a button in the applet to update our webpage.