虽然使用面向对象的思想进行j2me的编程,会增加代码量(增加发布文件的大小)和提高代码的复杂性。但是为了代码的可维护性和可扩展性,现在绝大多数的程序还是将界面和逻辑分离开来,下面先说明一下如何将midlet主类和界面分离。
在界面和midlet中,需要交换的系统内容主要有两部分:1、display对象;2、midlet中的退出处理。
示例代码如下:
package testmidlet;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class testmidlet extends midlet {
private static testmidlet instance;
private loginform displayable = new loginform();
/** constructor */
public testmidlet() {
instance = this;
}
/** main method */
public void startapp() {
display.getdisplay(this).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类和界面分离了.
