public class TankClient extends Frame {为什么案件没有反应?
Image offScreenImage = null;
int x = 20, y = 30;
public final static int WEITH = 300;
public final static int HEIGHT = 300;
Tank t = new Tank(x,y,true);
public void paint(Graphics g) {
t.draw(g);
}
public void update(Graphics g) {
if (offScreenImage == null) {
offScreenImage = this.createImage(WEITH, HEIGHT);
}
Graphics gOffScreen = offScreenImage.getGraphics();
Color c = gOffScreen.getColor();
gOffScreen.setColor(Color.green);
gOffScreen.fillRect(0, 0, WEITH, HEIGHT);
gOffScreen.setColor(c);
paint(gOffScreen);
g.drawImage(offScreenImage, 0, 0, null);
}
public void launFrame() {
this.setLayout(null);
this.setName("TankWar!");
this.setBackground(Color.green);
this.setBounds(100, 100, WEITH, HEIGHT);
this.addWindowListener(new WindowMoniter());
this .addKeyListener(new KeyMonitor());
this.setResizable(false);
this.setVisible(true);
Runnable r = new PaintThread();
Thread t = new Thread(r);
t.start();
}
class WindowMoniter extends WindowAdapter {
public void windowClosing(WindowEvent e) {
TankClient tc = (TankClient) e.getSource();
tc.setVisible(false);
System.exit(0);
}
}
class KeyMonitor extends KeyAdapter {
public void keyPressed(KeyEvent e) {
//t.keyPress(e);
switch(e.getKeyCode()){
case KeyEvent.VK_UP :
y-=5;
break;
case KeyEvent.VK_DOWN:
y+=5;
break;
case KeyEvent.VK_LEFT :
x-=5;
break;
case KeyEvent.VK_RIGHT :
x+=5;
break;
}
}
}
class PaintThread implements Runnable {
public boolean b = true;
public void run() {
while (b) {
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void stop() {
b = false;
}
}
public static void main(String[] args) {
new TankClient().launFrame();
}
}public class Tank {
public final static int TANKWEITH = 20;
public final static int TANKHEIGHT = 20;
int x;
int y;
boolean b = false;
//Color c = null;
public Tank(int x, int y, boolean b) {
this.x = x;
this.y = y;
this.b = b;
//this.c = c;
}
public void draw(Graphics g){
Color c = g.getColor();
g.setColor(Color.red);
g.fillOval(x, y, TANKWEITH, TANKHEIGHT);
g.setColor(c);
}
}
------解决方案--------------------
你按键更新的是TankClient.x, 画图用的是Tank.x
你去掉TankClient.x, y,在PaintThread里面直接更新t.x, t.y即可