Lwuit中关于TextField限制输入为数字的内容代码
在Lwuit中关于TextField的标签在前面已经接触过了,确实lwuit中的标签跟javax.microedition.midlet.*包中的标签有很大的区别。
比如这个TextFiled的区别:
1.在javax.microedition.midlet.*包中定义TextFiled并限制输入为数字:
TextField numberEntry = new TextField("Connect to:",null,256,TextField.PHONENUMBER);
在构造方法中就可以限制输入类型
2.在com.sun.lwuit.TextField包中定义TextFiled并限制输入为数字:
TextField tf = new TextField(TextArea.PHONENUMBER);
随然在构造方法中也可以限制输入类型,但似乎没起到作用
下面看一下关于Lwuit中TextField限制输入为数字的内容代码:
package com.mopietek;
import java.util.Hashtable;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.TextField;
import com.sun.lwuit.events.DataChangedListener;
import com.sun.lwuit.layouts.BorderLayout;
public class TextTest extends MIDlet{
TextField tf = null;
protected void destroyApp(boolean unconditional)
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.init(this);
Form f = new Form("ceshi");
f.setLayout(new BorderLayout());
tf = new TextField();
final Label label = new Label("kong");
Hashtable ht = new Hashtable();
ht.put(new Integer('0'), "0");
ht.put(new Integer('9'), "9");
ht.put(new Integer('8'), "8");
ht.put(new Integer('7'), "7");
ht.put(new Integer('6'), "6");
ht.put(new Integer('5'), "5");
ht.put(new Integer('4'), "4");
ht.put(new Integer('3'), "3");
ht.put(new Integer('2'), "2");
ht.put(new Integer('1'), "1");
ht.put(new Integer('#'), "+");
TextField.addInputMode("+123", ht, false);
tf.setConstraint(TextArea.PHONENUMBER);
//缺少这两句话就会报数组越界异常
tf.setInputMode("+123");
tf.setInputModeOrder(new String[]{"+123"});
tf.addDataChangeListener(new DataChangedListener(){
public void dataChanged(int i, int j) {
if(i == DataChangedListener.ADDED){
label.setText("ADDED");
if(tf.getText().length()>5){
tf.setText(tf.getText().substring(0,5));
}
}
if(i == DataChangedListener.CHANGED){
label.setText("CHANGED");
}
if(i == DataChangedListener.REMOVED){
label.setText("REMOVED");
}
}
});
f.addComponent(BorderLayout.NORTH,tf);
f.addComponent(BorderLayout.SOUTH,label);
f.show();
}
}