本例先容了一個常用的編程技巧,就是如何基於MIDP1.0實現屏幕的轉動後果。在MIDP2.0可以借助LayerManager的的“可視窗口”來實現。MIDP1.0通過變更坐標系來實現屏幕的轉動後果,只要借助Graphics.translate()方法。
package com.J2MEdev.translate;
import Javax.microedition.midlet.*;
import Javax.microedition.lcdui.*;
public class Translate extends MIDlet
{
private Display display; // The display
private TranslateCanvas canvas; // Canvas
public Translate()
{
display = Display.getDisplay(this);
canvas = new TranslateCanvas(this);
}
protected void startApp()
{
display.setCurrent( canvas );
}
protected void pauseApp()
{ }
protected void destroyApp( boolean unconditional )
{ }
public void exitMIDlet()
{
destroyApp(true);
notifyDestroyed();
}
}
/*
* TranslateCanvas.Java
*
* Created on 2005年12月1日, 下午10:15
*
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
*/
package com.J2MEdev.translate;
import Javax.microedition.lcdui.Canvas;
import Javax.microedition.lcdui.Command;
import Javax.microedition.lcdui.CommandListener;
import Javax.microedition.lcdui.Displayable;
import Javax.microedition.lcdui.Graphics;
import Javax.microedition.lcdui.Image;
class TranslateCanvas extends Canvas implements CommandListener {
private Command cmExit;
private Translate midlet;
private Image im = null;
private int translatex = 0, translatey = 0;
public TranslateCanvas(Translate midlet) {
this.midlet = midlet;
cmExit = new Command("Exit", Command.EXIT, 1);
addCommand(cmExit);
setCommandListener(this);
try {
//創立圖片
im = Image.createImage("/img.png");
} catch (Java.io.IOException e) {
System.err.println("Unable to locate or read .png file");
}
}
protected void paint(Graphics g) {
if (im != null) {
//清屏
g.setColor(255, 255, 255);
g.fillRect(0, 0, getWidth(), getHeight());
//變換坐標,請參考Graphics.translate(x,y)方法闡明
g.translate(translatex, translatey);
//總是在原點處畫圖片,由於前面變換了坐標 看起來同樣圖片會動起來
g.drawImage(im, 0, 0, Graphics.LEFT | Graphics.TOP);
}
}
public void commandAction(Command c, Displayable d) {
if (c == cmExit)
midlet.exitMIDlet();
}
protected void keyPressed(int keyCode) {
switch (getGameAction(keyCode)) {
case UP:
break;
case DOWN:
break;
case LEFT:
// 圖片右邊緣已經達到屏幕最右邊
System.out.println(translatex);
System.out.println(im.getWidth());
if (translatex + im.getWidth() < getWidth())
return;//直接返回
else
translatex -= 2;
break;
case RIGHT:
// 轉動到圖片的左邊緣
if (translatex>getWidth()-2)
return;
else
translatex += 2;
break;
}
repaint();
}
}