public void keyPressed(int keyCode) { int action = getGameAction(keyCode); switch (action) { case LEFT: left(); leFTPressed = true; break; case RIGHT: right(); rightPressed = true; break; default: break; } repaint(); }
public void keyReleased(int keyCode){ int action = getGameAction(keyCode); switch (action) { case LEFT: leFTPressed = false; buttonPressed = ""; break; case RIGHT: rightPressed = false; buttonPressed = ""; break; default: break; } repaint(); }
這樣我們在重新繪制屏幕的時候就可以根據標記位的狀態進行繪畫了
if (leFTPressed) { left();}if (rightPressed) { right();}筆者給出一個簡略的實例來進行論證,我們制作一個MIDlet,當用戶按下LEFT的時候,J2ME字符串向左側移動,當用戶按下RIGHT的時候,J2ME字符串向右側移動。簡略起見,我沒有處理DOWN和UP的情況。
import Javax.microedition.lcdui.*;import Javax.microedition.midlet.MIDlet;import Javax.microedition.midlet.MIDletStateChangeException; public class KeyActionMIDlet extends MIDlet { private Display display; private MainCanvas mainCanvas; protected void startApp() throws MIDletStateChangeException { display = Display.getDisplay(this); mainCanvas = new MainCanvas(); new
Thread(mainCanvas).start(); display.setCurrent(mainCanvas); } protected void pauseApp() { } protected void destroyApp(boolean arg0) throws MIDletStateChangeException { } } import Javax.microedition.lcdui.*; public class MainCanvas extends Canvas implements Runnable { private String buttonPressed; private boolean leFTPressed; private boolean rightPressed; private int px = getWidth() / 2; public final int py = getHeight() / 2; public MainCanvas() { buttonPressed = " "; } private void left() { if (px >= 0) { px--; } buttonPressed = "LEFT"; repaint(); } private void right() { if (px <= getWidth()
) { px; } buttonPressed = "RIGHT"; repaint(); } public void run() { while (true) { if (leFTPressed) { left(); } if (rightPressed) { right(); } try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } public void paint(Graphics g) { g.setColor(0xFFFFFF); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(0x000000); g.drawString(buttonPressed, 20, 20, Graphics.LEFT | Graphics.TOP); g.drawString("J2ME", px, py, Graphics.HCENTER | Graphics.TOP); } public void keyReleased(int keyCode) { int action = getGameAction(keyCode); switch (action) { case LEFT: leFTPressed = false; buttonPressed = ""; break; case RIGHT: rightPressed = false; buttonPressed = ""; break; default: break; } repaint(); } public void keyPressed(int keyCode) { int action = getGameAction(keyCode); switch (action) { case LEFT: left(); leFTPressed = true; break; case RIGHT: right(); rightPressed = true; break; default: break; } repaint(); } public void keyRepeated(int keyCode) { int action = getGameAction(keyCode); switch (action) { case LEFT: left(); break; case RIGHT: right(); break; default: break; } repaint(); }}