java 游戏编程(二)

作者在 2007-08-08 05:04:00 发布以下内容

小应用程序必须要通过浏览器运行,其生命周期开始与当它被浏览器加载的那一刻,结束于浏览器被关闭或转移至其他网页时。从开始到结束有四个方法会在某些时间被发生时被调用:

init()  程序第一次被加载时

start()   程序开始运行时

stop()   程序停止运行时

destroy()   程序结束时

这四个方法必须继承于Applet类,需要在子类中重定义这些方法的功能。

通过操作下面这个例子可以反映四个方法被调用的时机:

import java.applet.*;
import java.awt.*;
public class LifeCycle extends Applet
{
 public void init()
 {
  System.out.println("init method");
 }
 public void start()
 {
  System.out.println("start method");
 }
 public void paint(Graphics g)
 {
   g.drawString("Welcome to java gameworld",10,50);
   System.out.println("paint method");
 }
 public void stop()
 {
  System.out.println("stop method");
 }
 public void destroy()
 {
  System.out.println("stop method");
 }
}

同样定义一个start.html文件来加载这个类:

<html>
 <head><title>Life Cycle</title></head>
 <body>
  <Applet code="LifeCycle.class" width=200 height=200></applet>
 </body>
</html>

 

与之前不同的是,为了看见System.out.println里的字符,我们需要在命令提示符下使用appletviewer打开它,方法是在cmd中start.html的目录下输入appletviewer start.html

这样,通过对打开的这个窗口的操作就可以知道什么时候调用了什么方法了。

 

Java开拓 | 阅读 801 次
文章评论,共0条
游客请输入验证码