views:

428

answers:

2

How do you add zero padding to a JSpinner?
Since the spinner creates the JFormattedTextField itself, I can't just pass the format into the JFormattedTextField constructor.
Isn't there a way to set the formatting on an existing JFormattedTextField?

What I want: value = 37, editor = "0037"

UPDATE:
I have tried this as suggested:

JSpinner mySpinner = new JSpinner();  
mySpinner.setEditor(  
    new JSpinner.NumberEditor(mySpinner, "####"));

and the result is no change at all to the presentation of the spinner's data. It seems like a reasonable solution; has anyone tried this successfully so I can be sure it's just something flaky in my own application?

+3  A: 

You could set the editor yourself, like this:

// minimum of four digits
mySpinner.setEditor(new JSpinner.NumberEditor(mySpinner, "0000"));

Edit: I had used the wrong pattern before. "####" does not force zero-padding, but "0000" does. See DecimalFormat for more information on the formatting syntax.

Michael Myers
A: 

Referring to the javadocs, JSpinner has a setEditor(JComponent) method. Use that to set your custom JFormattedTextField, with its custom Format.

Kevin Montrose