Although the use of object-oriented programming will increase the amount of code (increase the size of the published file) and increase the complexity of the Code. However, for code maintainability and scalability, most programs still separate the interface from the logic. The following describes how to separate the main class and interface of the MIDlet.
In the interface and MIDlet, the system content to be exchanged mainly includes two parts: 1. Display object; 2. Exit Processing in the MIDlet.
The sample code is as follows:
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. policydestroyed ();
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 ();
}
}
}
The display object can be passed through the constructor, And the exit method can be executed through the method call. In this way, your code can implement the MIDlet class and interface separation.