J2ME学习(四)——将MIDlet和界面分离(比较基础)

J2ME学习()——将MIDlet和界面分离(比较基础)

 

       虽然使用面向对象的思想进行J2ME的编程,会增加代码量(增加发布文件的大小)和提高代码的复杂性。但是为了代码的可维护性和可扩展性,现在绝大多数的程序还是将界面和逻辑分离开来,下面先说明一下如何将MIDlet主类和界面分离。

       在界面和MIDlet中,需要交换的系统内容主要有两部分:1Display对象;2MIDlet中的退出处理。

       示例代码如下:

       package testmidlet;

 

import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

 

public class TestMIDlet extends MIDlet {

  private static TestMIDlet instance;

  private LoginForm displayable ;

private Display display;

 

  /** Constructor */

  public TestMIDlet() {

    instance = this;

   display = Display.getDisplay(this);

   displayable= new LoginForm(display);

  }

 

  /** Main method */

  public void startApp() {

    display .setCurrent(displayable);

  }

 

  /** Handle pausing the MIDlet */

  public void pauseApp() {

  }

 

  /** Handle destroying the MIDlet */

  public void destroyApp(boolean unconditional) {

  }

 

  /** Quit the MIDlet */

  public static void quitApp() {

    instance.destroyApp(true);

    instance.notifyDestroyed();

    instance = null;

  }

 

}

 

package testmidlet;

 

import javax.microedition.lcdui.*;

 

public class LoginForm extends Form implements CommandListener {

    private Display display;
 
/** Constructor */

  public LoginForm(Display display) {

    super("Test");

    this.display = display;
   
setCommandListener(this);

    // add the Exit command

    addCommand(new Command("Exit", Command.EXIT, 1));

  }

 

  /**Handle command events*/

  public void commandAction(Command command, Displayable displayable) {

    /** @todo Add command handling code */

    if (command.getCommandType() == Command.EXIT) {

// stop the MIDlet

      TestMIDlet.quitApp();

    }

  }

}

其中display对象可以通过构造方法进行传递,退出方法可以通过方法调用来执行.这样,你的代码就能实现MIDlet类和界面分离了.

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值