How to call an applet method from JavaScript

23,398

Solution 1

The problem is the if statement check:

document.CityChoice.City[0].checked == true

This is not exactly how it goes with JavaScript since the wrong expression you have there throws an error and it never makes it into the if statement body.

I removed the if statement and changed the code to something like this:

function selectedCity()
{
    document.SimpleMessageApplet.setMessage("Hello");
}

When I click I see the Hello message fine.

Change your HTML file content to something like:

<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Insert title here</title>
        <SCRIPT LANGUAGE="JavaScript">
            function selectedCity()
            {
                var elem = document.getElementById('cityRb');

                if(elem.checked)
                {
                    document.SimpleMessageApplet.setMessage(elem.value);
                }
            }
        </SCRIPT></HEAD>
    <BODY >
        <b>This is the Applet</b>
    <APPLET CODE="MessageApplet.class" NAME="SimpleMessageApplet" WIDTH=350 HEIGHT=100 >
    </APPLET >
    <FORM NAME="CityChoice">
        <input type="radio" id="cityRb" name="City" value="Boston" onClick="selectedCity()"> Boston<br>
    </form>
</BODY >
</html>

Also adding the full class code:

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Label;

/**
 *
 * @author hmmmmm
 */
public class MessageApplet extends Applet {

    private Label m_mess;

    public void init() {
        setBackground(Color.lightGray);
        setLayout(new BorderLayout());
        m_mess = new Label("MessageApplet is Running...: No Selection Yet", Label.CENTER);
        add(BorderLayout.CENTER, m_mess);
        m_mess.setBackground(Color.red);
    }

    public void setMessage(String message) {
        m_mess.setText("Selection: " + message);
    }
}

Solution 2

The problem you get is on different browsers is that they have different implementations of the outdated LiveConnect (JavaScript <-> Java) technology.

As a rule of thumb, Firefox will be more cooperative when trying to do such things.

Your problem is that you are trying to include your applet on the page in a very ancient way. Although it may and will work on some browsers, it is not the recommended way to include an applet to a page.

Java Web start is the tech stack and JNLP is the protocol you can use to distribute Java content in a standardized way as you can read in this article:

Java Web start

A deployment JNLP descriptor is the proper way you can use to embed your applet to a page. Also, it is a good idea to use Sun's deployJava.js script which will save you a lot of trouble when deploying your applet to a container on the page (it's a bit restricted though so feel free to add stuff to it).

Java™ Rich Internet Applications Deployment Advice

All in all, a JNLP/Java web start powered applet is the way to go. Below is an example of a deployment descriptor.

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <jnlp codebase="file:/C:/JavaApplication6/dist/" href="launch.jnlp" spec="1.0+">
        <information>
            <title>JavaApplication6</title>
            <description>blalbla</description>
            <description kind="short">JavaApplication6</description>

        </information>
    <update check="background"/>
    <security>
    <all-permissions/>
    </security>
        <resources>
    <j2se java-vm-args="-Djava.security.policy=applet.policy" version="1.5+"/>
    <jar href="JavaApplication6.jar" main="true"/>


        <jar href="lib/jna.jar"/>
    <jar href="lib/platform.jar"/>
    </resources>
        <applet-desc height="300" main-class="winToJnaApi.NewApplet" name="JavaApplication6" width="300">

        </applet-desc>
    </jnlp>
Share:
23,398
Pravin
Author by

Pravin

Updated on July 25, 2020

Comments

  • Pravin
    Pravin almost 4 years

    I have created an applet and I am going to access an applet method from my HTML page on a web project.

    Here my applet looks like:

    public class MessageApplet extends Applet {
    
        private Label m_mess;
    
        public void init()
        {
            setBackground(Color.lightGray);
            setLayout(new BorderLayout());
            m_mess = new Label("MessageApplet is Running...: No Selection Yet", Label.CENTER);
            add(BorderLayout.CENTER, m_mess);
        }
    
        public void setMessage(String message)
        {
            m_mess.setText("Selection: " + message);
        }
    }
    

    And my HTML page looks like:

    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Insert title here</title>
        <SCRIPT LANGUAGE="JavaScript">
            function selectedCity()
            {
                if(document.CityChoice.City[0].checked == true)
                {
                    document.SimpleMessageApplet.setMessage(document.CityChoice.City[0].value);
                }
            }
        </SCRIPT>
    </HEAD>
    
    <BODY>
        <b>This is the applet</b>
        <APPLET 
            CODE="MessageApplet.class" 
            NAME="SimpleMessageApplet" 
            WIDTH=350
            HEIGHT=100>
        </APPLET>
        <FORM NAME="CityChoice">
            <input type="radio" name="City" value="Boston" onClick="selectedCity()"> Boston<br>
        </form>
    </BODY>
    
    </html>
    

    But when I click radio button my browser hangs and I cannot access the applet method ever.

    My applet class is in default directory and HTML is in WebContent folder. What should I change in my code?

  • Pravin
    Pravin almost 12 years
    I replaced my code with above but my IE gets hang when I click on check box and at top of the page it shows Error box, when I click on that it opens java console that shows: MessageApplet.class not found. java.lang.ClassNotFoundException: MessageApplet.class at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source) at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source) at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source) at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source)
  • Timmo
    Timmo almost 12 years
    This is another problem. If the applet class is contained in a package then also add the package mypackage.MessageApplet.class before the applet class name. I would suggest for now moving the class into default package, compile it and have the html file in the same directory.
  • Pravin
    Pravin almost 12 years
    Now I create a package "myPackage" under which I placed MessageApplet.java and index.html but when I run, it shows 404 error that: The requested resource (/SignAppletTest/) is not available.
  • Pravin
    Pravin almost 12 years
    @baba I read about JNLP from above links but I am confused how to use it? can you please give me a simple "Hello World" program with JNLP file that I'll understand
  • Timmo
    Timmo almost 12 years
    Please use the html and Java class I sent you. Create a project and put both files in src directory of your project. Open bin/index.html in a browser. They work fine. Your src and bin directories might have different names. I don't know what IDE you are using or your project settings
  • Nikola Yovchev
    Nikola Yovchev almost 12 years
    @ DaTroop np. Glad I could help. @Balasaheb There are a lot of examples on the net but I will see what I can do. :)
  • Pravin
    Pravin almost 12 years
    thanks, its working, but I want to run it at server side hence I create a jar file containing Java class and html which you sent at same place and I want to redirect to that html from my index.html file but it can't find at run time. I placed this jar file in project classpath. How can i do that?
  • Timmo
    Timmo almost 12 years
    @Balasaheb you must not add the html file in the jar.I just told you to add it in the src directory for you to test and see that it works.For a correct deployment have a look here: docs.oracle.com/javase/tutorial/deployment/applet/… and here blogs.oracle.com/thejavatutorials/entry/…. baba's already mentioned jnlp
  • Pravin
    Pravin almost 12 years
    @baba yes, its working on my local machine using JNLP but when i try it run on tomcat server my java console show an error like: exception: JNLP file error: sign-applet.jnlp. Please make sure the file exists and check if "codebase" and "href" in the JNLP file are correct.. java.io.FileNotFoundException: JNLP file error: sign-applet.jnlp. at sun.plugin2.applet.JNLP2Manager.loadJarFiles(Unknown Source) at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.ru‌​n(Unknown Source)at java.lang.Thread.run(Unknown Source)
  • Nikola Yovchev
    Nikola Yovchev almost 12 years
    You have to make sure that if you use signed libraries(jars), e.g some crypto libs (bouncycastle), that all of your libraries are signed by the same authority. If you have two jars signed by different entities, you have to extract their contents, compile them and sign them with your own certificate or just obtain the unsigned jars.
  • Timmo
    Timmo almost 12 years
    @Balasaheb The question was "How to call Applet method from javascript". I answered that by finding the errors, correcting them and posting the code to help you. Yet you de-accepted my answer after accepting it just because you could not deploy the applet in a JAR. The question is not about deployment but what was wrong with your javascript code not calling your Applet method which I fixed for you. Baba was very correct about deployment but I am the one who fixed your code.Accept the answers if they r the solution indeed and open new questions with new titles for other problems next time.
  • Timmo
    Timmo almost 12 years
    @Balasaheb It just wasn't the way things work. You have a question and you get an answer move on. You have another question...post it as a different question. Anyway thanks for the understanding.