import javax.swing.JFrame;
public class GameFrame extends JFrame {//extends继承
GamePanel gp;
//构建GameFrame方法
public GameFrame(){
this.setSize(500,500);//
this.setTitle("推箱子");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
gp=new GamePanel();
this.add(gp);
}
}
创建一个画板
//构建画布
import java.awt.Graphics;
import javax.swing.JPanel;
//游戏画板
public class GamePanel extends JPanel {
GamePlayer player;
public GamePanel(){
player = new GamePlayer(200,300);
}
//绘制,重写
public void paint(Graphics g){
player.render(g);
}
}
创建一个玩家
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
public class GamePlayer {
Image im;//图片
int x,y;
//构建方法,初始化属性值
public GamePlayer(int x,int y){
//加载图片
ImageIcon icon=new ImageIcon("player.png");
im=icon.getImage();
this.x=x;
this.y=y;
}
//显示图片 渲染
public void render(Graphics g){
g.drawImage(im,x,y,null);
}
//玩家移动
public void movePlayer(int dx,int dy){
x+=dx;
y+=dy;
}
}
运行的Java程序
public class Run {
public static void main(String[] args) {
GameFrame gf=new GameFrame();//调用GameFrame方法
}
}