Search code examples
javajavascriptapplet

How to call a method declared in an applet from JavaScript


I am trying to make a basic Java applet to open a file on the client's computer for them. I would like to call the openFile function in the Java applet below via JavaScript.

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;

import javax.swing.JApplet;

public class Test extends JApplet {
    public void openFile(String filePath) {
        File f = new File(filePath);

        try {
            Desktop.getDesktop().open(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In between the body tags of my webpage I have the following:

<applet code="Test.class" height="0" width="0"></applet>

<script type="text/javascript">
    document.applets[0].openFile("C:\\test.log");
</script>

When I load the page I get the error:

TypeError: Object # has no method 'openFile'

What do I need to do to fix this error and get the applet working?


Solution

  • Use:

    <script src=
      "http://www.java.com/js/deployJava.js"></script>
    
    <script>
        <!-- The applet id can be used to get a reference to
        the applet object -->
        var attributes = { id:'mathApplet',
            code:'jstojava.MathApplet',  width:1, height:1};
        var parameters = {jnlp_href: 'math-applet.jnlp'};
        deployJava.runApplet(attributes, parameters, '1.6');
    </script>
    

    Reference: Invoking Applet Methods From JavaScript

    JavaScript is allowed to directly call the applet’s public methods or public variables. JavaScript considers the embedded applet as an object. By providing the applet with an ID, JavaScript can access it with:

        document.Applet_ID.Applet_Method()
    

    And you can use this,

    File MyApplet.html

    <html>
    <head>
        <script language="Javascript">
            function accessAppletMethod()
            {
                document.getElementById("AppletABC").appendText("Applet Method");
            }
        </script>
    
        <title>Testing</title>
    </head>
    
    <body onload="accessAppletMethod()">
    
        <h1>Javascript acess Applet method</h1>
    
        <applet width=300 height=100 id="AppletABC"
            code="JavaScriptToJava.class">
        </applet>
    </body>
    
    </html>
    

    File JavaScriptToJava.java

    import java.applet.Applet;
    import java.awt.FlowLayout;
    import java.awt.TextArea;
    
    public class JavaScriptToJava extends Applet{
    
        TextArea textBox;
    
        public void init(){
            setLayout(new FlowLayout());
            textBox = new TextArea(5, 40);
            add(textBox);
        }
    
        public void appendText(String text){
            textBox.append(text);
        }
    }