新建一个名为TankClient的类 并在类中添加如下的代码
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TankClient extends Frame{
public void lunchFrame(){
this.setLocation(400,300);
this.setSize(800, 600);
setVisible(true);
this.setResizable(false);
this.setTitle("坦克大战");
this.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e){
System.exit(0);//最重要的逻辑控制代码
}
});
}
public static void main(String[] args) {
TankClient tc =new TankClient();
tc.lunchFrame();
}
}
其中windowAdapter为事件处理器(实现了事件监听器接口windowListener中所有的事件处理函数,都是空实现,如果有需要可以自己重写对应的函数,简化了步骤),windowClosing为事件处理器,接收一个事件对象(windowEvent)。System.exit(0)为主要控制,表示退出程序。详细情况可以参考Java的事件处理机制。
注意掌握匿名类的书写方法
Tips 在Eclipse中如果要重写一个方法,可以使用标签栏中的Source