如何使用 DocumentFilter 自动将空字符串更改为 0?

How can I automatically change empty String to 0 with a DocumentFilter?

我想确保我的 JTextField 中始终有一个正整数。例如,JTextField 当前在创建 GUI 时有一个默认值“1”,我希望它在用户决定按下退格键时自动将文本设置为“,而不是变成空文本字段” 0”。这样做的原因是因为文本字段还有一个侦听器,它调用一个方法来根据这个数字更新 GUI 的另一部分。

我是 DocumentFilter 的新手,所以我什至不确定我的方向是否正确,但这是我目前所掌握的:

public class IntegerFilter extends DocumentFilter {

    public void remove(FilterBypass fb, int offs,
        int len) throws BadLocationException {

        if (offs == 0) {
            // I'm trying to think if there's something I can put here
        } else {
            super.remove(fb, offs, len);
        }
    }

    public void replace(FilterBypass fb, int offs, int len, String str,
        AttributeSet a) throws BadLocationException {

        String text = fb.getDocument().getText(0, fb.getDocument().getLength());
        text += str;
        if (text.matches("\d+")) {
            super.replace(fb, offs, len, str, a);
        }
    }
}

截至目前,我正在重写过滤器的 remove() 方法并检查用户删除的数字是否是最后一个。如果不是,则删除会正常工作,但如果是,则什么也不会发生。

我认为卡住的地方是我想在 remove 方法中调用 replace 方法,但我没有 AttributeSet 可以使用。

// I'm trying to think if there's something I can put here

首先你的基本逻辑是错误的。您不能只检查偏移量。您可以在文本字段中有 5 个数字,而只是试图删除第一个数字。

您想做的是:

  1. 始终调用 super.remove(...) 从文档中删除数字
  2. 然后你需要获取Document以确定Document中还有多少位数。如果该值为零,那么您可以调用 DocumentFilter 的 super.insertString(...) 方法来插入您想要插入到文档中的任何值。

I don't have AttributeSet to work with.

对于 JTextField,AttributeSet 将为 null。