Code example: Handling display orientation changes for a GameCanvas

The following code example shows how to use the Orientation API to handle the display orientation changes for a GameCanvas.

import com.nokia.mid.ui.orientation.Orientation;
import com.nokia.mid.ui.orientation.OrientationListener;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;

public class GameCanvasOrientationTest extends GameCanvas implements Runnable, OrientationListener{  

  Graphics g;
  boolean canDraw = true;

  /** Used for locking when accessing Graphics object */
  private static Object drawLock = new Object( );

  public GameCanvasOrientationTest( ) {
    super( true );
    g = getGraphics( );
    Orientation.addOrientationListener ( this );
    new Thread(this).start();
  }
    
  /** Orientation listener callback */
  public void displayOrientationChanged( int newDisplayOrientation ){
       
    switch( newDisplayOrientation ){
      case Orientation.ORIENTATION_PORTRAIT:
      case Orientation.ORIENTATION_PORTRAIT_180:
        /** Suspend rendering until orientation has been changed */
        canDraw = false;
        
        /** Change MIDlet UI orientation to portrait */
        synchronized( drawLock ){
          Orientation.setAppOrientation( Orientation.ORIENTATION_PORTRAIT );
        }
        break;

      case Orientation.ORIENTATION_LANDSCAPE:
      case Orientation.ORIENTATION_LANDSCAPE_180:
        /** Suspend rendering until orientation has been changed */
        canDraw = false;
        
        /** Change MIDlet UI orientation to landscape */
        synchronized( drawLock ){
          Orientation.setAppOrientation( Orientation.ORIENTATION_LANDSCAPE );
        }

        break;
    }
  }
  
  /** Thread for UI rendering */
  public void run( ){
    
    while( true){
      
      if ( canDraw == true ){
        render( g );
      }
      try{ Thread.sleep( 500 ); }
      catch( InterruptedException e ){}
    }
  }
  
  /** Java platform will call this when UI orientation has been changed */
  protected void sizeChanged( int w, int h ){
    /** Acquiring new Graphics Object since old is not valid anymore */
    g = getGraphics( );
    canDraw = true;
  }

  public void render( Graphics g ){

    synchronized( drawLock ){
 	     String output = "GameCanvas paint"; 
  	  	  int w = getWidth();
  	  	  int h = getHeight();
  	  	  
		  g.setColor(255,255,255);
		  g.fillRect(0, 0, w, h);
		  
		  g.setColor(255,0,0);
		  g.drawString(output,20, 20, 0);
		  flushGraphics();
    }
  }
}