限制JTextFiled只能輸入定長或者數字

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JTextField;

/**
 * 限制JTextFiled只能輸入定長或者數字
 * @author martin

 */
public class MyJTextField extends JTextField  {
     private int limit = Integer.MAX_VALUE;                      //最大定長數
     private boolean numberOnly;                                    //只能接受數字

     public MyJTextField() {

          addKeyListener(new KeyAdapter() {

               @Override
               public void keyTyped(KeyEvent e) {
                    if(getText().length() + 1 > limit) {

                         deleteInputChar(e);
                         return;
                    }
                    if (numberOnly) {
                         char input = e.getKeyChar();
                              if (!Character.isDigit(input)) {

                                   deleteInputChar(e);
                              }
                         }
                    }

                    private void deleteInputChar(KeyEvent source) {
                         source.setKeyChar((char) KeyEvent.VK_CLEAR);
                    }
               });

          }

 

          public void setMaxTextLength(int limit) {
               if(limit < 0) {
                    return;
               }
               this.limit = limit;
          }

 

          public int getMaxTextLength() {
               return limit;
          }

 

          public void setNumberOnly(boolean numberOnly) {
               this.numberOnly = numberOnly;
          }

 

          public boolean getNumberOnly() {
               return numberOnly;
          }   
     }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章