Search code examples
javaappletembedded-resourcejapplet

Cannot use applet in HTML


I have this code:

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;


public class MainApp extends JApplet implements ActionListener {
    private static final long serialVersionUID = -7076767216192554828L;
    JButton begin = new JButton(new ImageIcon("splash.png"));
    @Override
    public void init() {
        setSize(300, 300);
        setLayout(new BorderLayout());
    begin.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            begin();
        }

    });
    add(begin);
    setVisible(true);
}
private void begin() {
    remove(begin);
    repaint();
}
@Override
public void actionPerformed(ActionEvent e) {
          //to be used later
}
}

It works perfectly when seen in the applet viewer in Eclipse. However, in HTML, it fails:

<html>
<head>
<title> Test </title>
<body>
<APPLET code="MainApp.class" width="300" height="300"> Applet unavailable </APPLET> <br>
<a href="essay.docx"> Essay </a> (right click, Save Target As, in the menu under the name change it to "All Files," save as "essay.docx")
</body>
</html>

When I run this, it gives a java.lang.reflect.InvocationTargetException! I looked up the exception and found nothing helpful.

Before I used the .png for the button. everything was fine. I also added the repaint(), but that couldn't have made a difference.


Solution

  • The image is in the folder that contains the HTML file.

    // called from somewhere in the methods (e.g. init()) of the applet class 
    URL urlToImage = new URL(getDocumentBase(), "splash.png");
    begin = new JButton(new ImageIcon(urlToImage));
    // ...