【Java开源代码栏目提醒】:以下是网学会员为您推荐的Java开源代码-Bomb_Canvas.java,希望本篇文章对您学习有所帮助。
package ch08;
import java.io.IOException;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
public class Bomb_Canvas
extends GameCanvas
implements Runnable, CommandListener {
//代表
程序是否运行的状态
boolean running;
//存储构成动画的各图像帧
Image img;
//代表动画的精灵对象
Sprite sp;
//屏幕宽度
int win_width = getWidth();
//屏幕高度
int win_height = getHeight();
//每帧图像的宽度
int img_width = 65;
//每帧图像的高度
int img_height = 65;
//主MIDlet类实例
Bomb_MIDlet bm;
/*
3.构造器
*/
public Bomb_Canvas(Bomb_MIDlet bm) {
super(true);
this.bm = bm;
Command exitCommand = new Command("退出", Command.EXIT, 0);
addCommand(exitCommand);
setCommandListener(this);
try {
img = Image.createImage("/icons/background/bomb.png");
}
catch (IOException e) {
System.out.println(e.getMessage());
}
sp = new Sprite(img, img_width, img_height);
int x = (win_width - img_width) / 2;
int y = (win_height - img_height) / 2;
sp.setPosition(x, y);
start();
}
/*
4.启动线程
*/
public void start() {
running = true;
Thread t = new Thread(this);
t.start();
}
/*
5.控制进程
*/
public void run() {
Graphics g = getGraphics();
long st = 0, et = 0, diff = 0;
//控制每秒帧数,即动画快慢
int rate = 120;
while (running) {
st = System.currentTimeMillis();
render(g);
et = System.currentTimeMillis();
//避免刷新过快,暂停线程至要求帧数
diff = et - st;
if (diff < rate) {
try {
Thread.sleep(rate - diff);
}
catch (InterruptedException ex) {
stop();
}
}
}
}
/*
6.实现绘制
*/
private void render(Graphics g) {
g.setColor(0x000000);
g.fillRect(0, 0, win_width, win_height);
sp.nextFrame();
sp.paint(g);
flushGraphics();
}
/*
7.结束线程
*/
public void stop() {
running = false;
}
/*
8.响应按钮事件
*/
public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT) {
bm.quitApp();
}
}
}