简体   繁体   English

无法弄清楚我的DocumentFilter有什么问题

[英]Can't figure out what's wrong with my DocumentFilter

I tried putting together custom PlainDocument made by others for one I needed, but since I don't know the mechanics of PlainDocument, I failed and it didn't work. 我尝试将其他人制作的自定义PlainDocument组合在一起,但是因为我不知道PlainDocument的机制,所以我失败了,但它没有用。 I need something that will make sure my textfield only allows 2 letters, so anything a-zA-Z that occurs only twice. 我需要一些东西,以确保我的文本字段只允许2个字母,所以任何a-zA-Z只发生两次。 I tried this first: 我先试了一下:

    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);
         }

        }
    }

This doesn't even let me type in anything. 这甚至不让我输入任何东西。 I then tried this, which I tried putting together from two other threads, one of them letting only letters be typed in, and the other limiting the characters: 然后我尝试了这个,我尝试将其他两个线程放在一起,其中一个只允许输入字母,另一个限制字符:

    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);
        }

    }
}

I have no idea what's wrong. 我不知道出了什么问题。

Don't use a custom Document. 不要使用自定义文档。

Instead use a DocumentFilter . 而是使用DocumentFilter Read the section from the Swing tutorial on Implementing a Document Filter for a working example that limits the number of characters you can enter in a Document. 阅读有关实现文档过滤器的Swing教程中的部分,以获取限制可在文档中输入的字符数的工作示例。

Then just add some additional logic to make sure only letters are added. 然后只需添加一些额外的逻辑,以确保只添加字母。

Or an easier option is to use a JFormatttedTextField with a character mask. 或者更简单的选择是使用带有字符掩码的JFormatttedTextField。 Again see the tutorial on Using a Formatted Text Field . 再次参阅使用格式化文本字段的教程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM