日期:2014-05-20 浏览次数:20725 次
package com.Tank;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class MainTank extends JFrame{
/**
*
*/
MyPanel mp=null;
private static final long serialVersionUID = 8654325620366756927L;
public static void main(String[] args){
new MainTank();
}
//构造函数
public MainTank()
{
//创建我的面板
mp=new MyPanel();
//添加我的面板到窗口
this.add(mp);
//注册监听
this.addKeyListener(mp);
//设置窗口的大小
this.setSize(400,300);
//设置窗口标题
this.setTitle("坦克大战");
//初始化窗口的位置
this.setLocation(200,200);
//设置不允许用户调整窗口大小
this.setResizable(false);
//设置关闭窗口并释放内存
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置窗口为可见
this.setVisible(true);
}
}
//我的面板
class MyPanel extends JPanel implements KeyListener
{
MyTank mt=null;
private static final long serialVersionUID = 1L;
//MyPanel的构造函数
public MyPanel()
{
mt=new MyTank(100,100);
}
//重写paint函数
public void paint(Graphics g)
{
super.paint(g);
//设置背景颜色
g.setColor(Color.BLACK);
//设置活动区域
g.fillRect(0, 0, 400, 300);
this.drawTank(this.mt.getX(), this.mt.getY(), g, this.mt.getDirection(), this.mt.getColor());
this.repaint();
}
//画坦克
public void drawTank(int x,int y,Graphics g,int direction,int color)
{
//设置画笔颜色
switch(color)
{
case 0:
g.setColor(Color.YELLOW);
break;
case 1:
g.setColor(Color.RED);
break;
}
switch(direction)
{
//坦克向上
case 0:
g.fill3DRect(x-20, y-20, 10, 40, true);
g.fill3DRect(x+10, y-20, 10, 40, true);
g.fill3DRect(x-10, y-10, 20, 20, true);
g.drawOval(x-5, y-5, 10, 10);
g.drawLine(x, y, x, y-20);
//坦克向右
case 1:
g.fill3DRect(x-20, y-20, 40, 10, true);
g.fill3DRect(x-20, y+10, 40, 10, true);
g.fill3DRect(x-10, y-10, 20, 20, true);
g.drawOval(x-5, y-5, 10, 10);
g.drawLine(x, y, x-20, y);
//坦克向下
case 2:
g.fill3DRect(x-20, y-20, 10, 40, true);
g.fill3DRect(x+10, y-20, 10, 40, true);
g.fill3DRect(x-10, y-10, 20, 20, true);
g.drawOval(x-5, y-5, 10, 10);
g.drawLine(x, y, x, y+20);
//坦克向左
case 3:
g.fill3DRect(x-20, y-20, 40, 10, true);
g.fill3DRect(x-20, y+10, 40, 10, true);
g.fill3DRect(x-10, y-10, 20, 20, true);
g.drawOval(x-5, y-5, 10, 10);
g.drawLine(x, y, x-20, y);
}
}
@Override
//键盘输入并输出
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
//键盘按下
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if(e.getKeyCode()==KeyEvent.VK_W)