我如何将applet作为应用程序运行?

我有一个Applet类,我想让它作为一个应用程序运行,所以我写了以下代码:

public static void main(String args[]) { JFrame app = new JFrame("Applet Container"); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); app.setSize(200, 100); Hangman applet = new Hangman(); applet.init(); app.setLayout(new BorderLayout()); app.setSize(500,500); app.getContentPane().add(applet, BorderLayout.CENTER); app.setVisible(true); } 

注意:Hangman是applet类。 如果我运行它,它工作正常,但我要做的是,使它作为一个应用程序运行。

当我运行上面的main时,我收到以下错误:

 Exception in thread "main" java.lang.NullPointerException at java.applet.Applet.getCodeBase(Applet.java:152) at Me.Hangman.init(Hangman.java:138) at Me.Client.main(Client.java:54) Java Result: 1 

这个错误来自Hangman类中的这一行:

 danceMusic = getAudioClip(getCodeBase(), "../../audio/dance.au"); 

GetCodeBase()方法返回null,我需要帮助我如何使这个方法正常工作,或者可能用另一个可能访问我的文件获取资源的方法替换它?

先感谢您

Applet具有特殊的运行时环境。 如果您希望代码也作为应用程序运行,那么您不能依赖该环境提供的任何function。

显然你在这里使用的是Applet特有的function。 您必须搜索如何在应用程序中完成此操作,然后检测您正在运行的环境并使用适当的方法。

编辑:

我会尝试:而不是getCodeBase()

 getClass().getProtectionDomain().getCodeSource().getLocation(); 

但是getAudioClip也在applet中定义,所以这也是一个getAudioClip 。 而不是java.applet.AudioClip你必须使用javax.sound.sampled API。

使用Hangman.class.getResource()或getResourceAsStream()来加载资源。 http://www.java2s.com/Code/JavaAPI/java.lang/ClassgetResourceStringnamerelativetotheclasslocation.htm

我有一个类似的问题,并提出以下适用于参数,codeBase和getImage – 我仍然在寻找getAudioClip()部分…如果有像ImageIo for Audio这样的话会很棒。 ..

 // simulate Applet environment Map params = new HashMap(); URL documentBase; /** * set the parameter with the given name * * @param name * @param value */ public void setParameter(String name, String value) { params.put(name.toUpperCase(), value); } @Override public String getParameter(String name) { String result = null; if (params.containsKey(name)) result = params.get(name); else { try { result = super.getParameter(name); } catch (java.lang.NullPointerException npe) { throw new IllegalArgumentException("parameter " + name + " not set"); } } return result; } /** * @param documentBase * the documentBase to set * @throws MalformedURLException */ public void setDocumentBase(String documentBase) throws MalformedURLException { this.documentBase = new URL(documentBase); } @Override public URL getDocumentBase() { URL result = documentBase; if (result == null) result = super.getDocumentBase(); return result; } @Override public Image getImage(URL url) { Image result = null; if (this.documentBase != null) { try { result = ImageIO.read(url); } catch (IOException e) { } } else { result = super.getImage(url); } return result; }