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) {
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 .
Paŭlo Ebermann
source share