最近爲了打發空餘的時間,開始用Applet寫小遊戲。今天碰到了一個讓我很迷惑的問題:寫好的程序在eclipse這樣的IDE工具裏運行一切正常。但當在頁面上運行時,會在要出現圖片時不動,圖片顯示不出來。
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
我讀去圖片的方法如下:
ImageIcon image = new ImageIcon(applet.getCodeBase(), "img/biggerbat.JPG");
後來,在網上搜索資料才發現Applet在網頁上有些許限制,而其中最大的限制就是:
Applet不能訪問本地硬盤。
於是通過在網上搜索,終於找到了解決之道:
URL myResource = this.getClass().getResource("img/biggerbat.JPG");
ImageIcon image = new ImageIcon(myResource);
Applet雖然不能直接讀本地文件,但它可以通過URL來訪問資源。
下面是我轉自網絡上的資料:
To quickly convert a Java application to a Java applet, follow these simple steps below:
- Change:
public class HelloWorld {
to:
public class HelloWorld extends JApplet{
- Change:
public static void main(String[] args) {
to:
public void init() {
- Remove:
JFrame frame;
and change all references to the frame in the class to:
this
and all references in subclasses to:
null
- Move all your images into a subfolder called "images".
- Add this global variable:
private final static String imagePath = "images//"
- Create a method to load ImageIcons as resources:
private ImageIcon LoadImageIcon(String imgName){ URL myResource = this.getClass().getResource(imgName); return new ImageIcon(myResource); }
and change all instances of:
new ImageIcon("example.jpg")
to:
LoadImageIcon(imagePath + "example.jpg")
- Build a jar archive of your compiled class files.
- Create a HTML file like this one:
<html> <body> <applet code="HelloWorld.class" archive="HelloWorld.jar" height="100" width="100"> </body> </html>
And then, you are all set!
把Applet的Source打成一個jar包的原因是:
Applet的啓動時間很長
因爲每次都得下載所有東西,而且每下載一個類都要向服務器發一個請求。或許瀏覽器會作緩存,但這並不是一定的。所以一定要把applet的全部組件打成一個JAR的(Java ARchive)卷宗(除了.class文件之外,還包括圖像,聲音),這樣只要發一個請求就可以下載整個applet了。
遊戲還在繼續開發中。。。
自己也在不斷學習中。。。