时间紧张,直接贴代码:
/*
* Function: TankGame 1.0
* Draw Tank
*/
package com.test1;
import javax.swing.*;
import java.awt.*;
public class MyTankGame1 extends JFrame {
MyPanel mp = null;
public static void main(String[] args) {
// TODO 自动生成的方法存根
MyTankGame1 myTankGame1 = new MyTankGame1();
}
public MyTankGame1(){
mp = new MyPanel();
this.add(mp);
this.setSize(400, 300);
this.setVisible(true);
}
}
//My Planel
class MyPanel extends JPanel{
//Define a Tank
Hero hero = null;
public MyPanel(){
hero = new Hero(100, 100);
}
public void paint(Graphics g){
super.paint(g);
// Draw my tank. And then encapsulate them into functions.
g.fillRect(0, 0, 400, 300);
this.drawTank(hero.getX(), hero.getY(), g, 0, 0);
}
public void drawTank(int x, int y, Graphics g, int direct, int type){
// judge type
switch(type){
case 0:
g.setColor(Color.cyan);
break;
case 1:
g.setColor(Color.YELLOW);
break;
}
// judge direction
switch(direct){
case 0:
g.setColor(Color.CYAN);
g.fill3DRect(x, y, 5, 30, false);
// Draw right rect
g.fill3DRect(x + 15, y, 5, 30, false);
// Draw middle rect
g.fillRect(x + 5, y + 5, 10, 20);
// Draw circle
g.setColor(Color.green);
g.fillOval(x + 5, y + 10, 10, 10);
// Draw line
g.drawLine(x + 7, y + 15, x + 10, y);
break;
}
}
}
// Tank Class
class Tank{
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;
}
int x = 0;
int y = 0;
public Tank(int x, int y){
this.x = x ;
this.y = y ;
}
}
class Hero extends Tank{
public Hero(int x, int y){
super(x, y);
}
}
运行效果图: