In one of my java applications, there is a field where the user is supposed to enter a time. I know, I can simply keep it as a normal JTextField
and at the time of validation I can check the value and so on...
But I think there is a better way than that..
For example, if this is a matter with a date, then JXDatePicker
(which comes with swingx
) can be used very handily. Eventually, the users selection is guaranteed to be a date.
Likewise, there must be a better way for time selection too. Will someone share your knowledge if you know a better solution.
Any thought is appreciated. Thank you!
you could use a
JFormattedTextField
have a look at the example below, this will create aJFormattedTextField
which will accept only numbers and put them in the form XXhXXminXXs then add aActionListener
to theJFormattedTextField
and in that attempt to parse to a valid time object when ENTER for now I only show the use of theJFormattedTextField
and theActionListener
I didn't attempt to convert or any converting and parsing for valid time:I did a prototype of a
TimeField
some time ago, it still needs a little work, but the concept is pretty basic.It basically presents two
JTextFields
, one for the hour and one for the minutes and makes them appear to be a single field.Through the use of some
DocumentFilter
s, it restricts the users input.I did this some time ago and it needs work, but the basic idea is there...if you have problems, you will need to try and figure it out yourself ;)
Simple answer, validation.
JFormattedTextField
does not valid the values, but only limits the fact that you can enter digits, you could just as easily enter99:99
into aJFormattedTextField
. The intention of this implementation is to provide real time validation while providing simple data entry requirementsJSpinner
instances allowing to select hours, minutes and secondsJFormattedTextField
with some improvements to provide immediate user feedback (for example color the background red as soon as the input becomes invalid)I don't see any reasons for multiplay
JSpinner
, orJFormattedTextField
, this doens't make me any sence, those concepts aren't user-friendly, have look at:use Java Calendar
use simple JSpinner with SpinnerDateModel