將MIDlet和介面分離

來源:互聯網
上載者:User

雖然使用物件導向的思想進行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 ;
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類和介面分離了.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.