📄 man_canvas.java
字号:
package ch08;
import java.io.IOException;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
public class Man_Canvas
extends GameCanvas
implements Runnable, CommandListener {
//代表程序是否运行的状态
boolean running;
//存储构成动画的各图像帧
Image img;
//代表动画的精灵对象
Sprite sp;
//屏幕宽度
int win_width = getWidth();
//屏幕高度
int win_height = getHeight();
//每帧图像的宽度
int img_width = 114;
//每帧图像的高度
int img_height = 80;
//绘制上下文
Graphics g = getGraphics();
//主MIDlet类实例
Man_MIDlet mm;
/*
3.构造器
*/
public Man_Canvas(Man_MIDlet mm) {
super(true);
this.mm = mm;
Command exitCommand = new Command("退出", Command.EXIT, 0);
addCommand(exitCommand);
setCommandListener(this);
try {
img = Image.createImage("/icons/background/man.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);
sp.setFrame(0);
render(g);
start();
}
/*
4.启动线程
*/
public void start() {
running = true;
Thread t = new Thread(this);
t.start();
}
/*
5.控制进程
*/
public void run() {
while (running) {
GameKeyInput();
}
}
/*
6.响应按键
*/
private void GameKeyInput() {
int KeyState = getKeyStates();
if ( (KeyState & UP_PRESSED) != 0) {
sp.setFrame(0);
render(g);
}
if ( (KeyState & DOWN_PRESSED) != 0) {
sp.setFrame(3);
render(g);
}
if ( (KeyState & LEFT_PRESSED) != 0) {
sp.setFrame(1);
render(g);
}
if ( (KeyState & RIGHT_PRESSED) != 0) {
sp.setFrame(2);
render(g);
}
}
/*
7.实现绘制
*/
private void render(Graphics g) {
g.setColor(0x000000);
g.fillRect(0, 0, win_width, win_height);
sp.paint(g);
flushGraphics();
}
/*
8.结束线程
*/
public void stop() {
running = false;
}
/*
9.响应按钮事件
*/
public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT) {
mm.quitApp();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -