1

How can I limit input of digits using jSpinner as a time picker?

When I use this code:

JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner, "HH:mm");
DateFormatter formatter = (DateFormatter)editor.getTextField().getFormatter();
formatter.setAllowsInvalid(false); // this makes what you want
formatter.setOverwriteMode(true);

I took this example from here: Similar problem using jSpinner as time picker on StackOverflow

So when I start typing right at the beginning 1111, then it works fine until I enter further digits, then it starts calculating and giving me "strange" output, like:

12:51

when I entered another 1 after 1111. When I put 12h time format, like:

JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner, "HH:mm a");

then it works just fine, stopping at the end after forth digit and not allowing any other input. How can I get this behavior for 24h time format?

  • Personal opinion, I hate date/time entry using a `JSpinner`, it just doesn't do the job right and the entry process can just be a pain for users. Sometime ago I wrote a prototype/proof of concept `TimeField` which takes a lot of the pain out of the process - have a look at [this example](https://stackoverflow.com/questions/11881301/best-way-to-constrain-user-to-enter-a-time-in-a-jtextfield/11881681#11881681) for more ideas. If you're stuck using a `JSpinner`, then you might be out of luck – MadProgrammer Oct 24 '17 at 21:51
  • You might also consider having a play around with some of the ideas presented [here](https://stackoverflow.com/questions/21960236/jspinner-time-picker-model-editing) and [here](https://stackoverflow.com/questions/5515413/jspinner-exclusively-for-time) – MadProgrammer Oct 24 '17 at 21:55

0 Answers0