天天看點

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