Question

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?

Was it helpful?

Solution

You can set the editor yourself, like this:

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

"0000" is a DecimalFormat string specifying four digits, zero-padded as necessary; "####" specifies four digits but does not zero-pad.

The DecimalFormat API documentation covers formatting strings in more detail.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top