用swing画了一个坦克,但是坦克动不了,请大神帮忙看看。。
package text1;import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TankGame extends JFrame{
MyPanel mp;
public static void main(String[] args) {
// TODO Auto-generated method stub
TankGame tg=new TankGame();
}
public TankGame()
{
mp=new MyPanel();
this.add(mp);
this.addKeyListener(mp);
this.setSize(400,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
class Tank
{
int x=0,y=0;
int d=0;
public int getD() {
return d;
}
public void setD(int d) {
this.d = 0;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
int speed=1;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Tank(int x,int y)
{
this.x=x;
this.y=y;
}
}
class MyTank extends Tank
{
public MyTank(int x,int y)
{
super(x,y);
}
public void moveUp()
{
y-=speed;
}
public void moveDown()
{
y+=speed;
}
public void moveLeft()
{
x-=speed;
}
public void moveRight()
{
x+=speed;
}
}
class MyPanel extends JPanel implements KeyListener
{
MyTank my=null;
public void paint(Graphics g)
{
my=new MyTank(100,100);
super.paint(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 400,300);
this.drawTank(this.my.getX(),this.my.getY(), g, 0,this.my.getD());
}
public void drawTank(int x,int y,Graphics g,int Type,int d)
{
switch(Type)
{
case 0:
g.setColor(Color.cyan);
break;
case 1:
g.setColor(Color.green);
break;
}
switch(d)
{
case 0:
g.fill3DRect(x, y, 5,20 ,false);
g.fill3DRect(x+15, y,5, 20,false);
g.fill3DRect(x+5, y+4, 10, 12, false);
g.fillOval(x+5, y+5, 7, 8);
g.drawLine(x+9, y+9, x+9, y);
break;
case 1:
g.fill3DRect(x, y, 5,20 ,false);
g.fill3DRect(x+15, y,5, 20,false);
g.fill3DRect(x+5, y+4, 10, 12, false);
g.fillOval(x+5, y+5, 7, 8);
g.drawLine(x+9, y+9, x+9, y);
break;
case 2:
g.fill3DRect(x, y, 5,20 ,false);
g.fill3DRect(x+15, y,5, 20,false);
g.fill3DRect(x+5, y+4, 10, 12, false);
g.fillOval(x+5, y+5, 7, 8);
g.drawLine(x+9, y+9, x+9, y);
break;
case 3:
g.fill3DRect(x, y, 5,20 ,false);
g.fill3DRect(x+15, y,5, 20,false);
g.fill3DRect(x+5, y+4, 10, 12, false);
g.fillOval(x+5, y+5, 7, 8);
g.drawLine(x+9, y+9, x+9, y);
break;
}
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyCode()==KeyEvent.VK_W)
{
this.my.setD(0);
this.my.moveUp();
}else if(e.getKeyCode()==KeyEvent.VK_D)
{
this.my.setD(1);
this.my.moveRight();
}else if(e.getKeyCode()==KeyEvent.VK_S)
{
//System.out.println(e.getKeyChar());
//my.setY(my.getY()+1);
//System.out.println(my.getY());
this.my.setD(2);
this.my.moveDown();
}else if(e.getKeyCode()==KeyEvent.VK_A)
{
this.my.setD(3);
this.my.moveLeft();
}
this.repaint();
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
//System.out.println();
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}