Question

I am getting an annoying error for my Java applet. I am new to applets so please note that I am not that experienced with this at all.

I have an HTML file labelled as index.html with the following code:

    <HTML>   
    <HEAD>
            <TITLE>Applet JAR Example
        </TITLE>
    </HEAD>  
    <BODY> 
        <CENTER>
            <B>Are YOU ready to dance??
            </B>
            <BR>
                <BR>

                <APPLET CODE="shawn/Main.class" ARCHIVE="lol.jar"
                        WIDTH=400      
                HEIGHT=300>    
</APPLET>   
</CENTER>
</BODY>  
</HTML>

In the same directory, I have a Jar file labelled as lol.jar with the following code:

package shawn;

import java.applet.AudioClip;
import java.awt.*;
import java.io.File;
import java.io.Serializable;
import javax.swing.*;

public class Main extends JApplet implements Serializable {

        Image img = Toolkit.getDefaultToolkit().getImage("hey.gif");

        @Override
        public void init(){
            playSound();
        }

       @Override
    public void paint(Graphics g)    {
        g.drawImage(img, 0, 0, this);
    }

    public void playSound(){
        AudioClip ac = getAudioClip(getCodeBase(), "hey.wav");
        ac.play();
    }
}

Inside that same directory, I have two files labelled as hey.wav, and hey.gif.

When I execute the page the applet fails to load, outputting only the message Error. Click for details. When I click, it says:

RuntimeException

followed by...

java.lang.reflect.InvocationTargetException

Everything works when I run it in Eclipse, but it only does this when I export it. I`ll add more details if needed.

Était-ce utile?

La solution

One definite problem in the applet is:

Image img = Toolkit.getDefaultToolkit().getImage("hey.gif");

If you look at the JavaDocs for getImage(String) it states:

Returns an image which gets pixel data from the specified file, whose format can be either GIF, JPEG or PNG. The underlying toolkit attempts to resolve multiple requests with the same filename to the same returned Image.

The highlight of file was by my choice. Applets and files are rarely used together, and it is not appropriate for this situation. Instead the Image must be accessed by URL.

Applet offers instead Applet.getImage(URL) & getImage(URL,String). The 2nd is particularly handy when we need to form an URL relative to the code base or document base.

If the image is located in the same directory as the HTML, it might be loaded using something along the lines of:

Image img = getImage(getDocumentBase(), "hey.gif");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top