Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Probability cell editor

Tags:

java

swing

jtable

I have class Probability. I want use custom renderer for it (already done) and double like editor. But I 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

like image 722
Stan Kurilin Avatar asked Jun 12 '11 11:06

Stan Kurilin


2 Answers

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.

like image 148
Paŭlo Ebermann Avatar answered Nov 11 '22 03:11

Paŭlo Ebermann


..numbers in range 0..100

Use a JSpinner as the TableCellEditor.

like image 45
Andrew Thompson Avatar answered Nov 11 '22 02:11

Andrew Thompson