import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
//JFrame为事件源
public class MytankGame extends JFrame{
Mypanel mp = null;
public static void main(String[] args) {
MytankGame mg = new MytankGame();
}
//构造方法设置画布属性,定义自己的画框,并将划款添加进JFrame
public MytankGame() {
this.setTitle("坦克旅游");
mp = new Mypanel();
this.add(mp);
//创建监听
this.addKeyListener(mp);
this.setSize(400,300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
//定义自己的画框,并且作为监听者
class Mypanel extends JPanel implements KeyListener{
int x;
int y;
Ltank LL = null;
//构造函数实例化我的坦克
public Mypanel() {
LL = new Ltank(500,500);//坦克的初始坐标
}
//重写父类的画笔方法
public void paint(Graphics g) {
super.paint(g);
//设置地图为黑色
g.fillRect(0, 0, 400, 300);
//坦克显示的属性
this.drawTank(x + 180, y + 130, g, 0, 0);
}
//画出自己的坦克
public void drawTank(int x, int y, Graphics g, int direct, int type) {
switch (type) {
case 0:
g.setColor(Color.cyan);
break;
default:
g.setColor(Color.blue);
break;
}
switch (direct) {
case 0:
g.fill3DRect(x, y, 5, 20, false);
g.fill3DRect(x + 15, y, 5, 20, false);
g.fill3DRect(x + 5, y + 5, 10, 20, false);
g.fillOval(x + 5, y + 10, 10, 10);
g.drawLine(x + 10, y + 15, x + 10, y);
break;
default:
break;
}
}
@Override
public void keyPressed(KeyEvent arg0) {
if(arg0.getKeyCode() == KeyEvent.VK_DOWN) {
y ++;
}
else if(arg0.getKeyCode() == KeyEvent.VK_UP) {
y --;
}
else if(arg0.getKeyCode() == KeyEvent.VK_LEFT) {
x --;
}
else if(arg0.getKeyCode() == KeyEvent.VK_RIGHT) {
x ++;
}
this.repaint();
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
//定义一个坦克类
class Tank {
int x = 0;
int y = 0;
//获取坦克的x,y坐标
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 Ltank extends Tank {
public Ltank(int x, int y) {
super(x,y);
}
}