Search code examples
javajavascripthtmlappletjapplet

Call JApplet function from javascript is not a function


I am trying to call a JApplet function from javascript, but it won't work.

This is the code of my applet:

public class Main extends JApplet implements ActionListener {
    private static final long serialVersionUID = 1L;
    private JTextArea m_textArea;
    private JButton m_button;
    public String mypublicvariable = "foo";

    public Main() {
        this.setLayout(null);

        m_textArea = new JTextArea();
        m_textArea.setBounds(25, 25, 200, 100);
        m_textArea.setText("some value");
        getContentPane().add(m_textArea);

        m_button = new JButton("crypt");
        m_button.setBounds(25, 150, 100, 20);
        m_button.addActionListener(this);
        getContentPane().add(m_button);
    }

    public static void main(String[] args) {
        new Main();
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        if(arg0.getSource().equals(m_button)) {
            m_textArea.setText("worked");
        }
    }

    public void doSomething() {
        m_textArea.setText("sdlkjfdöjdlkjfsfsyfhudjfdsfj");
    }
}

This is my HTML Code:

<!DOCTYPE HTML>
<html>
    <head>
    </head>
    <body>
        <applet name="TestApplet" id="TestApplet" code="main.Main" archive="test.jar" width="500" height="500" />
        <script>
            console.warn(document.TestApplet.mypublicvariable);

            document.TestApplet.doSomething();
        </script>
    </body>
</html>

Neither I get the value of my public variable(undefined) nor I can call my public function(document.TestApplet.doSomething is not a function). For clarification, I exported the whole project of with the Main class as a jar file and named it test.jar. My class Main is in the package main.


Solution

  • The applet element is invalid. It was never meant to be a self-closing element. For robustness sake, it should declare the scriptable flag.