下面的一个实例是TextField的使用实例,输入、提交并显示输入内容。
package mtk; 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.TextField; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; public class TextFieldCapture extends MIDlet implements CommandListener { private Display display; private Form mainForm; private final static Command CMD_SUBMIT=new Command("提交",Command.SCREEN,1); private final static Command CMD_EXIT=new Command("退出",Command.EXIT,1); private TextField textField; public TextFieldCapture() { display=Display.getDisplay(this); textField=new TextField("姓名:","",20,TextField.ANY); mainForm=new Form("请输入"); mainForm.append(textField); mainForm.addCommand(CMD_SUBMIT); mainForm.addCommand(CMD_EXIT); mainForm.setCommandListener(this); } protected void destroyApp(boolean arg0){ } protected void pauseApp() { } protected void startApp() throws MIDletStateChangeException { display.setCurrent(mainForm); } public void commandAction(Command c, Displayable d) { if(c==CMD_EXIT){ destroyApp(false); notifyDestroyed(); }else{ if(c==CMD_SUBMIT){ textField.setString("你好,"+textField.getString()); mainForm.removeCommand(CMD_SUBMIT); } } } }
下面的实例是TextField属性应用,利用其中的TextField.ANY|TextField.PASSWORD,使得输入字符隐藏起来。
package mtk; 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.TextField; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; public class HideText extends MIDlet implements CommandListener { private Display display; private Form mainForm; private final static Command SUBMIT=new Command("提交",Command.SCREEN,1); private final static Command CMD_EXIT=new Command("退出",Command.EXIT,1); private TextField textField; public HideText() { display=Display.getDisplay(this); textField=new TextField("密码","",20,TextField.ANY|TextField.PASSWORD); mainForm=new Form("请输入密码"); mainForm.addCommand(CMD_EXIT); mainForm.addCommand(SUBMIT); mainForm.append(textField); mainForm.setCommandListener(this); } protected void destroyApp(boolean arg0){ } protected void pauseApp() { } protected void startApp() throws MIDletStateChangeException { display.setCurrent(mainForm); } public void commandAction(Command c, Displayable d) { if(c==CMD_EXIT){ destroyApp(false); notifyDestroyed(); }else{ if(c==SUBMIT){ textField.setConstraints(TextField.ANY); textField.setString("谢谢"); mainForm.removeCommand(SUBMIT); } } } }