为什么我的坦克不能移动呢

liang545621 2011-12-09 08:15:55
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.*;
public class Demo extends JFrame{
MyPanel mp=null;
public static void main(String args[]){
Demo demo=new Demo();
}
public Demo(){
mp=new MyPanel();
this.add(mp);
Thread t=new Thread(mp);
t.start();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setSize(800,700);
}
}
class MyPanel extends JPanel implements KeyListener, Runnable{
int x=250,y=550;
int direct=0;

public void paint(Graphics g) {

super.paint(g);

this.drawTank(getX(),getY(), direct=0, g);

}
public void drawTank(int x,int y,int direct,Graphics g){
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+71,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-4,y+30);
break;
}

}
public void run() {
while(true){
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
}

this.repaint();
}

}
public void keyTyped(KeyEvent e) {

if (e.getKeyCode() == KeyEvent.VK_UP)
{


this.setDirect(0);
this.moveUp();

} else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
{


this.setDirect(1);
this.moveRight();

} else if (e.getKeyCode() == KeyEvent.VK_DOWN)
{

this.setDirect(2);
this.moveDown();
} else if (e.getKeyCode() == KeyEvent.VK_LEFT)
{
this.setDirect(3);
this.moveLeft();
}

}
private void moveLeft() {
x-=10;
}
private void moveDown() {
y+=10;
}
private void moveRight() {
x+=10;
}
private void moveUp() {
y-=10;
}
public int getDirect() {
return direct;
}
public void setDirect(int direct) {
this.direct = direct;
}

public void keyPressed(KeyEvent e) {

}
public void keyReleased(KeyEvent e) {

}
}

...全文
109 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧