import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Yard extends Frame { public static final  int ROWS=40; 
public static final  int COLS=60; 
public static final  int BLOCK_SIZE=15; 

Snake s=new Snake();
Egg e=new Egg();
Image offScreen=null; public static void main(String[] args) {
new Yard().launch(); }

public void launch(){
this.setBounds(200, 50, COLS*BLOCK_SIZE, ROWS*BLOCK_SIZE);
this.addKeyListener(new KListener());

this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent arg0) {
System.exit(0);
}

}); new Thread(new PaintThread()).start();
this.setVisible(true);
}


public void update(Graphics g) {//此处没有使用默认super(),就打断了继续调用Paint()
if(offScreen ==null){
offScreen=this.createImage(COLS*BLOCK_SIZE, ROWS*BLOCK_SIZE);

}

Graphics gOffScreen=offScreen.getGraphics();//得到缓冲图的画笔

//Color c=gOffScreen.getColor();

paint(gOffScreen);//调用方法在缓冲图上作画,刷点
//gOffScreen.setColor(c);
g.drawImage(offScreen, 0, 0, null);//一次性将换冲图放在窗口上
}

public void paint(Graphics g) {
Color c=g.getColor();

//刷背景
g.setColor(Color.gray);
g.fillRect(0, 0, COLS*BLOCK_SIZE, ROWS*BLOCK_SIZE);

//画格子
g.setColor(Color.darkGray);
for(int i=1;i<ROWS;i++){
g.drawLine(0, i*BLOCK_SIZE, COLS*BLOCK_SIZE, i*BLOCK_SIZE);
}
for(int i=1;i<COLS;i++){
g.drawLine(i*BLOCK_SIZE, 0, i*BLOCK_SIZE, ROWS*BLOCK_SIZE);
} //画蛇

s.draw(g);
e.draw(g);
g.setColor(c);


}


class PaintThread implements Runnable{ public void run() {
while(true){
repaint();//调用包装类的repaint()方法进行重画-upDate()
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

}

     class KListener extends KeyAdapter{ public void keyPressed(KeyEvent e) {

s.keyPressed(e);

}

public void keyReleased(KeyEvent e) {

}


 }
     
     }
其他的类我先不贴了吧,现在为嘛他连窗口关闭都不响应呢Frame

解决方案 »

  1.   

    上面代码太多,其实就是下面这些,不知道哪里错了,连窗口关闭都不响应了
            public void launch(){
    this.setBounds(200, 50, COLS*BLOCK_SIZE, ROWS*BLOCK_SIZE);
    this.addKeyListener(new KListener());

    this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent arg0) {
    System.exit(0);
    }

    }); new Thread(new PaintThread()).start();
    this.setVisible(true);
    }
      

  2.   

    this.addWindowListener(new WindowAdapter()估计是这个this的问题可以定义一个对象来调用试试,别用无名的
      

  3.   


    可我的这个类就是Frame的子类啊,不是直接给它加监听吗?你是要我给他定义一个Frame的成员变量?   我新手。。
      

  4.   


    可我的这个类就是Frame的子类啊,不是直接给它加监听吗?你是要我给他定义一个Frame的成员变量?   我新手。。
    我的意思是: Yard a=new Yard();用a调用launch。JFrame jf=new JFrame();用jf调用addWindowListener(new WindowAdapter()
      

  5.   


    可我的这个类就是Frame的子类啊,不是直接给它加监听吗?你是要我给他定义一个Frame的成员变量?   我新手。。
    我的意思是: Yard a=new Yard();用a调用launch。JFrame jf=new JFrame();用jf调用addWindowListener(new WindowAdapter()
    当然就别继承了
      

  6.   

    楼上正解,为什么你喜欢用this啊