JTextField限制 输入数字

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

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

posted @ 2014-05-15 21:23  牧之丨  阅读(2153)  评论(0编辑  收藏  举报