Domanda

I have a program which removes all non-digit characters from a JTextField and limits it to 5 digits. But this Document filter also removes the backspace function, which means I cannot edit the input I've done. How can I add the backspace again without removing my filter?

Edit: Thank you for your answers. I've added the function to "public void remove" and now my removal works again. But I noticed that it stores my text input backwards. if I write "12345" and then use my (int length-1) it removes "1", then "2" and so on. Why is it doing that?

public class onlyNumericDocumentFilter extends DocumentFilter {

    @Override
    public void insertString(DocumentFilter.FilterBypass fb, int offset,
            String string, AttributeSet attr) throws BadLocationException {
        if (fb.getDocument().getLength() + string.length() > 5) {
            return;
        }
        fb.insertString(offset, string, attr);
    }

    @Override
    public void remove(DocumentFilter.FilterBypass fb, int offset, int length)
            throws BadLocationException {

      //edit: 
          fb.remove(length-1, 1);  


       // fb.insertString(offset, "", null);
    }

    @Override
    public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
            String text, AttributeSet attr) throws BadLocationException {
        if (fb.getDocument().getLength() + text.length() > 5) {
            return;
        }
        fb.insertString(offset, text.replaceAll("\\D", ""), attr);
    }
}
È stato utile?

Soluzione

You suppress the remove here

public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException 
        {  
            fb.insertString(offset, "", null);
        }  
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top