JTextField限制 输入数字 【转】

原文:http://blog.sina.com.cn/s/blog_46fb85920100mi1m.html

貌似有很多方法,先记了再说...

1.限制输入数字

用法 textfield.setDocument(new IntegerDocument());   

class IntegerDocument extends PlainDocument

{   

public void insertString(int offset, String s, 
AttributeSet attributeSet) throws BadLocationException

{

      try  

{

    Integer.parseInt(s);

}

catch(Exception ex)

{

   Toolkit.getDefaultToolkit().beep();

    return;

}

super.insertString(offset, s, attributeSet);

}

}

 

2.限制输入数字和长度

public class NumberLenghtLimitedDmt extends PlainDocument {

   private int limit; 
   public NumberLenghtLimitedDmt(int limit) {
    super();
       this.limit = limit;
    } 
   public void insertString
     (int offset, String str, AttributeSet attr)
                                   throws BadLocationException {   
       if (str == null){
        return;
       }
       if ((getLength() + str.length()) <= limit) {
     
       char[] upper = str.toCharArray();
       int length=0;
       for (int i = 0; i < upper.length; i++) {     
           if (upper[i]>='0'&&upper[i]<='9'){         
              upper[length++] = upper[i];
           }
       }
         super.insertString(offset, new String(upper,0,length), attr);
      }
    }
}

用法:

JTextField   text=new JTextField();

text.setDocument(new NumberLenghtLimitedDmt(7));

那么这个文本框只能输入7位而且是只能是数字!!!

 

3.添加KeyListener

public void keyTyped(KeyEvent e)
    {
     if ((e.getKeyChar() >= e.VK_0 && e.getKeyChar() <= e.VK_9) 
      || e.getKeyChar() == e.VK_ENTER || e.getKeyChar() == e.VK_TAB
      || e.getKeyChar() == e.VK_BACK_SPACE || e.getKeyChar() == e.VK_DELETE 
      || e.getKeyChar() == e.VK_LEFT || e.getKeyChar() == e.VK_RIGHT 
      || e.getKeyChar() == e.VK_ESCAPE) 
      return;   
     e.consume();
    }

 

 

4.使用JFormattedTextField

5.貌似还能用正则表达式 - - 还不会玩,等学了补充下

posted @ 2012-11-28 23:23  Leo Forest  阅读(491)  评论(0编辑  收藏  举报