Probability Cell Editor

I have a Probability class. I want to use my own visualizer for it (already done) and a dual editor. But I can’t even find a double editor (number only), so I really don’t know how to implement it. The question is, how should I implement it?

* difference from the dual editor: it should only allow numbers in the range 0..100

+7
source share
2 answers

How about a JFormattedTextField using an AbstractFormatter that does the conversion and a DocumentFilter to reject everything that is not a valid percentage?

Here is a DocumentFilter example (not verified by 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 like to override remove() and replace similar way.

(I suppose there might be a more efficient implementation, but it will be fast enough for most user input speeds, I suppose.)

This filter will be returned from your implementation method of AbstractFormatter getDocumentFilter .

+5
source

.. numbers in the range 0..100

Use JSpinner as TableCellEditor .

+5
source

All Articles