1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
/**
* A canvas that displays the key code corresponding to the key pressed.
*/
public class KeyCodeCanvas extends Canvas {
private KeyCode myMIDlet;
private String myCurrentCode = "none";
private boolean myPoundPressed = false;
/**
* just set a handle back to the MIDlet.
*/
public KeyCodeCanvas(final KeyCode midlet) {
this.myMIDlet = midlet;
}
/**
* Paint the key code corresponding to the key that has been pressed.
*
* Note that this is far from optimized!!!
*/
public void paint(final Graphics g) {
// get the size of the painting region:
int width = getWidth();
int hcenter = width / 2;
int height = getHeight();
// clear the screen by coloring everything white:
g.setColor(0xffffff);
g.fillRect(0, 0, width, height);
// write the instructions at the top in black:
g.setColor(0x000000);
Font font = g.getFont();
int fontHeight = font.getHeight();
g.drawString("to exit", hcenter, 0, Graphics.TOP | Graphics.HCENTER);
g.drawString("press # twice", hcenter, fontHeight + 1, Graphics.TOP | Graphics.HCENTER);
// Now draw the key code number:
g.drawString(this.myCurrentCode, hcenter, 2 * (fontHeight + 1), Graphics.TOP
| Graphics.HCENTER);
}
/**
* Record the keycode.
*/
public void keyPressed(final int keyCode) {
// check for the pound key, and if this is
// the second pound in a row, quit:
if (keyCode == Canvas.KEY_POUND) {
if (this.myPoundPressed) {
this.myMIDlet.quit();
return;
} else {
this.myPoundPressed = true;
}
} else {
this.myPoundPressed = false;
}
// Now set the key code:
this.myCurrentCode = (new Integer(keyCode)).toString();
// Now display it:
repaint();
}
} |
Partager