Search code examples
java-memidpmidletlcdui

(J2ME) get the reference of the MIDlet from some other class?


I am trying to make a class that can set what is on the screen (Like set a Form to the Display, what ever.) outside the midlet (Main) class
So I thought I have to enter and change the Main's variable display, but I went to an error.

Here's the whole program:

//Main.java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Main extends MIDlet {

    public Other othr = new Other(this);
    public Display display = Display.getDisplay(this);
    public void startApp() {
        display.setCurrent(othr);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
}


//Other.java
import javax.microedition.lcdui.*;
public class Other extends Canvas{

    Form a = new Form("a");
    public TextEdit(Main mc){
        //HERE IT IS!
        mc.display.getDisplay(mc).setCurrent(a);
        //If I comment out the above, I get no error.

    }
    protected void paint(Graphics g) {
         //Nothing yet
    }

}

And I always get the error "The application has unexpectedly quit".

I also tried to replace mc.display.getDisplay(mc).setCurrent(a); with Display.getDisplay(mc).setCurrent(a);, error is not showed then, but Form a isn't displayed at all.

It's likely to be a stupid mistake, but I'm lost

What can I do?


Solution

  • It's a small mistake in your code. Make changes in your code like following.

    //Main.java
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    public class Main extends MIDlet {
    
        public Other othr ;
        public Display display ;
        public void startApp() {
             display= Display.getDisplay(this);
            othr=new Other(this);
            display.setCurrent(othr);
        }
    
        public void pauseApp() {
        }
    
        public void destroyApp(boolean unconditional) {
        }
    }
    

    and check your Other look like this, make sure what you want Form or Canvas both are different.

    For Form your code like this

    //Other.java
    import javax.microedition.lcdui.*;
    public class Other {
    
        Form a ;
        public Other(Main mc){
            //HERE IT IS!
           a=new Form("a");
            Display.getDisplay(mc).setCurrent(a);
            //If I comment out the above, I get no error.
    
        }
    
    }
    

    For Canvas check this one

    /Other.java
    import javax.microedition.lcdui.*;
    public class Other extends Canvas{
    
         public Other(Main mc){
            //HERE IT IS!
            Display.getDisplay(mc).setCurrent(this);
            //If I comment out the above, I get no error.
    
        }
        protected void paint(Graphics g) {
             //Nothing yet
        }
    
    }
    

    This will help you, Note:: Check difference between Canvas & Forms.