Mã hiện tại của bạn không đặt độ dài tối đa, thay vào đó là xác định số cột hiển thị.
Để hạn chế độ dài tối đa của dữ liệu, bạn có thể đặt tùy chỉnh Document
cho trường text mà không cho phép bổ sung mà phá vỡ những hạn chế chiều dài tối đa:
public final class LengthRestrictedDocument extends PlainDocument {
private final int limit;
public LengthRestrictedDocument(int limit) {
this.limit = limit;
}
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if (str == null)
return;
if ((getLength() + str.length()) <= limit) {
super.insertString(offs, str, a);
}
}
}
Sau đó thiết lập trường văn bản của bạn để sử dụng này tài liệu:
text2.setDocument(new LengthRestrictedDocument(8));
Nguồn
2012-10-25 19:18:26
Bạn có thể tìm thấy ví dụ tốt về cách thực hiện việc này tại đây (http://www.java2s.com/Tutorial/Java/0240__Swing/LimitJTextFieldinputtoamaximumlength.htm). – Designpattern