开发者

Probability cell editor

开发者 https://www.devze.com 2023-03-12 22:17 出处:网络
I have class Probability. I want use custom renderer for it (already done) and double like editor. But I 开发者_Go百科can\'t even find double editor (only Number), so I really have no idea how I shoul

I have class Probability. I want use custom renderer for it (already done) and double like editor. But I 开发者_Go百科can't even find double editor (only Number), so I really have no idea how I should implement it. The question is: how I should implement it?

*difference from double editor: it should permit only numbers in range 0..100


What about a JFormattedTextField with an AbstractFormatter doing the conversion, and a DocumentFilter to reject anything which is not a valid percentage value?

Here is an example DocumentFilter (not tested, from reading the documentation):

class PercentageFilter extends DocumentFilter {
    insertString(FilterBypass bp, int offset, String adding, AttributeSet attrs) {
        Document doc = bp.getDocument();
        String text = doc.getText(0, offset) + adding + doc.getText(offset, doc.getLength()-offset);
        try {
            double d = Double.parseDouble(text);
            if(d < 0 || 100 < d) {
                // to big or too small number
                return;
            }
        }
        catch(NumberFormatException ex) {
            // invalid number, do nothing.
            return;
        }
        // if we come to this point, the entered number
        // is a valid value => really insert it into the document.
        bp.insertString(offset, adding, attrs);
    }
}

You would want to override remove() and replace similarly.

(I suppose there could be a more efficient implementation, but this will be fast enough for most user's typing speed, I suppose.)

This filter would be returned from your AbstractFormatter implementation's getDocumentFilter method.


..numbers in range 0..100

Use a JSpinner as the TableCellEditor.

0

精彩评论

暂无评论...
验证码 换一张
取 消