javaswingdocumentfilter

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


I want to make sure that there is always a positive Integer in my JTextField. For example, the JTextField currently has a default "1" when the GUI is created, and I want it such that if the user decides to hit backspace, instead of becoming an empty text field, I want it to automatically set the text to "0". The reason for this is because the text field also has a listener which calls a method to keep another part of the GUI updated according to this number.

I'm pretty new to DocumentFilter so I'm not even sure I'm going in the right direction but here's what I have so far:

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

As of right now I'm overriding the remove() method of the filter and checking to see if the digit that the user is deleting is the last one. If not then delete works as regular, but if so, then nothing happens yet.

I think where I'm stuck is the fact that I want to call the replace method inside the remove method, but I don't have AttributeSet to work with.


Solution

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

    First of all your basic logic is wrong. You can't just check the offset. You could have 5 numbers in the text field and are just trying to remove the first number.

    What you want to do is:

    1. always invoke super.remove(...) to remove the digit from the Document
    2. then you need to get the Document to determine how many digits are still in the Document. If the value is zero then you can invoke the super.insertString(...) method of the DocumentFilter to insert whatever value you want to be inserted into the Document.

    I don't have AttributeSet to work with.

    The AttributeSet would be null for a JTextField.