Question

In J2ME to create the Display class object we use

private Display d;
d=Display.getDisplay(this);

What is this as parameter?

I know this refers to the current instance but when I write the following I get errors

d=Display.getDisplay(new MyClassName());

When I saw in book the method was written like below

static Display getDisplay(MIDlet midlet)

So then I tried this

MIDlet m;
d=Display.getDisplay(m);

But I am getting errors and I cannot even pass new MIDlet() as parameter since it's an abstract class.

Was it helpful?

Solution

As Android says, this in d=Display.getDisplay(this); refers to your MIDlet.

But when you write the following you get errors

d=Display.getDisplay(new MyClassName());   

It's because you try to create MIDlet by it's constructor. You would to see MIDlet doc:

protected MIDlet() Protected constructor for subclasses. The application management software is responsible for creating MIDlets and creation of MIDlets is restricted. MIDlets should not attempt to create other MIDlets. Throws: SecurityException - unless the application management software is creating the MIDlet.

OTHER TIPS

In the code d=Display.getDisplay(this); , this refers to the Current Midlet. The Method getDisplay() takes one midlet argument. Take the following simple example

public class MyMidlet extends Midlet
{
    private Display display;

   public MyMidlet()
   {
       display = Display.getDisplay(this);  // Here this refers to the current class's Midlet
   }
}

Now suppose you have normal class file like below,

public class MyClass
{
    private Display display;
    Midlet m;

   public MyClass()
   {
       display = Display.getDisplay(m);  // You can not do this directly.
   }
}

if you want the above scenario then you might need to change your code some how like below, suppose you have both the class in same package.

// Midlet Class 
    public class MyMidlet extends Midlet
    {
        private MyClass mycls;
        public void myMethod ()
        {
           mycls = MyClass(this); // Passing Midlet reference to MyClass's constructor.
        }
        ....
        ....
        ....
    }


// another class file 
    public class MyClass
    {
        private Display display;
        Midlet m;

       public MyClass( Midlet m )
       {
        this.m = m;
        display = Dispaly.getDisplay(m);  // Now it will work
       }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top