当前位置: 代码迷 >> Java面试 >> 下面的程序哪里出错?为什么小弟我移动W,A,S,D键的时候坦克的方向不改变呢
  详细解决方案

下面的程序哪里出错?为什么小弟我移动W,A,S,D键的时候坦克的方向不改变呢

热度:27   发布时间:2016-04-17 19:36:44.0
下面的程序哪里出错?为什么我移动W,A,S,D键的时候坦克的方向不改变呢?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class Demo extends JFrame {

  Mypanel mp = null;

  public static void main(String[] args) {
  Demo mtg = new Demo();

  }
  public Demo() {
  mp = new Mypanel();
 
  Thread t=new Thread(mp);
  t.start();
  this.add(mp);
   
  this.addKeyListener(mp);
  this.setSize(800,700);
   
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setVisible(true);
  }
}
class Mypanel extends JPanel implements KeyListener ,Runnable{
  
  int x=100;
  int y=100;
 
  int direct=0;
  int speed=1;
  int color;
  public void paint(Graphics g){
super.paint(g);

g.setColor(Color.yellow);
g.fill3DRect(x+11,y+12,50,5,false);
g.fill3DRect(x+11,y+44,50,5,false);
g.setColor(Color.red);
g.fillRect(x+19,y+15,30,30);
g.setColor(Color.BLUE);
g.fillOval(x+23, y+18, 23,23);
g.setColor(Color.black);
g.drawLine(x+34,y+30,x+71,y+30);

}
  public void move(){
Graphics g = null;
switch(direct){
case 0:
g.setColor(Color.yellow);
g.fill3DRect(x+17,y+5,5,50,false);
g.fill3DRect(x+48,y+5,5,50,false);
g.setColor(Color.red);
g.fillRect(x+19,y+15,30,30);
g.setColor(Color.BLUE);
g.fillOval(x+23, y+18, 23,23);
g.setColor(Color.green);
g.drawLine(x+34,y+34,x+34,y-3);
break;
case 1:
g.setColor(Color.yellow);
g.fill3DRect(x+11,y+12,50,5,false);
g.fill3DRect(x+11,y+44,50,5,false);
g.setColor(Color.red);
g.fillRect(x+19,y+15,30,30);
g.setColor(Color.BLUE);
g.fillOval(x+23, y+18, 23,23);
g.setColor(Color.green);
g.drawLine(x+34,y+30,x-4,y+30);
break;
 
case 2:
g.setColor(Color.yellow);
g.fill3DRect(x+17,y+5,5,50,false);
g.fill3DRect(x+48,y+5,5,50,false);
g.setColor(Color.red);
g.fillRect(x+19,y+15,30,30);
g.setColor(Color.BLUE);
g.fillOval(x+23, y+18, 23,23);
g.setColor(Color.green);
g.drawLine(x+34,y+34,x+34,y+71);
break;
case 3:
g.setColor(Color.yellow);
g.fill3DRect(x+11,y+12,50,5,false);
g.fill3DRect(x+11,y+44,50,5,false);
g.setColor(Color.red);
g.fillRect(x+19,y+15,30,30);
g.setColor(Color.BLUE);
g.fillOval(x+23, y+18, 23,23);
g.setColor(Color.green);
g.drawLine(x+34,y+30,x+71,y+30);
break;
}
 
  }

   
  public void keyPressed(KeyEvent e) {
   
   
  if (e.getKeyCode() == KeyEvent.VK_W)
  {  
  this.setdirect(0);
y-=4;
   
  } else if (e.getKeyCode() == KeyEvent.VK_D)
  {
  this.setdirect(1);
  x+=4;

   
  } else if (e.getKeyCode() == KeyEvent.VK_S)
  {
  this.setdirect(2);
y+=4;

 
  } else if (e.getKeyCode() == KeyEvent.VK_A) 
  {
  this.setdirect(3);
x-=4;

  }
  this.repaint(); 
  }


private void setdirect(int i) {

}
public void keyReleased(KeyEvent arg0) {
  }

  public void keyTyped(KeyEvent arg0) {
  相关解决方案