Java Applet 憑藉強大的互動功能在網路應用中佔據重要地位,但其程式設計入門門檻較高。本文整理了 Java Applet 開發中最基礎且實用的核心技巧,涵蓋文字顯示、參數讀取、滑鼠鍵盤事件回應、圖像與聲音處理等關鍵技術,並附上完整範例碼,幫助開發者快速上手。
使用 Graphics 類別的 drawString() 方法即可實現文字繪製。Java 採用 Unicode 編碼(每字元 16 位元),原生支援中文顯示。
// HelloWorld.java
import java.awt.*;
import java.applet.*;
public class HelloWorld extends Applet {
String text = "Hello World!";
public void paint(Graphics g) {
g.drawString(text, 20, 20); // 在座標 (20,20) 顯示文字
}
}
注意:早期瀏覽器(如 IE 4.0)可能存在中文顯示 Bug,建議使用 Netscape 或更新版瀏覽器測試。
Applet 可透過 HTML <param> 標籤接收參數,通常在 init() 初始化階段讀取。
// ShowText.java
public class ShowText extends Applet {
String text;
public void init() {
text = getParameter("word"); // 讀取參數
}
public void paint(Graphics g) {
g.drawString(text, 20, 20);
}
}
對應 HTML:
<applet code="ShowText.class" width="100" height="28">
<param name="word" value="Hello World!">
</applet>
參數名稱不區分大小寫(word 與 WORD 等同)。
覆寫 mouseDown() 與 mouseUp() 方法處理滑鼠按下與釋放事件。Java 不區分滑鼠左右鍵。
public boolean mouseDown(Event evt, int x, int y) {
text = "Mouse Down";
repaint();
return true;
}
public boolean mouseUp(Event evt, int x, int y) {
text = "";
repaint();
return true;
}
覆寫 keyDown() 與 keyUp() 方法處理鍵盤按下與釋放。
public boolean keyDown(Event evt, int x) {
text = "Key Down";
repaint();
return true;
}
public boolean keyUp(Event evt, int x) {
text = "";
repaint();
return true;
}
使用 getImage() 載入圖片,drawImage() 繪製;使用 getAudioClip() 載入音效,play()、loop()、stop() 控制播放。
getSize() 或 bounds() 取得 Applet 寬高g.setColor(Color.red) 設定繪圖顏色掌握這些核心技巧,即可開發出具備基本互動功能的 Java Applet 應用。建議搭配官方 API 文件深入學習各類別完整方法。