JAVA不像C#可以有maxLength這個屬性對文本框的輸入長度進行控制,但也是有辦法實現相應的功能的。java
寫一個MyDocument類,繼承PlainDocument。重寫insertString(int offset,String str,AttributeSet a)方法。this
代碼以下:spa
- 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);
- }
- }
- }
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