J2ME Canvas KeyPressed
This tutorial is going to show you how to handle keypressed event in J2ME using canvas class. After going through the given example, you will be able to show different output against different keypressed actions. This example illustrates you how to set different game actions on the various keypressed codes that will help you to show different actions on different key clicks.
Find out these game Action used in this example within switch statement:
- case UP: message = "[UP]"; break;
- case DOWN: message = "[DOWN]"; break;
- case LEFT: message = "[LEFT]"; break;
- case RIGHT: message = "[RIGHT]"; break;
- case FIRE: message = "[FIRE]"; break;
- case GAME_A: message = "[LEFT_UP]"; break;
- case GAME_B: message = "[RIGHT_UP]"; break;
- case GAME_C: message = "[LEFT_DOWN]"; break;
- case GAME_D: message = "[RIGHT_DOWN]"; break;
- default: message = ""; break;
And the following methods is used to paint the screen and text:
- int width = getWidth();
- int height = getHeight();
- g.setColor(255, 0, 0);
- g.fillRect(0, 0, width - 1, height - 1);
- g.setColor(0, 0, 255);
- g.drawRect(0, 0, width - 1, height - 1);
- g.setFont(font);
- int x = width / 2;
- int y = height / 2;
- g.drawString(message, x, y, Graphics.BASELINE | Graphics.HCENTER);
The Application is as follows:
Source Code of KeyCanvas.java
import javax.microedition.midlet.*;
|