[英]Can't figure out what's wrong with my DocumentFilter
我嘗試將其他人制作的自定義PlainDocument組合在一起,但是因為我不知道PlainDocument的機制,所以我失敗了,但它沒有用。 我需要一些東西,以確保我的文本字段只允許2個字母,所以任何a-zA-Z只發生兩次。 我先試了一下:
public class LetterDocument extends PlainDocument {
private String text = "";
@Override
public void insertString(int offset, String txt, AttributeSet a) {
try {
text = getText(0, getLength());
if ((text + txt).matches("^[a-zA-Z]{2}$")) {
super.insertString(offset, txt, a);
}
} catch (Exception ex) {
Logger.getLogger(LetterDocument.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
這甚至不讓我輸入任何東西。 然后我嘗試了這個,我嘗試將其他兩個線程放在一起,其中一個只允許輸入字母,另一個限制字符:
public class LetterDocument extends PlainDocument {
private int limit;
private String text = "";
LetterDocument(int limit) {
super();
this.limit = limit;
}
@Override
public void insertString(int offset, String txt, AttributeSet a)
throws BadLocationException {
if (txt == null)
return;
try {
text = getText(0, getLength());
if (((text + txt).matches("[a-zA-Z]"))
&& (txt.length()) <= limit) {
super.insertString(offset, txt, a);
}
} catch (Exception ex) {
Logger.getLogger(LetterDocument.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
我不知道出了什么問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.