How to set DocumentFilter with input length and range? e.g. 1-3 or 10-80

前端 未结 2 1633
没有蜡笔的小新
没有蜡笔的小新 2020-12-22 07:29

I\'m using DocumentFilter to restrict input as integer or decimal. And the code I post here is working well for that.

Can anybody help me about how to restrict the i

2条回答
  •  囚心锁ツ
    2020-12-22 08:07

    Based on MadProgrammer answer I tested editing his "replace" function in "MyIntFilter" class to:

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text,
                    AttributeSet attrs) throws BadLocationException {
    
        Document doc = fb.getDocument();
        StringBuilder sb = new StringBuilder(2);
        sb.append(doc.getText(0, doc.getLength()));
        sb.replace(offset, offset + length, text);
    
        if (test(sb.toString())) {
            if (sb.length() < maxLength + 1) { //test string size
                super.replace(fb, offset, length, text, attrs);
                }
            }
        } else {
            // warn the user and don't allow the insert
        }
    
    }
    

    it worked fine for me.

提交回复
热议问题