I want to use a JFormattedTextField
to allow the user to input time duration values into a form. Sample valid values are:
2h 30m
72h 15m
6h
0h
However I am having limited success with this. Can some one please suggest how this can be accomplished? I am OK if this result can be achieved using a JTextField
as well.
Thanks!
If it is worth anything, here's my current attempt:
mFormattedText.setFormatterFactory(
new DefaultFormatterFactory(
new DateFormatter(
new SimpleDateFormat("H mm"))));
This sorta works except that:
I cannot get*h
andm
to appear as plain text (I tried escaping)- The number of hours has a max
*: See @nanda's answer
tl;dr
ISO 8601
If you are willing to redefine your desired input formats, I suggest using the already-existing formats defined by the ISO 8601 standard.
The pattern
PnYnMnDTnHnMnS
uses aP
to mark the beginning, aT
to separate any years-months-days portion from any hours-minutes-seconds portion.An hour-and-a-half is
PT1H30M
, for example.java.time
The java.time classes use the ISO 8601 formats by default when parsing/generating strings. This includes the
Period
andDuration
classes for representing spans of time not attached to the timeline.Going the other direction, parsing a string.
See live code in IdeOne.com.
See my similar Answer to a similar Question.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.The code:
Have you tried
H'h' mm'm'
?Here's an example of using
InputVerifier
to accommodate multiple input formats.hmm, what i think is that you can achieve the same goal by, creating three different JTextField for all the three time components, one for the HOUR, MINUTE and Second (if it's included) to get your input... just a thought, you could just concatenate them if you it's necessary... just a thought...