如何使用netbeans J2ME为不同的移动键(如数字和箭头键)编写代码?

时间:2010-12-11 23:08:32

标签: java-me mobile netbeans6.8 keystore

喜 我想知道在移动设备的键盘上按下了哪个关键用户.....

2 个答案:

答案 0 :(得分:3)

这是示例代码:

package hello;

public class KeyDemoCanvas extends Canvas {
    String eventType = "- Press any!";
    int keyCode;

    public void keyPressed(int keyCode) {
        eventType = "pressed";
        this.keyCode = keyCode;
        repaint();
    }

    public void keyReleased(int keyCode) {
        eventType = "released";
        this.keyCode = keyCode;
        repaint();
    }

    public void keyRepeated(int keyCode) {
        eventType = "repeated";
        this.keyCode = keyCode;
        repaint();
    }

    protected void paint(Graphics g) {
        g.setGrayScale(255);
        g.fillRect(0, 0, getWidth(), getHeight());

        g.setGrayScale(0);

        int y = 0;
        // y = write (g, y, "Key "+ eventType);
        if (keyCode == 0) {
            return;
        }

        y = write(g, y, "Char/Code: " + ((keyCode < 0) ? "N/A" : ""
                + (char) keyCode) + "/" + keyCode);
        y = write(g, y, "Name: " + getKeyName(keyCode));
        String gameAction;
        switch (getGameAction(keyCode)) {
            case LEFT:
                gameAction = "LEFT";
                break;
            case RIGHT:
                gameAction = "RIGHT";
                break;
            case UP:
                gameAction = "UP";
                break;
            case DOWN:
                gameAction = "DOWN";
                break;
            case FIRE:
                gameAction = "FIRE";
                break;
            case GAME_A:
                gameAction = "GAME_A";
                break;
            case GAME_B:
                gameAction = "GAME_B";
                break;
            case GAME_C:
                gameAction = "GAME_C";
                break;
            case GAME_D:
                gameAction = "GAME_D";
                break;
            default:
                gameAction = "N/A";
        }
        write(g, y, "Action: " + gameAction);
    }

    public int write(Graphics g, int y, String s) {
        g.drawString(s, 0, y, Graphics.LEFT | Graphics.TOP);
        return y + g.getFont().getHeight();
    }
}

答案 1 :(得分:0)

使用Canvas.getGameAction(keyCode),然后与Canvas.UP,Canvas.DOWN等进行比较。查看this