?
Solved

Help with J2ME GameCanvas load

Posted on 2008-11-18
3
Medium Priority
?
2,320 Views
Last Modified: 2013-12-21
Ok, basically what i am doing is creating a game, the game uses a Display manager to display a number of forms and then when the user selects play on the menuscreen it should load the game canvas....however i get an error.

The line it doesnt seem to like, in the Main.java is :   gamescrn = new GameScreen(this);
The error this line gives it:
unreported exception java.lang.exception; must be caught or declared to be thrown

(ignor all the code workings in the GameScreen.java i havnt worked on making ti work  yet)

All i need is to be able to load the game canvas however i cant!  There seems to be some sort of problem between the Main.java and the GameScreen.java


Any help would be much appreciated


*****************  Main.java ***********************
 
mport javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
 
/**
 * @author Gary
 */
public class Main extends MIDlet {
  private Display display; // The display
 
  protected Splash splashscrn; // Canvas to display timer
 
  protected Menu menuscrn; // List to change timer options
  
  protected GameScreen gamescrn; // List to change timer options
  
  
 
 // protected HighScore scorescrn; // Form with gauge to set timer sleep
 
  //protected Instructions instructscrn; // Class to help manage screens
  
  protected DisplayManager displayMgr; // Class to help manage screens
  
 
  public Main()  {  
    display = Display.getDisplay(this);
    splashscrn = new Splash(this);
    menuscrn = new Menu("Menu", List.IMPLICIT, this);
    gamescrn = new GameScreen(this);
 
 
    // Create a display manager object
    displayMgr = new DisplayManager(display, splashscrn);
  }
 
  protected void startApp() {
    // Start with the canvas
    display.setCurrent(splashscrn);
    
    
  }
 
  protected void pauseApp() {
  }
 
  protected void destroyApp(boolean unconditional) {
  }
 
  public void exitMIDlet() {
    destroyApp(true);
    notifyDestroyed();
  }
}
 
 
 
 
 
*************** Menu.java ********************
 
 
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
 
/**
 * @author Gary
 */
 
public class Menu extends List implements CommandListener {
   
    private Main midlet; // Main midlet
    private Command cmquickexit;
    private Command cmselect;
    
    public Menu(String title, int listType, Main midlet) {
 
    super(title, listType);
 
    // Save reference to MIDlet so we can
    // access the display manager class
    this.midlet = midlet;
 
    append("Play", null);
    append("High Scores", null);
    append("Instructions", null);
    append("Exit", null);
    
    cmquickexit = new Command("Exit", Command.EXIT, 1);
    cmselect = new Command("Select", Command.ITEM, 2);
    addCommand(cmquickexit);
    addCommand(cmselect);
    setCommandListener(this);
        
    }
    
    public void commandAction(Command c, Displayable s) {
    // Event generated by the implicit list
    if (c == List.SELECT_COMMAND) {
      switch (getSelectedIndex()) {
      case 0:
        // Push current displayable and show the form
        // to adjust the timer sleep
       midlet.displayMgr.pushDisplayable(midlet.gamescrn);
        
          
        
        break;
 
      /**case 1:
        // Start timer and return to previous displayable
        midlet.cvTimer.startTimer();
        midlet.displayMgr.popDisplayable();
        break;
 
      case 2:
        // Stop timer and return to previous displayable
        midlet.cvTimer.stopTimer();
        midlet.displayMgr.popDisplayable();
        break;*/
      }
    
    }
  }
 
    
}
 
 
 
   
****************** DisplayManager.java ***********************
 
import java.util.Stack;
import javax.microedition.lcdui.*;
 
 
class DisplayManager extends Stack {
  private Display display; // Reference to Display object
 
  private Displayable mainDisplayable; // Main displayable for MIDlet
 
  private Alert alStackError; // Alert for error conditions
 
  /*--------------------------------------------------
   * Display manager constructor
   *-------------------------------------------------*/
  public DisplayManager(Display display, Displayable mainDisplayable) {
    // Only one display object per midlet, this is it
    this.display = display;
    this.mainDisplayable = mainDisplayable;
 
    // Create an alert displayed when an error occurs
    alStackError = new Alert("Displayable Stack Error");
    alStackError.setTimeout(Alert.FOREVER); // Modal
  }
 
  /*--------------------------------------------------
   * Push the current displayable onto stack and set
   * the passed in displayable as active
   *-------------------------------------------------*/
  public void pushDisplayable(Displayable newDisplayable) {
    push(display.getCurrent());
    display.setCurrent(newDisplayable);
  }
 
  /*--------------------------------------------------
   * Return to the main displayable object of MIDlet
   *-------------------------------------------------*/
  public void home() {
    while (elementCount > 1)
      pop();
    display.setCurrent(mainDisplayable);
  }
 
  /*--------------------------------------------------
   * Pop displayable from stack and set as active
   *-------------------------------------------------*/
  public void popDisplayable() {
    // If the stack is not empty, pop next displayable
    if (empty() == false)
      display.setCurrent((Displayable) pop());
    else
      // On error show an alert
      // Once acknowledged, set 'mainDisplayable' as active
      display.setCurrent(alStackError, mainDisplayable);
  }
}
 
 
 
 
***************** GameScreen.java *************************
 
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
 
 
public class GameScreen extends javax.microedition.lcdui.game.GameCanvas {
 
  //---------------------------------------------------------
  //   dimension fields
  //  (constant after initialization)
 
  /**
   * the height of the green region below the ground.
   */
  static final int GROUND_HEIGHT = 32;
 
  /**
   * a screen dimension.
   */
  static final int CORNER_X = 0;
 
  /**
   * a screen dimension.
   */
  static final int CORNER_Y = 0;
 
  /**
   * a screen dimension.
   */
  static int DISP_WIDTH;
 
  /**
   * a screen dimension.
   */
  static int DISP_HEIGHT;
 
  /**
   * a font dimension.
   */
  static int FONT_HEIGHT;
 
  /**
   * the default font.
   */
  static Font FONT;
 
  /**
   * a font dimension.
   */
  static int SCORE_WIDTH;
 
  /**
   * The width of the string that displays the time,
   * saved for placement of time display.
   */
  static int TIME_WIDTH;
 
  /**
   * color constant
   */
  public static final int BLACK = 0;
 
  /**
   * color constant
   */
  public static final int WHITE = 0xffffff;
  
 private Main midlet; // Main midlet
 
 
 
  //---------------------------------------------------------
  //   game object fields
 
  /**
   * a handle to the display.
   */
  private Display myDisplay;
 
  
 
  /**
   * the LayerManager that handles the game graphics.
   */
  private LayerManager layermanager;
 
  /**
   * whether or not the game has ended.
   */
  private boolean GameOver;
 
  /**
   * the player's score.
   */
  private int Score = 0;
 
  /**
   * How many ticks we start with.
   */
  private int intGameTicks = 950;
 
  /**
   * this is saved to determine if the time string needs 
   * to be recomputed.
   */
  private int OldGameTicks = intGameTicks;
 
  /**
   * the number of game ticks that have passed.
   */
  private int GameTicks = OldGameTicks;
 
  /**
   * we save the time string to avoid recreating it 
   * unnecessarily.
   */
  private static String InitialString = "1:00";
 
  /**
   * we save the time string to avoid recreating it 
   * unnecessarily.
   */
  private String TimeString = InitialString;
 
  //-----------------------------------------------------
  //    gets/sets
 
  /**
   * This is called when the game ends.
   */
 
 
  //-----------------------------------------------------
  //    initialization and game state changes
 
  /**
   * Constructor sets the data, performs dimension calculations, 
   * and creates the graphical objects.
   */
  public GameScreen(Main midlet) throws Exception {
    super(false);
 
    this.midlet = midlet;
    //myDisplay = Display.getDisplay(midlet);
    
    // calculate the dimensions
    DISP_WIDTH = getWidth();
    DISP_HEIGHT = getHeight();
    Display disp = Display.getDisplay(midlet);
    if(disp.numColors() < 256) {
      throw(new Exception("game requires 256 shades"));
    }
    /*if((DISP_WIDTH < 150) || (DISP_HEIGHT < 170)) {
      throw(new Exception("Screen too small"));
    }
    if((DISP_WIDTH > 250) || (DISP_HEIGHT > 250)) {
      throw(new Exception("Screen too large"));
    }*/
    FONT = getGraphics().getFont();
    FONT_HEIGHT = FONT.getHeight();
    SCORE_WIDTH = FONT.stringWidth("Score: 000");
    if(layermanager == null) {
      layermanager = new LayerManager(CORNER_X, CORNER_Y + FONT_HEIGHT*2, 
	   DISP_WIDTH, DISP_HEIGHT - FONT_HEIGHT*2 - GROUND_HEIGHT);
    } 
  }
 
  
  void setGameOver() {
    GameOver = true;
    midlet.pauseApp();
  }
    
  /**
   * This is called as soon as the application begins.
   */
  void start() {
    GameOver = false;
    myDisplay.setCurrent(this);
    repaint();
  }
 
  /**
   * sets all variables back to their initial positions.
   */
  void reset() {
    layermanager.reset();
    Score = 0;
    GameOver = false;
    GameTicks = intGameTicks;
    OldGameTicks = intGameTicks;
    repaint();
  }
 
  /**
   * clears the key states.
   */
  void flushKeys() {
    getKeyStates();
  }
 
  /**
   * This version of the game does not deal with what happens
   * when the game is hidden, so hopefully it won't be hidden...
   * see the version in the next chapter for how to implement 
   * hideNotify and showNotify.
   */
  protected void hideNotify() {
  }
 
  /**
   * This version of the game does not deal with what happens
   * when the game is hidden, so hopefully it won't be hidden...
   * see the version in the next chapter for how to implement 
   * hideNotify and showNotify.
   */
  protected void showNotify() {
  }
 
  //-------------------------------------------------------
  //  graphics methods
 
  /**
   * paint the game graphic on the screen.
   */
  public void paint(Graphics g) {
    // clear the screen:
    g.setColor(WHITE);
    g.fillRect(CORNER_X, CORNER_Y, DISP_WIDTH, DISP_HEIGHT);
    // color the grass green
    g.setColor(0, 255, 0);
    g.fillRect(CORNER_X, CORNER_Y + DISP_HEIGHT - GROUND_HEIGHT, 
	       DISP_WIDTH, DISP_HEIGHT);
    // paint the layer manager:
    
      layermanager.paint(g);
   
    // draw the time and score
    g.setColor(BLACK);
    g.setFont(FONT);
    g.drawString("Score: " + Score, 
		 (DISP_WIDTH - SCORE_WIDTH)/2, 
		 DISP_HEIGHT + 5 - GROUND_HEIGHT, g.TOP|g.LEFT);
    // write game over if the game is over
    if(GameOver) {
      //midlet.setNewCommand();
      // clear the top region:
      g.setColor(WHITE);
      g.fillRect(CORNER_X, CORNER_Y, DISP_WIDTH, FONT_HEIGHT*2 + 1);
      int goWidth = FONT.stringWidth("Game Over");
      g.setColor(BLACK);
      g.setFont(FONT);
      g.drawString("Game Over", (DISP_WIDTH - goWidth)/2, 
      		   CORNER_Y + FONT_HEIGHT, g.TOP|g.LEFT);
    }
  }
  
  /**
   * a simple utility to make the number of ticks look like a time...
   */
  public String formatTime() {
    if((GameTicks / 16) + 1 != OldGameTicks) {
      TimeString = "";
      OldGameTicks = (GameTicks / 16) + 1;
      int smallPart = OldGameTicks % 60;
      int bigPart = OldGameTicks / 60;
      TimeString += bigPart + ":";
      if(smallPart / 10 < 1) {
	TimeString += "0";
      }
      TimeString += smallPart;
    }
    return(TimeString);
  }
 
  //-------------------------------------------------------
  //  game movements
 
  /**
   * Tell the layer manager to advance the layers and then 
   * update the display.
   */
  void advance() {
    GameTicks--;
    Score += layermanager.advance(GameTicks);
    if(GameTicks == 0) {
      setGameOver();
    }
    // paint the display
    
      paint(getGraphics());
      flushGraphics();
    
  }
 
  /**
   * Respond to keystrokes.
   */
  public void checkKeys() { 
    if(! GameOver) {
      int keyState = getKeyStates();
      if((keyState & LEFT_PRESSED) != 0) {
	layermanager.setLeft(true);
      } 
      if((keyState & RIGHT_PRESSED) != 0) {
	layermanager.setLeft(false);
      }
      if((keyState & UP_PRESSED) != 0) {
	layermanager.shoot();
      } 
    }
  }
 
}

Open in new window

0
Comment
Question by:Rocker4500
1 Comment
 
LVL 6

Accepted Solution

by:
CodeFish earned 1000 total points
ID: 22991638
You need to initialize your gamescrn in a try/catch block.

{
   gamescrn = new GameCanvas(this);        
}
catch (Exception e)
{
//Exception handling:
System.out.println(e);
}
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month14 days, 4 hours left to enroll

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question