0

我的 Java 小程序出现烦人的错误。我是小程序的新手,所以请注意,我对此一点经验都没有。

我有一个标记为 index.html 的 HTML 文件,其中包含以下代码:

    <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>

在同一目录中,我有一个标记为 lol.jar 的 Jar 文件,其中包含以下代码:

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();
    }
}

在同一个目录中,我有两个标记为 hey.wav 和 hey.gif 的文件。

当我执行页面时,小程序无法加载,只输出消息Error. Click for details。当我点击时,它说:

运行时异常

其次是...

java.lang.reflect.InvocationTargetException

当我在 Eclipse 中运行它时一切正常,但只有在我导出它时它才会这样做。如果需要,我会添加更多细节。

4

1 回答 1

1

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");
于 2013-05-15T04:37:51.633 回答