一個Java Applet程序中必須有一個類是Applet類的子類,成為該子類是Java Applet的主類, 并且必須
是public class。 Applet類是包java.applet中的一個類, 同時它還是包java.awt中Container(容器)類
的子類。
因此Java Applet的主類的實例是一個容器。
如下:
import java.applet.*;
import java.awt.*;
publicclass ?Fivteenth extendsApplet
{
protected Button button1, button2;
int sum;
public void init()? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //初始化,程序執行過程中只被調用一次
{
button1 = new Button("OK");
button2 = new Button("Cancel");
add(button1);
add(button2);
}
public void start() ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //初始化后,緊接著自動調用start()方法,start()將多次自動調用執行
{
sum = 0;
for(int i = 0; i <= 100; ++ i)
{
sum += i;
}
}
public void stop()//停止,當瀏覽器離開java Applet所在頁面轉到其他頁面時調用stop()方法
{
}
public void destroy()//瀏覽器結束瀏覽時,執行destroy()方法
{
}
public void paint(Graphics g)//該方法可以使一個applet在屏幕上顯示某些信息,如文字色彩背景等
{
g.setColor(Color.blue);
g.drawString("程序設計方法", 20, 60);
g.setColor(Color.red);
g.drawString("sum = " + sum, 20, 100);
}
}
---------------------------------------------------------------------------------
---------------------------------------------------------------------------------
---------------------------------------------------------------------------------
import java.applet.*;
import java.awt.*;
publicclass TextFieldExample extendsApplet
{
TextField text1, text2, text3;
public void init()
{
text1 = new TextField("輸入密碼:");
text1.setEditable(false);
text2 = new TextField(10);
text2.setEchoChar('*');
text3 = new TextField("我是一個文本框", 20);
add(text1);
add(text2);
add(text3);
}
}