J2ME: subclassing lcdui.game.Layer

hello,
am trying to subclass from javax.microedition.lcdui.game.Layer (part of Sun's J2ME distribution), which is an abstract class that has no constructors.
i get a compiler error saying "cannot resolve symbol: constructor Layer()".
what am i doing wrong?
this is my non-working code:
import javax.microedition.lcdui.game.*;
public class PlayfieldLayer extends Layer {     
  public void paint(Graphics g) {     }

Better late than never!
The problem is that you are implicitely making a call
to the default constructor Layer() of the super class
javax.microedition.lcdui.game.Layer which does not exist.
The Layer class has one constructor Layer(int width, int height)
but this constructor has the 'package' scope,
which means it is not visible outside package
javax.microedition.lcdui.game.
This is taken from the source code from Sun:
* Creates a new Layer with the specified dimensions.
* This constructor is declared package scope to
* prevent developers from creating Layer subclasses
* By default, a Layer is visible and its upper-left
* corner is positioned at (0,0).
* @param width The width of the layer, in pixels
* @param height The height of the layer, in pixels
Layer(int width, int height) {
setWidthImpl(width);
setHeightImpl(height);
The only solution is to extend TiledLayer or Sprite instead.
It is not a very nice solution because
these classes were obviously not intended for this.
This problem is mentionned in the
Nokia Series 60 Developer Platform 2.0 Specification (p.91):
" 2.1.16.1 Layer-class subclassing
The implementation must have only the package-protected constructor:
Layer(int width, int height)
This leads to the application not being allowed to create
new classes that inherit the Layer abstract class.
This requirement means that the Sprite and TiledLayer classes
are the only classes that directly inherit the Layer class.
Any other classes must be inherited from either
the Sprite or TiledLayer class."
I tried to add my own Layer extension class in package
javax.microedition.lcdui.game, but the compiler will not allow this:
"Cannot create class in system package".
It was worth a try...
What has motivated the decision to
'prevent developers from creating Layer subclasses'?
I think it is probably a last minute decision
that is not consistent with the original intended design.
Why make the Layer abstract class public if it has no
accessible constructor?

Similar Messages

  • Subclass of game.layer in MIDP2.0

    Im trying to create a class that extends from Layer so that I can add it to a LayerManager and several other reasons. Anyway a search on this forum gave me me no solutiuons. Several other programmers have faced the same problem, all these topcis where posted in 2003 and I was hoping that now 1.5 years layers there is a solution to it.
    public class GameLayer extends Layer
          * @param arg0
          * @param arg1
         GameLayer(int arg0, int arg1)
              super(arg0, arg1);
         /** (non-Javadoc)
          * @param arg0
         public void paint(Graphics arg0)
    }

    hmm i think i know what you mean... i think. here is my code so far but im not seeing anything, do i still have to add the the SkidLayer to the LayerManager!?
    public class SkidLayer extends Sprite
         Image m_SkidImage;
          * @param arg0
         public SkidLayer(Image arg0)
              super(arg0);
              m_SkidImage = Image.createImage(2,2);
         public void repaint()
              Graphics g = m_SkidImage.getGraphics();
              g.drawLine(0,0,100,100);
              this.paint(g);
         public void paint()
              repaint();
    }

  • Is there any j2me 3d/2d game editor ?

    is there any game editor for none programmers?
    to create cell phone games?

    Hi,
    I don't know about any targeting JME platform, but there's a nice project called Greenfoot at www.greenfoot.org focusing on IDE for developing 2D games in JSE.

  • Requesting Feedback on J2ME Concept and Game. (InterPhace)

    Folks,
    I've been working on my only game for about a year (part time) and wondered if I could ask for some feedback on the concept.
    InterPhace is a Bluetooth real-time multiplayer puzzle game, which relies on fast reactions, logical thinking and good judgement.
    The first player to hack the InterPhace before time limit expires wins the game and shocks the other player.
    Each time a player wins a round, their rating (score) is increased and these score can be uploaded back onto a Web/WAP site. (http://www.rumblex.com)
    I was hoping someone tell me how they find the user interface, the bluetooth multiplayer and the overall fell of the game.
    There are free downloads of Interphace over at http://www.interphacegame.co.uk and anybody is welcome to try it.
    thanks

    The update seems rather inconsistent. Sometimes I and my shots hang frozen while the enemies keep moving. I think you're using several threads to do the update: don't. All the elements of the game should run at the same speed, and the way to do that is to have them all run by the same update loop.
    I also had problems with the collision detection, particularly with the enemies which homed in on me. Frequently a bullet would go straight through them, close to the centre.
    The sound issues you mention are probably due to the way you load them. Could you post the code which loads a single sound?
    The difficulty curve could IMO be a lot higher, although that depends on your target audience - how experienced they are at gaming, and whether you're after a 3 minute game or a 30 minute game. Arcade shoot-em-ups tend to be rather frantic.
    Also, once you've got the basics settled and are looking to move onto polish, I would say that at the end of a level you should stop spawning enemies but wait until all of the current ones have died or reached the bottom before you stop the game and transition to the inter-level screen.
    For keys, Enter is conventional for jump. Shooting would fit more naturally at the left of the keyboard, where the left hand can handle it. Z, X, S perhaps.
    Finally, since you raise the question of the most appropriate forum for this thread, there's a Java Game Programming forum near the bottom of the list.

  • Problem with Subclassing

    I made a toolbar and subclassed it in another form but when i close the subclassed form and open it again it gives me error that it cannot find the source object.
    What is the proper way of subclassing and changing source module?
    Thanks

    unless there is at least one public or protected
    constructor in the Layer class definition you will not
    be able to subclass it. Since it is abstract and, I
    presume, is actually usable, then it is possible that
    all the constructors are package scoped so only other
    javax.microedition.lcdui.game classes may subclass
    it.
    i recommend scouring the class javadoc to make sure
    how it is to be used.
    dlgrassedlgrasse,
    Sun's javadoc documentation for the class (sadly not available online) says:
    -----8X----
    javax.microedition.lcdui.game
    Class Layer
    java.lang.Object
    |
    +-javax.microedition.lcdui.game.Layer
    Direct Known Subclasses:
    Sprite, TiledLayer
    public abstract class Layer
    extends Object
    A Layer is an abstract class representing a visual element of a game. Each Layer has position (in terms of the upper-left corner of its visual bounds), width, height, and can be made visible or invisible.
    Layer subclasses must implement a paint(Graphics) method so that they can be rendered.
    -----8X----
    Then follow a bunch of method descriptions etc.
    It might be possible that it is in fact not meant to be subclassed, but then why would they go into detail about how to subclass it?
    Also, the ready-made subclasses (Sprite, TiledLayer) are very specialized and thus not always useful, so it is more or less necessary to subclass from Layer.
    strange huh?

  • Problem inherit Layer

    Hello, I'm using th eMIDP 2.0 and i'm trying to extends the abstract Layer class.
    This is the code :
    lass
    BGLayer extends Layer{
         private String name;
         BGLayer(){
              name="BackGroundLayer";
         public void paint(Graphics g){
              g.setColor(255,255,255);
              g.drawRoundRect(20,20,200,200,5,5);
         }//end paint
    }//end class
    when i compile all the project, and error occurred :
    BGLayer.java:12: Layer(int,int) in javax.microedition.lcdui.game.Layer cannot be applied to ()
    []      BGLayer(){
    [] ^
    what's the problem? someone can help me?
    thanks

    i got the same problem with you.
    I think the layer constructor Layer(int, int) is set to package-friendly but not protected.

  • J2me simple game application

    when i select the new Game option Game Screen doesn't work properly.please help me ican't find problem in this program but the project build sucsessfully;
    Midlet class....
    //@Author Lasantha PW
    //Title Java Developer
    //Project Name Simple Midlet Game Application
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    //main midlet
    public class Mario extends MIDlet{
    Display display; //display object
         //private String player,background;
         private Image splashLogo;//splash image
         MainMenuScreen mainMenuScreen;//main menu object
         AboutScreen about;
         boolean isSplash=true; //splash condition
         MarioCanvas marioCanvas;//=new MarioCanvas(this);
         public int noOfLives=3; //player lives
         public Mario(){
              marioCanvas=new MarioCanvas(this);
              about=new AboutScreen(this);
         public void startApp(){
              display=Display.getDisplay(this);
              mainMenuScreen=new MainMenuScreen(this);
              if(isSplash) {
              isSplash=false;
                   try {
                   splashLogo=Image.createImage("/splash.png");
                   new SplashScreen(display,mainMenuScreen,3000,splashLogo);
              catch(Exception ex){}
         public void pauseApp(){
         public void destroyApp(boolean unconditional){
              notifyDestroyed();
         public void mainMenuScreenQuit(){
              destroyApp(true);
         public void mainMenuScreenShow(){
              display.setCurrent(mainMenuScreen);
         public void gameScreenShow(){
              display.setCurrent(marioCanvas);
              marioCanvas.start1();
         public void aboutScreenShow(){
              display.setCurrent(about);
         public void gameScreenQuit(){
              destroyApp(true);
         public Display getDisplay(){
              return display;
    Main Menu class..................................
    //@Author Lasantha PW
    //Title Java Developer
    //Project Name Simple Midlet Game Application
    import javax.microedition.lcdui.*;
    import java.io.IOException;
    public class MainMenuScreen extends List implements CommandListener{
         //create midlet object
         private Mario midlet;
         //create command objects
         private Command exit=new Command("Exit",Command.EXIT,1);
         private Command select=new Command("Select",Command.ITEM,1);
         //private MarioCanvas marioCanvas;
         public MainMenuScreen(Mario midlet){
         super("Tank32",Choice.IMPLICIT);
         this.midlet=midlet;
         append("New Game",null);
         append("Settings",null);
         append("High Score",null);
         append("Help",null);
         append("About",null);
         addCommand(exit);
         addCommand(select);
         setCommandListener(this);
         public void commandAction(Command c,Displayable d){
         if(c==exit){
         midlet.mainMenuScreenQuit();return;
         else if(c==select){
         processMenu();return;
         else{
         processMenu();return;
         private void processMenu(){
         List down=(List)midlet.display.getCurrent();
         switch(down.getSelectedIndex()){
         case 0:scnNewGame();break;
         case 1:scnSettings();break;
         case 2:scnHighScore();break;
         case 3:scnHelp();break;
         case 4:scnAbout();break;
         //private methods for processMenu method
         private void scnNewGame(){     
              midlet.gameScreenShow();     
         private void scnSettings(){}
         private void scnHighScore(){}
         private void scnHelp(){}
         private void scnAbout(){
              midlet.aboutScreenShow();
    GameScreen......................................
    //@Author Lasantha PW
    //Title Java Developer
    //Project Name Simple Midlet Game Application
    import javax.microedition.lcdui.*;
    import javax.microedition.lcdui.game.*;
    import java.util.*;
    public class MarioCanvas extends GameCanvas implements Runnable,CommandListener{
    //command objects
         private Command exit=new Command("Exit",Command.EXIT,1);
         //main midlet
         public Mario midlet;
         public boolean isPlay=true;
         public int dx=4;
         public int dy=4;
         public int BASE=(2*getHeight())/3;
         public Vector allObstacles;
         //Resourse for player
         public Image playerPic;
         Player player;
         public boolean leftTrueRightFalse=true;
         //Power power;
         Image powerPic;
         //resourse for devils
         public Image devilPic;
         Devil devil1;
         LayerManager layerManager;
         public MarioCanvas(Mario midlet){
              super(true);
              this.midlet=midlet;
              addCommand(exit);
              setCommandListener(this);
         public void start1(){
              try{
                   //initialize all image objets
                   playerPic=Image.createImage("/player.png");
                   //powerPic=Image.createImage("/power.png");
                   devilPic =Image.createImage("/Devil.png");
                   //player object
                   Player player=new Player(playerPic,0,BASE-15,this);
                   //obstacle objects
                   devil1=new Devil(devilPic,player,100,BASE-15);
                   //vector object
                   allObstacles=new Vector(0,100);
                   //bullets=new Vector();
                   //add obstacles to the vector
                   allObstacles.addElement(((Sprite)devil1));
                   //set all obstacles to player
                   player.setAllObstacles(allObstacles);          
                   layerManager=new LayerManager();
                   //append to the layermanager     
                   layerManager.append(player);
                   layerManager.append(devil1);
                   Thread t=new Thread(this);
                   t.start();
              catch(Exception ex){
                   System.err.println("Error"+ex);
         public void run(){
              while(isPlay){
                   userInput();
                   verifyGameState();
                   updateBackground();
                   updateGameScreen();
              try{Thread.currentThread().sleep(15);}
              catch(Exception ex){}                    
         public void updateBackground(){
              Graphics g=getGraphics();
              g.setColor(0,124,0);
              g.fillRect(0,0,this.getWidth(),this.getHeight());
              g.setColor(0,224,0);
              g.fillRect(0,BASE+30,this.getWidth(),80);
         public void updateGameScreen(){
              Graphics g=this.getGraphics();
              if(player.Y<BASE){
              //player.incrementY(dy);
              else if(player.Y>BASE){
              player.Y=BASE;
              player.setY(BASE);}
              g.setColor(0,244,0);
              g.fillRect(0,BASE+30,1500,80);
              layerManager.paint(g,0,0);
              flushGraphics();
         public void userInput(){
              if((this.getKeyStates()&LEFT_PRESSED)!=0){}
              if((this.getKeyStates()&RIGHT_PRESSED)!=0){}
              if((this.getKeyStates()&FIRE_PRESSED)!=0){}     
         public void verifyGameState(){
         public void commandAction(Command c,Displayable d){
              if(c==exit){
                   midlet.gameScreenQuit();
    }

    pwlasantha wrote:
    when i select the new Game option Game Screen doesn't work properly.please help me ican't find problem in this program but the project build sucsessfully;
    ...If it "doesn't work properly", there's "something going wrong".

  • Tiled Layer - NullPointerException

    Hi, getting a small problem when initialising a tiled layer object. When I initialise the TiledLayer object "backgroundLayer", it throws a NullPointerException, and the Catch "System.out.println("")" is also being displayed, stating it cannot find the image. The image itself is in the "src" folder for the game, it's a 31 by 61 PNG file named "levelOne.png". I can't figure out why the image isn't being displayed, please help lol.
    Thanks.
    import javax.microedition.lcdui.*;
    import javax.microedition.lcdui.game.*;
    import javax.microedition.lcdui.Image.*;
    import javax.microedition.media.*;
    import javax.microedition.io.*;
    import javax.bluetooth.*;
    import java.util.*;
    import java.io.*;
    public class Engine extends GameCanvas implements Runnable {
        public Thread thread;
        public LayerManager layerManager;
        public TiledLayer backgroundLayer;
        public Image backgroundImage;
        boolean isRunning;
        public Engine (AwakeMIDlet m) {
            super(true);
            try {
                backgroundImage = Image.createImage("/levelOne.png");
            catch (IOException ioe) {
                System.out.println("Image unable to be displayed.");
            layerManager = new LayerManager();
            backgroundLayer = new TiledLayer(5, 5, backgroundImage, 31, 31);
            isRunning = true;
            int[] cells = {
                1, 2, 2, 2, 1, // Top
                1, 0, 0, 0, 1,
                1, 0, 0, 0, 1,
                1, 0, 0, 0, 1,
                2, 1, 1, 1, 2
            for (int i = 0; i < cells.length; i++) {
                int column = i % 5;
                int row = (i - column)/5;
                backgroundLayer.setCell(column, row, cells);
    backgroundLayer.setPosition(0, 0);
    layerManager.append(backgroundLayer);
    public void go() {
    thread = new Thread(this);
    thread.start();
    public void run() {
    Graphics g = getGraphics();
    while(isRunning = true) {

    If you're using NetBeans, the path of the image file should be relative to the project root. If as you say the image file is in the "src" folder that should bebackgroundImage = Image.createImage("/src/levelOne.png");Other IDEs may treat the path differently.
    db

  • Switching in-between game levels

    I'm having problems trying to invoke my setMap method in my game canvas class. It works fine when I use it in my tile layer class after removing the default case in the switch statement, but for some reason, it doesn't switch the level in my game's thread. Could it be that I have to call the garbage collector, then the method, or will I have to create a seperate array that merges my current map with the next level? I've searched and asked everywhere and found absolutely nothing.
    package de.enough.polish.example;
    import javax.microedition.lcdui.game.*;
    import javax.microedition.lcdui.*;
    public class TheLevels {
        private static final int [][] level1={
        {0,0,0,0,0,0,0,9,10,0,0,0,0,0,0,0,0,0},
        {6,6,6,6,6,6,6,7,8,5,5,5,5,5,5,5,5,5},
        {1,1,1,1,1,1,2,3,3,4,1,1,1,1,1,1,1,1}
        private static final int [][] level2={
        {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
        {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
        {2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2}
        private int TILE_WIDTH=64;
        private int TILE_HEIGHT=64;
        private int TILE_NUM_ROW = 3;
        private int TILE_NUM_COL = 18;
        private int [][] currentLevel;
        private TiledLayer theBoard;
        private int screenHeight;
        private int bgColor;
        /** Creates a new instance of TheLevels */
        public TheLevels(int screenHeight) throws Exception {
            this.screenHeight = screenHeight;
            setMap(1);
        public void setMap(int level) throws Exception{
            Image tileImages = null;
            switch (level){
                case 1:  tileImages = Image.createImage("/street.png");
                          currentLevel = level1;
                          //groundColor = 0xF8DDBE;
                          break;
                case 2:  tileImages = Image.createImage("/grass.png");
                            currentLevel = level2;
                default: tileImages = Image.createImage("/street.png");
                          currentLevel = level1;
                          //groundColor = 0xF8DDBE;
                          break;
                theBoard = new TiledLayer(TILE_NUM_COL,TILE_NUM_ROW, tileImages, TILE_WIDTH, TILE_HEIGHT);
                for (int rows=0; rows<TILE_NUM_ROW; rows++) {
                  for (int columns=0; columns<TILE_NUM_COL; columns++) {
                    theBoard.setCell(columns,rows,currentLevel[rows][columns]);
            public TiledLayer getBackground(){
                return theBoard;
            public int getBackgroundColor() {
                return bgColor;
            public int getWidth(){
                return theBoard.getWidth();
            public int getHeight(){
                return theBoard.getHeight();
    }

    I would connect each device to a power source, and then reset them by holding the power button and the home button until they turn off.
    If it keeps happening, I would put the devices in recovery mode and restore them with iTunes.
    This article will help with that if needed:
    iOS: Unable to update or restore
    http://support.apple.com/kb/HT1808

  • WTK 2.1 J2ME : Compatible phone list ?

    Hi,
    I build my first JAVA J2ME soft, I would like to know for which phones it could be compatible ?
    How can I get this information ( I used only the emulator Sun..) ?
    I know I could get all phones and test !! ;-) where is Santa !!
    If one constructor is interested to provide me with phones in order to finish my tests :-)
    Thanks !

    Correct - there are different versions of the MIDP api JARs for MIDP1.0 and MIDP2.0. For example, javax.microedition.lcdui.game package only exists in MIDP2.0, so if you use classes from this package in your software, it will not be able to run on MIDP1.0 hardware.
    Most devices are MIDP1.0 at the moment, but MIDP2.0 phone are becoming increasingly available.
    There are a few other things you should bear in mind when developing for phones. Firstly, most phones have a maximum JAR file size - make sure your packaged JAR size does not exceed this, else it will not install.
    Secondly, phones have a maximum heap size - my current Nokia has 200KB. This limits the number of objects you can instantiate, so you have to be careful to garbage collect and reuse where possible.
    Have fun!
    Phil

  • Exchanged J2ME game3D

    Hi, lucky day, I leaning about programming game 3D with J2ME, by load file m3g (export by blender). I look JRS and API Graphics3D, but when I try write code of example and build then don't run. I don't understand, too. I think I don't understand algorithms of it. Hope will be exchanged with others.

    Thank you!
    I know my English is awful (bad), I will try, this is the first for me in the forum of international. You looking my code:
    package Skywar.m3g;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import java.lang.Object;
    import javax.microedition.m3g.*;
    import java.util.Timer;
    import java.util.TimerTask;
    import javax.microedition.lcdui.game.*;
    * @author BDPL
    public class SkywarCanvas extends Canvas implements Runnable {
    private static final String sk = "/sk.m3g";
    // public static final int mb_ID = 2;
    public SkywarCanvas mCanvas;
    public Camera mCamera;
    public World mWorld;
    public Graphics3D g3d;
    public Group root;
    public boolean isRunning = true; //truy van canvas
    //private TimerTask mRefreshTask = null;
    //private Timer mRefreshTimer = new Timer();//thoi gian lam tuoi
    private static final float g3dx = 15.f;//toa do truc x cua doi tuong tren man hinh 2D
    private static final float g3dy = 0.25f;//toa do truc y cua doi tuong tren man hinh 2D
    //private AnimationController animSky = null;
    private int oldg3dX = 1; //toa do cu theo truc X
    private int oldg3dY = 1; //toa do cu theo truc Y
    private int width = getWidth();//chieu cao cua canvas
    private int height = getHeight();//chieu rong cua canvas
    //private boolean isplay;//kiem tra vong lap sprite
    //private long delay;
    // private int sprx, spry;//toa do hien tai cua sprite
    //bat dau canva
    public void showNotify(int sleeptime){
    init();
    //tao ra mot luong chay game
    Thread thr = new Thread();
    isRunning = true;
    thr.start();
    //dung canvas
    public void hideNotify(){
    isRunning = false;
    //khoi tao doi tuong vaf load doi tuong
    protected void init(){
    g3d = Graphics3D.getInstance();
    try{
    Object3D[] object = Loader.load("/sk.m3g");
    mWorld = (World) object[0];
    Camera mC = mWorld.getActiveCamera();
    float aspect = (float) getWidth()/(float) getHeight();
    mC.setPerspective(60.f, aspect, 1.0f, 1000.0f);
    } catch (Exception e){
    e.printStackTrace();
    /* public void getObject(){
    root = (Group)mWorld.find(mb_ID);
    //bao gom cac hoat canh va mot so doi tuong khac ve thoi gian
    public void run(){
    while (isRunning){
    if ((mWorld != null)&& (g3d != null)){
    int sleep = (int)System.currentTimeMillis();
    showNotify(sleep);
    //co the goi boi canh ra roi moi den doi tuong
    repaint();
    try {
    Thread.sleep(1000);
    } catch (Exception e){}
    protected void paint(Graphics g){
    //cat 1 hinh chu nhat de hien thi
    if ((g.getClipWidth() != width) || (g.getClipHeight() != height) ||
    (g.getClipX() != oldg3dX) || (g.getClipY() != oldg3dY)) {
    g.setColor(0x00);
    g.fillRect(0, 0, mCanvas.getWidth(), mCanvas.getHeight());
    // render the 3D scene
    if ((g3d != null) && (mWorld != null)) {
    g3d.bindTarget(g);
    g3d.setViewport(oldg3dX, oldg3dY, width, height);
    g3d.render(mWorld);
    g3d.releaseTarget();
    public Displayable getD() {
    return(this);
    //thu tuc dieu khien doi tuong
    public void keyPressd(int keyCode){
    int gameAction = getGameAction(keyCode);
    if(gameAction == Canvas.FIRE){
    Transform transform = new Transform();
    mCamera.getCompositeTransform(transform);
    float[] direction = {0.0f, 0.0f, g3dy, 0.0f};
    transform.transform(direction);
    mWorld.translate(direction[0], direction[1], direction[2]);
    } else {
    switch(gameAction){
    case Canvas.LEFT:
    mCamera.postRotate(g3dx, 0.0f, 1.0f, 0.0f);
    break;
    case Canvas.RIGHT:
    mCamera.postRotate(g3dx, 0.0f, -1.0f, 0.0f);
    break;
    case Canvas.UP:
    mCamera.postRotate(g3dx, 1.0f, 0.0f, 0.0f);
    break;
    case Canvas.DOWN:
    mCamera.postRotate(g3dx, -1.0f, 0.0f, 0.0f);
    break;
    default:
    break;
    repaint();
    public SkywarCanvas(){
    * duoc su dung nham lam tuoi che do cho canvas moi khi chay
    private class RefreshTask extends TimerTask{
    public void run(){
    mCanvas.repaint();
    /* public String name() {
    return("Binary World");
    package Skywar.m3g;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.game.*;
    import javax.microedition.lcdui.*;
    import java.lang.Object;
    import javax.microedition.m3g.*;
    import javax.microedition.io.file.*;
    import javax.microedition.io.*;
    import javax.microedition.midlet.MIDletStateChangeException;
    import javax.microedition.m3g.*;
    import javax.microedition.m3g.Object3D;
    import java.util.*;
    * @author BDPL
    public class SkyMain extends MIDlet implements CommandListener{
    private Command mExit = new Command("Exit", Command.EXIT, 1);
    private Command mGo = new Command("Go", Command.SCREEN, 1);
    private Command mPause = new Command("Pause", Command.SCREEN, 2);
    private SkywarCanvas mCanvas;
    private SkyMain mSky;
    private Display mDisplay;
    private boolean gameOver = false;
    private Graphics3D g3d;
    private World mWorld;
    public SkyMain(){
    super();
    mDisplay = Display.getDisplay(this);
    public void startApp() throws MIDletStateChangeException {
    mDisplay.setCurrent(mCanvas);
    mCanvas.addCommand(mExit);
    mCanvas.addCommand(mGo);
    mCanvas.addCommand(mPause);
    mCanvas.setCommandListener(this);
    mCanvas.repaint();
    public void pauseApp() {
    mWorld = null;
    public void destroyApp(boolean unconditional) {
    public void commandAction(Command c, Displayable s){
    if(c == mExit){
    try{
    destroyApp(false);
    notifyDestroyed();
    }catch (Exception e){
    e.printStackTrace();
    //an go
    private void setGoCommand() {
    mCanvas.removeCommand(mPause);
    mCanvas.addCommand(mGo);
    //an pause
    private void setPauseCommand() {
    mCanvas.removeCommand(mGo);
    mCanvas.addCommand(mPause);
    Reality, when I build, error code " can not found MIDletM3G". I thing I write algorithms is wrong.

  • Need help on mobile gaming development basic  {working the game main menu}

    package Assignment1;
    import java.io.IOException;
    import java.util.Random;
    import javax.microedition.lcdui.Canvas;
    import javax.microedition.lcdui.Display;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.lcdui.game.Sprite;
    public class a1Canvas extends GameCanvas implements Runnable{
        private Display display;
        private Sprite ufoSprite;
        private Image backgroundImage;
        private long frameDelay;
        private int ufoX;
        private int ufoY;
        private int ufoXDir;
        private int ufoXSpeed;
        private int ufoYSpeed;
        private Random rand;
        private Sprite[] roidSprite = new Sprite[3];
        private boolean gameOverState;
        //constructor
        public a1Canvas(Display display){
            super(true);
            this.display = display;
            frameDelay = 33;
            gameOverState = false;
        public void start(){
            display.setCurrent(this);
            //start the animation thread
             rand = new Random();     // Initialize the random number generator
             ufoXSpeed = ufoYSpeed = 0; // Initialize the UFO and roids sprites
            try {
                backgroundImage = Image.createImage("/background.jpg");
                ufoSprite = new Sprite(Image.createImage("/ufo.png"));
                //initialise sprite at middle of screen
                ufoSprite.setRefPixelPosition(25,25);
                ufoX = (int)(0.5 * (getWidth()- ufoSprite.getWidth()));
                ufoY = (int)(0.5 * (getHeight()- ufoSprite.getHeight()));
                ufoSprite.setPosition(ufoX, ufoY);
                Image img = Image.createImage("/Roid.png");
                roidSprite[0] = new Sprite(img, 42, 35);   //create 1st frame-animated asteroid sprite
                roidSprite[1] = new Sprite(img, 42, 35);
                roidSprite[2] = new Sprite(img, 42, 35);
            } catch (IOException ex) {
                System.err.println("Failed to load images");
            Thread t = new Thread(this);
            t.start();
        public void run() {
            while (!gameOverState){
                update();
                draw(getGraphics());
                try{
                    Thread.sleep(frameDelay);
                }catch(InterruptedException ie){}
            gotoMainMenu(getGraphics());
        private void draw(Graphics graphics) {
            //clear background to black
            graphics.setColor(0, 0, 0);
            graphics.fillRect(0, 0, getWidth(), getHeight());
            //draw the background
            graphics.drawImage(backgroundImage, getWidth()/2, getHeight()/2, Graphics.HCENTER | Graphics.VCENTER);
            ufoSprite.paint(graphics);
            for(int i=0;i<3;i++){
                roidSprite.paint(graphics);
    flushGraphics(); //flush graphics from offscreen to on screen
    private void update() {
    // Process user input to control the UFO speed
    int keyState = getKeyStates();
    if ( (keyState & LEFT_PRESSED) != 0 )
    ufoXSpeed--;
    else if ( (keyState & RIGHT_PRESSED) != 0 )
    ufoXSpeed++;
    if ( (keyState & UP_PRESSED) != 0 )
    ufoYSpeed--;
    else if ( (keyState & DOWN_PRESSED) != 0 )
    ufoYSpeed++;
    ufoXSpeed = Math.min(Math.max(ufoXSpeed, -8), 8);
    ufoYSpeed = Math.min(Math.max(ufoYSpeed, -8), 8);
    ufoSprite.move(ufoXSpeed, ufoYSpeed); // Move the UFO sprite
    checkBounds(ufoSprite); // Wrap UFO sprite around the screen
    // Update the roid sprites
    for (int i = 0; i < 3; i++) {
    roidSprite[i].move(i + 1, 1 - i); // Move the roid sprites
    checkBounds(roidSprite[i]); // Wrap asteroid sprite around the screen
    // Increment the frames of the roid sprites; 1st and 3rd asteroids spin in opposite direction as 2nd
    if (i == 1)
              roidSprite[i].prevFrame();
    else
              roidSprite[i].nextFrame();
    // Check for a collision between the UFO and roids
    if ( ufoSprite.collidesWith(roidSprite[i], true) ) {
    System.out.println("Game Over !");
    gameOverState = true;
    }//if
    }//for
    public void stop(){
    gameOverState = true;
    private void checkBounds(Sprite sprite) {
    // Wrap the sprite around the screen if necessary
    if (sprite.getX() < -sprite.getWidth())
         sprite.setPosition(getWidth(), sprite.getY());
    else if (sprite.getX() > getWidth())
         sprite.setPosition(-sprite.getWidth(), sprite.getY());
    if (sprite.getY() < -sprite.getHeight())
         sprite.setPosition(sprite.getX(), getHeight());
    else if (sprite.getY() > getHeight())
         sprite.setPosition(sprite.getX(), -sprite.getHeight());
    private void gotoMainMenu(Graphics graphics) {
    graphics.setColor(0, 0, 0);
    graphics.fillRect(0, 0, getWidth(), getHeight());
    graphics.setColor(255, 0, 0);
    graphics.drawRect(0, 0, getWidth()-1, getHeight()-1);
    graphics.setColor(255, 255, 255);
    graphics.drawString("GAME NAME", getWidth()/2 -50, 30, Graphics.LEFT | Graphics.TOP);
    graphics.setColor(255, 0, 0);
    graphics.drawString("Main Menu", getWidth()/2 -50, 50, Graphics.LEFT | Graphics.TOP);
    graphics.setColor(0, 255, 0);
    graphics.drawString("Start Game", getWidth()/2 , 80, Graphics.LEFT | Graphics.TOP);
    graphics.drawString("Instructions", getWidth()/2 , 110, Graphics.LEFT | Graphics.TOP);
    flushGraphics();
    int keyState = getKeyStates();
    if ( (keyState & FIRE_PRESSED) != 0 ){
    System.out.println("game start");
    gameOverState = false;
    The problem i am facing is :
    the FIRE button is not functioning, i put a system.out.println and it didnt print.
    i am unsure whether i put the key input listener at the correct function
    this button is supposed to start the game again.
    What i want to do :
    i want to display the main menu when i launched the game
    when game is over, it will display back to the main menu again
    when i press the fire button it will play the game again.
    i hope someone can help me on this :)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    kdoom wrote:
    The problem i am facing is :
    the FIRE button is not functioning, i put a system.out.println and it didnt print.
    i am unsure whether i put the key input listener at the correct function
    this button is supposed to start the game again.
    What i want to do :
    i want to display the main menu when i launched the game
    when game is over, it will display back to the main menu again
    when i press the fire button it will play the game again.
    i hope someone can help me on this :)You didn't have to create a whole new post just for the formatted code, silly. You could have just replied in the old thread. Anyway:
    Step through the program and think about what each line is doing. Most importantly:
        public void run() {
            while (!gameOverState){
                update();
                draw(getGraphics());
                try{
                    Thread.sleep(frameDelay);
                }catch(InterruptedException ie){}
            gotoMainMenu(getGraphics());
        }This says that while the game is being played, update( ), then draw( ). When the game is over, call gotoMainMenu( ).
       private void gotoMainMenu(Graphics graphics) {
            //do a bunch of graphics stuff
            int keyState = getKeyStates();
            if ( (keyState & FIRE_PRESSED) != 0 ){
                System.out.println("game start");
                gameOverState = false;
        }This says to do a bunch of graphics stuff, and then to check the key states. If fire is being pressed, print something out and set gameOverState to false. This check only happens once. When the state is being checked, most likely the user will not be pressing any keys, so the code is done.
    Also, simply setting the gameOverState variable to false outside of the loop you use it in won't do anything. For example:
    boolean doLoop = true;
    int count = 0;
    while(doLoop){
       count++;
       if(count > 10){
          doLoop = false;
    doLoop = true;Would you expect that second doLoop = true to start the while loop over?

  • Game with layers

    Hi, I'm trying to develop a little game. It's a simple 3/4
    view (top-down view isometric) car game (quite classic I know). But
    what I'm looking for is how to add different layers in my game. I
    mean when the car is under a tree, then the car should disappear
    (now it runs over the tree), same with a tunnel, the car should not
    be seen.
    How to manage this ? I only need 2 layers, the game layer
    (street, grass) and the top layer (trees, tunnels,...)
    Thanks for help.

    Car is on which layer?
    Just shift your layers and check if the car is going under
    the tree...

  • Import J2ME source into Java ME SDK 3.0

    Hi,
    Im new to Java ME.
    The internet has lots of J2ME examples for games(but none for Java ME SDK 3.0), and im trying to import these into Java ME SDK 3.0 . I click on new project and select 'Import Wireless Toolkit Project', but it doesn't detect a project. Ive tried this with several popular J2ME samples.
    Anyone know how to do this right, so I can import J2ME projects into Java ME SDK 3.0 completely, with classes, packages and resources intact?
    I tried making a new project, and then copying the files into the relevant directories too. All the classes show up in the SDK, but on running the program no app is displayed in the emulator.

    Don't double post. I've removed the thread you started in the Java Programming forum with the identically same question.
    db

  • J2ME 3D rendering problem

    Hi,
    I'm experimenting with 3D which is available in the WTK22, and have come accross an annoying problem. I can create a mesh and convert it to a Node no problem, however these are my issues:
    1). The mesh can be converted to an Object3D, but then won't cast to a world.
    myWorld = (World) myObject
    results in a cast error.
    2). So, I tried using the Graphics3D render method which just renders nodes, but using
    g3d.render(MYOBJECT,null);
    results in an IllegalStateException.
    It seems therefore that the mesh is incorrect, but it's straight from the examples. I have attached the code in the hope it will be usefull, please ignore all of the variables at the top :P
    ThreeD.java:
    package Game;
    import java.io.*;
    import java.util.*;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.lcdui.game.*;
    import javax.microedition.media.*;
    import javax.microedition.media.control.*;
    import javax.microedition.m3g.*;
    public class ThreeD extends MIDlet implements CommandListener
         LayerManager layers = new LayerManager();
         TiledLayer tiles;
         Calendar cal = Calendar.getInstance();
         Date date;
         Alert alert;
         int LastKey = 0;
         int GameTemp = 0;
         Random generator = new Random( System.currentTimeMillis() );
         Display display;
         public Graphics g;
         VideoControl videoControl;
         Graphics3D g3d;
         Background background = new Background();
         Fog fog;
         Image2D image2D;
         Texture2D texture2D;
         Transform tTransform = new Transform();
         World MYWORLD = new World();
         Node MYOBJECT;
         // Rem This is called when your application starts up, use it for setting variables etc.
         Canvas MYCANVAS;
         Timer timer0;
         public ThreeD()
              CUBE MYOBJECTa = new CUBE();
              MYOBJECT = (Node) MYOBJECTa.getObject();
         // Rem This is your main function, your application will run from this.
         public void startApp()
              display = Display.getDisplay(this);
              // Rem This is the main canvas, you can create more.
              MYCANVAS = new Canvas()
                   protected void showNotify(){ startTimer(); repaint(); }
                   protected void hideNotify(){ timer0.cancel(); }
                   // Rem This is where the main drawing operations are done.
                   protected void paint(Graphics b)
                        g = b;
                        // Rem This must be performed for any 3D commands to work
                        g3d = Graphics3D.getInstance();
                        g3d.bindTarget(b);
                        // Rem Clear our 3D viewport
                        background.setColor(0xf54588);
                        g3d.clear(background);
                        if(g3d == null){ System.out.println("Cannot get device"); }
                        if(MYWORLD == null){ System.out.println("World is null!"); }
                        // Rem Render the world
                        //g3d.render(MYWORLD);
                        g3d.render(MYOBJECT,null);
                        // Rem Close the 3D command set
                        g3d.releaseTarget();
                   // Rem This is called when a key is pressed.
                   protected void keyPressed(int keyCode)
                        date = new Date(); LastKey = Math.abs((int) date.getTime());
                        // Rem Update the screen.
                        repaint();
                   // Rem This is a loop with a sync rate of 1 second (1000 milli seconds)
                   private void startTimer()
                        timer0 = new Timer();
                        TimerTask updateTask = new TimerTask()
                             public void run()
                                  // Rem Update the screen.
                                  repaint();
                        long interval = 1000;
                        timer0.schedule(updateTask, interval,interval);}
              // Rem Show the canvas on the screen.
              display.setCurrent(MYCANVAS);
              // Rem Give it a listener so that the form can respond to user input (Action Function).
              MYCANVAS.setCommandListener(this);
         // Rem This is active when your application is paused.
         public void pauseApp() {     }
         // Rem This is called when a button is pressed, c is the name of your button.
         public void commandAction(Command C, Displayable s) {     }
         // Rem This is called when your application is closing.
         public void destroyApp(boolean unconditional) {     }
    CUBE.java:
    package Game;
    import javax.microedition.m3g.*;
    public class CUBE {
         public CUBE(){}
         public static Mesh getObject(){
              int[][] aaStripLengths = {{4}, {4}, {4}, {4}, {4}, {4}};
              // These are the vertex positions
              short[] aPos =
                        // Front
                        -1, -1, 1,     // B
                        1, -1, 1,     // C
                        -1, 1, 1,     // A
                        1, 1, 1,     // D
                        // Bottom
                        -1, -1, -1,     // F
                        1, -1, -1,     // G
                        -1, -1, 1,     // B
                        1, -1, 1,     // C
                        // Top
                        -1, 1, 1,     // A
                        1, 1, 1,     // D
                        -1, 1, -1,     // E
                        1, 1, -1,     // H
                        // Right
                        1, 1, 1,     // D
                        1, -1, 1,     // C
                        1, 1, -1,     // H
                        1, -1, -1,     // G
                        // Left
                        -1, -1, 1,     // B
                        -1, 1, 1,     // A
                        -1, -1, -1,     // F
                        -1, 1, -1,     // E
                        // Back
                        1, -1, -1,     // G
                        -1, -1, -1,     // F
                        1, 1, -1,     // H
                        -1, 1, -1     // E
              // These are the colors for the vertices
              byte[] aCol =
                        // Front
                        -1, 0, 0,
                        -1, 0, 0,
                        -1, 0, 0,
                        -1, 0, 0,
                        // Bottom
                        0, -1, 0,
                        0, -1, 0,
                        0, -1, 0,
                        0, -1, 0,
                        // Top
                        0, 0, -1,
                        0, 0, -1,
                        0, 0, -1,
                        0, 0, -1,
                        // Right
                        -1, -1, 0,
                        -1, -1, 0,
                        -1, -1, 0,
                        -1, -1, 0,
                        // Left
                        -1, 0, -1,
                        -1, 0, -1,
                        -1, 0, -1,
                        -1, 0, -1,
                        // Back
                        0, -1, -1,
                        0, -1, -1,
                        0, -1, -1,
                        0, -1, -1,
              // Calculate the number of submeshes and vertices directly from the sizes
              // of the arrays. This prevents us getting a mismatch if we decide to change
              // the cells to a different shape later.
              int cSubmeshes = aaStripLengths.length;
              int cVertices = aPos.length/3;
              // We will share a default appearance between all the faces on the cube. Each
              // face is a separate "submesh" - it can have a separate appearance if we wish.
              Appearance app = new Appearance();
              // We need to specify an appearance and the submesh data for each face.
              Appearance[] appa = new Appearance[cSubmeshes];
              IndexBuffer[] iba = new IndexBuffer[cSubmeshes];
              int startIndex=0;
              for(int i=0;i<cSubmeshes;i++)
                   // We use the same apppearance for each.
                   appa=app;
                   // And we create a new triangle strip array for each submesh.
                   // The start index for each one just follows on from previous submeshes.
                   iba[i] = new TriangleStripArray(startIndex, aaStripLengths[i]);
                   for(int j=0; j<aaStripLengths[i].length;j++)
                        startIndex+=aaStripLengths[i][j];
              // Now we create a new vertex buffer that contains all the above information
              VertexBuffer vertexBuffer = new VertexBuffer();
              vertexBuffer.setDefaultColor(0xFFFFFFFF); // white
                   // Copy the vertex positions into a VertexArray object
                   VertexArray vaPos = new VertexArray(cVertices, 3, 2);
                   vaPos.set(0, cVertices, aPos);
                   vertexBuffer.setPositions(vaPos, 0.40f, null);
                   // Copy the vertex colors into a VertexArray object
                   VertexArray vaCols = new VertexArray(cVertices, 3, 1);
                   vaCols.set(0, cVertices, aCol);
                   vertexBuffer.setColors(vaCols);
              // Create the mesh, set its translation...
              Mesh m = new Mesh(vertexBuffer, iba, appa);
              m.setTranslation(0,0,0);
              // ...and finally return
              return m;
    Thanks,
    John

    CUBE MYOBJECTa = new CUBE();
    MYOBJECT = (Node) MYOBJECTa.getObject();maybe it is because that "CUBE" class can not be rendered
    you should convert it to m3g.Mesh dont you ?

Maybe you are looking for