j2me高级界面和低级界面的切换
今天在用j2me做低级界面应用的时候 需要接收用户输入的数据.以前没有做过,整理了一下,写了一个例子.留作参考;全文如下:
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class MainMIDlet extends MIDlet implements CommandListener {
public static MainMIDlet self ;
public static Display display;
MainCanvas mainCanvas ;
private Form form;
TextField t ;
String str ;
private Command confirmCommand = new Command("确定", Command.ITEM, 1);
private Command exitCommand = new Command("返回", Command.EXIT, 1);
public MainMIDlet() {
// TODO Auto-generated constructor stub
self = this ;
mainCanvas = new MainCanvas() ;
display = Display.getDisplay(this);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
display.setCurrent(mainCanvas);
}
public void gotoForm() {
form = new Form("高级用户界面");
String label = "input:";
String text = "";
int size = 20;
t = new TextField(label, text, size, TextField.ANY);
form.append(t);
form.addCommand(exitCommand);
form.addCommand(confirmCommand);
form.setCommandListener(this);
display.setCurrent(form);
}
public void gotoCanvas(){
display.setCurrent(mainCanvas) ;
MainMIDlet.self.mainCanvas.setFullScreenMode(true) ;
}
class MainCanvas extends Canvas implements Runnable{
Image img ;
public MainCanvas(){
setFullScreenMode(true);
try{
img = Image.createImage("/img.png") ;
}catch(Exception e){
System.out.println("pic not found");
}
new Thread(this).start() ;
}
protected void paint(Graphics g) {
// TODO Auto-generated method stub
g.drawImage(img,0,0,0) ;
g.drawString("低级用户界面",0,0,0) ;
g.drawString("[确定]切换到高级界面", getWidth()/2, getHeight()/2,0) ;
if(str!=null&&str.length()>0)
g.drawString("输入:"+MainMIDlet.self.str, getWidth()/2, getHeight()/2+15, 0) ;
}
public void run() {
// TODO Auto-generated method stub
}
protected void keyPressed(int keyCode) {
// TODO Auto-generated method stub
switch(keyCode){
case -5: //确定
MainMIDlet.self.gotoForm();
break;
}
}
protected void keyReleased(int keyCode) {
// TODO Auto-generated method stub
super.keyReleased(keyCode);
}
}
public void commandAction(Command c, Displayable d) {
// TODO Auto-generated method stub
if(c==exitCommand){
str = null ;
gotoCanvas() ;
}
if(c==confirmCommand){
str = t.getString() ;
gotoCanvas() ;
}
}
}