JAVA 中限制文本框輸入長度的辦法

JAVA不像C#可以有maxLength這個屬性對文本框的輸入長度進行控制,但也是有辦法實現相應的功能的。java

寫一個MyDocument類,繼承PlainDocument。重寫insertString(int offset,String str,AttributeSet a)方法。this

代碼以下:spa

  1. public class MyDocument extends PlainDocument{
  2. private int maxLength;
  3. public MyDocument(int newMaxLength)
  4. {
  5. super();
  6. maxLength=newMaxLength;
  7. }
  8. public MyDocument()
  9. {
  10. this(10);
  11. }
  12. public void insertString(int offset,String str,javax.swing.text.AttributeSet a) throws BadLocationException
  13. {
  14. if(getLength()+str.length()>maxLength)
  15. {
  16. return;
  17. }
  18. else
  19. {
  20. super.insertString(offset, str,a);
  21. }
  22. }
  23. }
public class MyDocument extends PlainDocument{ private int maxLength; public MyDocument(int newMaxLength) { super(); maxLength=newMaxLength; } public MyDocument() { this(10); } public void insertString(int offset,String str,javax.swing.text.AttributeSet a) throws BadLocationException { if(getLength()+str.length()>maxLength) { return; } else { super.insertString(offset, str,a); } } }

若是想讓jTextField的輸入長度爲13,那麼只需jt_username.setDocument(new MyDocument(13))便可。.net

相關文章
相關標籤/搜索