簡體   English   中英

無法弄清楚我的DocumentFilter有什么問題

[英]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);
        }

    }
}

我不知道出了什么問題。

不要使用自定義文檔。

而是使用DocumentFilter 閱讀有關實現文檔過濾器的Swing教程中的部分,以獲取限制可在文檔中輸入的字符數的工作示例。

然后只需添加一些額外的邏輯,以確保只添加字母。

或者更簡單的選擇是使用帶有字符掩碼的JFormatttedTextField。 再次參閱使用格式化文本字段的教程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM