2011-05-30 79 views
5

我有一個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); 
} 

注:劊子手是applet類。如果我運行它,它工作正常,但我要做的是,使它作爲應用程序運行。

當我運行上面的主,我得到了以下錯誤:

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 

此錯誤是來自該行的劊子手類:

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

GetCodeBase()方法返回null,我需要幫助,我該如何使這個方法正常工作,或者用另一種可以訪問我的文件來獲取資源的方法來替換它?

預先感謝您

回答

1

Applets有一個特殊的運行環境。如果您希望代碼也作爲應用程序運行,那麼您不能依賴該環境提供的任何功能。

顯然你在這裏使用的是一個小程序特定的功能。您必須搜索如何在應用程序中完成此操作,然後檢測您正在運行的環境並使用適當的方法。

編輯:

相反getCodeBase()的我會嘗試:

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

getAudioClip也是在一個applet定義的,所以這是一個不走了。而不是java.applet.AudioClip你必須使用javax.sound.sampled API。

+0

首先,我想感謝你,但你能否請我帶領我找到一個正確的方式來加載圖像和audioclips,而不使用「getCodeBase」url在applet? – Mostafa 2011-05-30 10:48:44

+0

請參閱我的編輯。 – vbence 2011-05-30 11:50:41

0

我有一個類似的問題,並提出了以下適用於參數,codeBase和getImage很好 - 我仍然在尋找getAudioClip()部分...它會很好,如果有像ImageIo對於音頻....

// simulate Applet environment 
Map<String, String> params = new HashMap<String, String>(); 
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; 
} 
相關問題