?? maincanvas.java
字號:
package com.j2medev.chapter5.game;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
public class MainCanvas extends GameCanvas implements Runnable,CommandListener {
private ScrollScreen midlet = null;
private boolean isPlay;
private long delay; //線程休眠的時間間隔
private int width; // 屏幕寬度
private int height; //屏幕高度
private int scnX, scnY; //可視窗口的左上角坐標
Image backgroundImage;
private Sprite backgroundSprite;
private LayerManager layerManager;
public static final Command exitCommand = new Command("退出",Command.EXIT, 1);
public MainCanvas(ScrollScreen midlet) throws Exception {
super(true);
this.midlet = midlet;
width = getWidth();
height = getHeight();
scnX = 55;
scnY = 20;
delay = 20;
backgroundImage = Image.createImage("/background.png");
backgroundSprite = new Sprite(backgroundImage);
layerManager = new LayerManager();
layerManager.append(backgroundSprite);
this.addCommand(exitCommand);
this.setCommandListener(this);
}
public void start() {
isPlay = true;
//啟動游戲線程
Thread t = new Thread(this);
t.start();
}
public void stop() {
isPlay = false;
}
//游戲主循環
public void run() {
Graphics g = getGraphics();
while (isPlay == true) {
input();
drawScreen(g);
try {
//線程休眠
Thread.sleep(delay);
} catch (InterruptedException ie) {
}
}
}
//處理用戶輸入 支持四個方向的屏幕滾動
private void input() {
int keyStates = getKeyStates();
//根據用戶輸入調整scnX和scnY的值
if ((keyStates & LEFT_PRESSED) != 0) {
if (scnX - 1 > 0)
scnX--;
}else if ((keyStates & RIGHT_PRESSED) != 0) {
if (scnX + 1 + 140 < backgroundImage.getWidth())
scnX++;
}else if((keyStates & UP_PRESSED)!=0){
if(scnY -1 > 0){
scnY--;
}
}else if((keyStates & DOWN_PRESSED)!=0){
if(scnY+1+140<backgroundImage.getHeight()){
scnY++;
}
}
}
private void drawScreen(Graphics g) {
//清屏
g.setColor(0xffffff);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(0x0000ff);
//設置視窗
layerManager.setViewWindow(scnX, scnY, 140, 140);
layerManager.paint(g, 20, 20);
//繪制到主屏幕
flushGraphics();
}
public void commandAction(Command cmd,Displayable displayable){
if(cmd == exitCommand){
//停止線程,銷毀MIDlet
stop();
midlet.exit();
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -