This J2ME tip illustrates a method of moving small blocks around the screen. In order to do this, you might create a class to represent each block by recording its x and y coordinates and its speeds along the x and y axes. The Canvas paint(...) method then fills its background with an appropriate color and loops over the set of blocks, drawing a filled rectangle for each, using its current coordinates to determine the location of its corresponding rectangle.

class Block {
  int x; // X position
  int y; // Y position
  int xSpeed; // Speed in the X direction
  int ySpeed; // Speed in the Y direction

protected void paint(Graphics g) {

  // Paint with the background color
  g.fillRect(0, 0, width, height);

  // Draw all of the blocks

  synchronized (this) {

    for (int i = 0, count = blocks.length; i < count; i++) {
      g.fillRect(blocks[i].x, blocks[i].y, SIZE, SIZE);

   In order to create movement, you need to start a timer that
   periodically calls a method that updates the coordinates of each 
   block and then causes the Canvas to be painted again. 
public synchronized void moveAllBlocks( ) {

  // Update the positions and speeds of all of the blocks
  for (int i = 0, count = blocks.length; i < count; i++) {
    blocks[i].move( );
    // Request a repaint of the screen
    repaint( );





 Related Tips