MIDP3.0

javax.microedition.lcdui.game
Class GameCanvas

java.lang.Object
  extended by javax.microedition.lcdui.Displayable
      extended by javax.microedition.lcdui.Canvas
          extended by javax.microedition.lcdui.game.GameCanvas

public abstract class GameCanvas
extends Canvas

The GameCanvas class provides the basis for a game user interface. In addition to the features inherited from Canvas (commands, input events, etc.) it also provides game-specific capabilities such as an off-screen graphics buffer and the ability to query key status.

A dedicated buffer is created for each GameCanvas instance. Since a unique buffer is provided for each GameCanvas instance, it is preferable to re-use a single GameCanvas instance in the interests of minimizing heap usage. The developer can assume that the contents of this buffer are modified only by calls to the Graphics object(s) obtained from the GameCanvas instance; the contents are not modified by external sources such as other MIDlets or system-level notifications. The buffer is initially filled with white pixels.

The buffer's size is set to the maximum dimensions of the GameCanvas. However, the area that may be flushed is limited by the current dimensions of the GameCanvas (as influenced by the presence of a Ticker, Commands, etc.) when the flush is requested. The current dimensions of the GameCanvas may be obtained by calling getWidth and getHeight.

A game may provide its own thread to run the game loop. A typical loop will check for input, implement the game logic, and then render the updated user interface. The following code illustrates the structure of a typical game loop:

 // Get the Graphics object for the off-screen buffer
 Graphics g = getGraphics();

 while (true) {
  // Check user input and update positions if necessary
  int keyState = getKeyStates();
  if ((keyState & LEFT_PRESSED) != 0) {
      sprite.move(-1, 0);
  } else if ((keyState & RIGHT_PRESSED) != 0) {
      sprite.move(1, 0);
  }

  // Clear the background to white
  g.setColor(0xFFFFFF);
  g.fillRect(0, 0, getWidth(), getHeight());

  // Draw the Sprite
  sprite.paint(g);

  // Flush the off-screen buffer
  flushGraphics();
 }
 

Since:
MIDP 2.0

Field Summary
static int DOWN_PRESSED
          The bit representing the DOWN key.
static int FIRE_PRESSED
          The bit representing the FIRE key.
static int GAME_A_PRESSED
          The bit representing the GAME_A key (may not be supported on all devices).
static int GAME_B_PRESSED
          The bit representing the GAME_B key (may not be supported on all devices).
static int GAME_C_PRESSED
          The bit representing the GAME_C key (may not be supported on all devices).
static int GAME_D_PRESSED
          The bit representing the GAME_D key (may not be supported on all devices).
static int LEFT_PRESSED
          The bit representing the LEFT key.
static int RIGHT_PRESSED
          The bit representing the RIGHT key.
static int UP_PRESSED
          The bit representing the UP key.
 
Fields inherited from class javax.microedition.lcdui.Canvas
ACTIONS_ALL, ACTIONS_NAVIGATION, ACTIONS_NONE, DOWN, FIRE, GAME_A, GAME_B, GAME_C, GAME_D, KEY_BACKSPACE, KEY_DELETE, KEY_DOWN, KEY_ENTER, KEY_ESCAPE, KEY_LEFT, KEY_NUM0, KEY_NUM1, KEY_NUM2, KEY_NUM3, KEY_NUM4, KEY_NUM5, KEY_NUM6, KEY_NUM7, KEY_NUM8, KEY_NUM9, KEY_POUND, KEY_RIGHT, KEY_SELECT, KEY_SPACE, KEY_STAR, KEY_TAB, KEY_UP, LEFT, RIGHT, UP
 
Constructor Summary
protected GameCanvas(boolean suppressKeyEvents)
          Creates a new instance of a GameCanvas.
protected GameCanvas(boolean suppressKeyEvents, boolean preserveBuffer)
          Creates a new instance of a GameCanvas.
 
Method Summary
 void flushGraphics()
          Flushes the off-screen buffer to the display.
 void flushGraphics(int x, int y, int width, int height)
          Flushes the specified region of the off-screen buffer to the display.
protected  Graphics getGraphics()
          Obtains the Graphics object for rendering a GameCanvas.
 int getKeyStates()
          Gets the states of the physical game keys.
 void paint(Graphics g)
          Paints this GameCanvas.
 
Methods inherited from class javax.microedition.lcdui.Canvas
getGameAction, getHeight, getKeyCode, getKeyName, getSoftkeyLabelCoordinates, getWidth, hasPointerEvents, hasPointerMotionEvents, hasRepeatEvents, hideNotify, isDoubleBuffered, keyPressed, keyReleased, keyRepeated, pointerDragged, pointerPressed, pointerReleased, repaint, repaint, serviceRepaints, setFullScreenMode, setKeyListener, setPaintMode, setRequiredActions, showNotify, sizeChanged
 
Methods inherited from class javax.microedition.lcdui.Displayable
addCommand, getCommand, getCommandLayoutPolicy, getCommands, getCurrentDisplay, getMenu, getTicker, getTitle, invalidateCommandLayout, isShown, removeCommand, removeCommandOrMenu, setCommand, setCommandLayoutPolicy, setCommandListener, setMenu, setTicker, setTitle
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

UP_PRESSED

public static final int UP_PRESSED
The bit representing the UP key. This constant has a value of 0x0002 (1 << Canvas.UP).

See Also:
Constant Field Values

DOWN_PRESSED

public static final int DOWN_PRESSED
The bit representing the DOWN key. This constant has a value of 0x0040 (1 << Canvas.DOWN).

See Also:
Constant Field Values

LEFT_PRESSED

public static final int LEFT_PRESSED
The bit representing the LEFT key. This constant has a value of 0x0004 (1 << Canvas.LEFT).

See Also:
Constant Field Values

RIGHT_PRESSED

public static final int RIGHT_PRESSED
The bit representing the RIGHT key. This constant has a value of 0x0020 (1 << Canvas.RIGHT).

See Also:
Constant Field Values

FIRE_PRESSED

public static final int FIRE_PRESSED
The bit representing the FIRE key. This constant has a value of 0x0100 (1 << Canvas.FIRE).

See Also:
Constant Field Values

GAME_A_PRESSED

public static final int GAME_A_PRESSED
The bit representing the GAME_A key (may not be supported on all devices). This constant has a value of 0x0200 (1 << Canvas.GAME_A).

See Also:
Constant Field Values

GAME_B_PRESSED

public static final int GAME_B_PRESSED
The bit representing the GAME_B key (may not be supported on all devices). This constant has a value of 0x0400 (1 << Canvas.GAME_B).

See Also:
Constant Field Values

GAME_C_PRESSED

public static final int GAME_C_PRESSED
The bit representing the GAME_C key (may not be supported on all devices). This constant has a value of 0x0800 (1 << Canvas.GAME_C).

See Also:
Constant Field Values

GAME_D_PRESSED

public static final int GAME_D_PRESSED
The bit representing the GAME_D key (may not be supported on all devices). This constant has a value of 0x1000 (1 << Canvas.GAME_D).

See Also:
Constant Field Values
Constructor Detail

GameCanvas

protected GameCanvas(boolean suppressKeyEvents)
Creates a new instance of a GameCanvas. A new buffer is also created for the GameCanvas and is initially filled with white pixels.

If the developer only needs to query key status using the getKeyStates method, the regular key event mechanism can be suppressed for game keys while this GameCanvas is shown. If not needed by the application, the suppression of key events may improve performance by eliminating unnecessary system calls to keyPressed, keyRepeated and keyReleased methods.

If requested, key event suppression for a given GameCanvas is started when it is shown (i.e. when showNotify is called) and stopped when it is hidden (i.e. when hideNotify is called). Since the showing and hiding of screens is serialized with the event queue, this arrangement ensures that the suppression effects only those key events intended for the corresponding GameCanvas. Thus, if key events are being generated while another screen is still shown, those key events will continue to be queued and dispatched until that screen is hidden and the GameCanvas has replaced it.

Note that key events can be suppressed only for the defined game keys (UP, DOWN, FIRE, etc.); key events are always generated for all other keys.

Parameters:
suppressKeyEvents - true to suppress the regular key event mechanism for game keys, otherwise false.

GameCanvas

protected GameCanvas(boolean suppressKeyEvents,
                     boolean preserveBuffer)
Creates a new instance of a GameCanvas. A new buffer is also created for the GameCanvas and is initially filled with white pixels.

If the developer only needs to query key status using the getKeyStates method, the regular key event mechanism can be suppressed for game keys while this GameCanvas is shown. If not needed by the application, the suppression of key events may improve performance by eliminating unnecessary system calls to keyPressed, keyRepeated and keyReleased methods.

If requested, key event suppression for a given GameCanvas is started when it is shown (i.e. when showNotify is called) and stopped when it is hidden (i.e. when hideNotify is called). Since the showing and hiding of screens is serialized with the event queue, this arrangement ensures that the suppression effects only those key events intended for the corresponding GameCanvas. Thus, if key events are being generated while another screen is still shown, those key events will continue to be queued and dispatched until that screen is hidden and the GameCanvas has replaced it.

Note that key events can be suppressed only for the defined game keys (UP, DOWN, FIRE, etc.); key events are always generated for all other keys.

The developer can control preserving the buffer after flushGraphics call: if preserveBuffer == true then the buffer is preserved (MIDP 2.0 behavior), if preserveBuffer == false then after the flushGraphics call the buffer is undefined. In addition, calling flushGraphics(x,y,width,height) must throw an exception if preserveBuffer == false.

Parameters:
suppressKeyEvents - true to suppress the regular key event mechanism for game keys, otherwise false.
preserveBuffer - true to preserve the buffer after flushGraphics, false to indicate that after flushGraphics call the buffer is undefined.
Since:
MIDP 3.0
See Also:
flushGraphics(), flushGraphics(int, int, int, int)
Method Detail

getGraphics

protected Graphics getGraphics()
Obtains the Graphics object for rendering a GameCanvas. The returned Graphics object renders to the off-screen buffer belonging to this GameCanvas.

Rendering operations do not appear on the display until flushGraphics() is called; flushing the buffer does not change its contents (the pixels are not cleared as a result of the flushing operation).

A new Graphics object is created and returned each time this method is called; therefore, the needed Graphics object(s) should be obtained before the game starts then re-used while the game is running. For each GameCanvas instance, all of the provided graphics objects will render to the same off-screen buffer.

The newly created Graphics object has the following properties:

Returns:
the Graphics object that renders to this GameCanvas' off-screen buffer
See Also:
flushGraphics(), flushGraphics(int, int, int, int)

getKeyStates

public int getKeyStates()
Gets the states of the physical game keys. Each bit in the returned integer represents a specific key on the device. A key's bit will be 1 if the key is currently down or has been pressed at least once since the last time this method was called. The bit will be 0 if the key is currently up and has not been pressed at all since the last time this method was called. This latching behavior ensures that a rapid key press and release will always be caught by the game loop, regardless of how slowly the loop runs.

For example:

 // Get the key state and store it
 int keyState = getKeyStates();
 if ((keyState & LEFT_KEY) != 0) {
  positionX--;
 } else if ((keyState & RIGHT_KEY) != 0) {
  positionX++;
 }
 

Calling this method has the side effect of clearing any latched state. Another call to getKeyStates immediately after a prior call will therefore report the system's best idea of the current state of the keys, the latched bits having been cleared by the first call.

Some devices may not be able to query the keypad hardware directly and therefore, this method may be implemented by monitoring key press and release events instead. Thus the state reported by getKeyStates might lag the actual state of the physical keys since the timeliness of the key information is be subject to the capabilities of each device. Also, some devices may be incapable of detecting simultaneous presses of multiple keys.

This method returns 0 unless the GameCanvas is currently visible as reported by Displayable.isShown(). Upon becoming visible, a GameCanvas will initially indicate that all keys are unpressed (0); if a key is held down while the GameCanvas is being shown, the key must be first released and then pressed in order for the key press to be reported by the GameCanvas.

Returns:
An integer containing the key state information (one bit per key), or 0 if the GameCanvas is not currently shown.
See Also:
UP_PRESSED, DOWN_PRESSED, LEFT_PRESSED, RIGHT_PRESSED, FIRE_PRESSED, GAME_A_PRESSED, GAME_B_PRESSED, GAME_C_PRESSED, GAME_D_PRESSED

paint

public void paint(Graphics g)
Paints this GameCanvas. By default, this method renders the off-screen buffer at (0,0). Rendering of the buffer is subject to the clip region and origin translation of the Graphics object.

Specified by:
paint in class Canvas
Parameters:
g - the Graphics object with which to render the screen.
Throws:
java.lang.NullPointerException - if g is null

flushGraphics

public void flushGraphics(int x,
                          int y,
                          int width,
                          int height)
Flushes the specified region of the off-screen buffer to the display. The contents of the off-screen buffer are not changed as a result of the flush operation. This method does not return until the flush has been completed, so the app may immediately begin to render the next frame to the same buffer once this method returns.

If the specified region extends beyond the current bounds of the GameCanvas, only the intersecting region is flushed. No pixels are flushed if the specified width or height is less than 1.

This method does nothing and returns immediately if the GameCanvas is not currently shown or the flush request cannot be honored because the system is busy.

Parameters:
x - the left edge of the region to be flushed
y - the top edge of the region to be flushed
width - the width of the region to be flushed
height - the height of the region to be flushed
Throws:
java.lang.IllegalStateException - if the preserveBuffer == false in GameCanvas constructor
See Also:
flushGraphics()

flushGraphics

public void flushGraphics()
Flushes the off-screen buffer to the display. The size of the flushed area is equal to the size of the GameCanvas. The contents of the off-screen buffer are not changed as a result of the flush operation. This method does not return until the flush has been completed, so the app may immediately begin to render the next frame to the same buffer once this method returns.

This method does nothing and returns immediately if the GameCanvas is not currently shown or the flush request cannot be honored because the system is busy.

See Also:
flushGraphics(int,int,int,int)

MIDP3.0

Send a comment or suggestionVersion 3.0 of Mobile Information Device Profile Specification
Java is a trademark or registered trademark of Sun Microsystems, Inc. in the US and other countries. Copyright 2002-2009 Motorola Inc. Portions copyright 1993-2002 Sun Microsystems, Inc. and Motorola, Inc. All Rights Reserved.