I am trying to create a JFormattedTextField that only accepts a 24-hour time.
I am very close to a solution, but have one case where the following code example does not work.
If you enter the time "222" and change focus from the field, the time is corrected to "2202". I would like it to only accept a full 4 digit 24-hour time. This code works as I want in almost all cases, except the one I just mentioned. Any suggestions?
public static void main(String[] args) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("HHmm");
dateFormat.setLenient(false);
DateFormatter dateFormatter = new DateFormatter(dateFormat);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFormattedTextField textField = new JFormattedTextField(dateFormatter);
frame.add(textField, BorderLayout.NORTH);
frame.add(new JTextField("This is here so you can change focus."), BorderLayout.SOUTH);
frame.setSize(250, 100);
frame.setVisible(true);
}
As others have mentioned, your best bet is probably to validate the lenght of the input string. My preferred approach would be subclassing SimpleDateFormat
to keep all the parsing logic in one place:
public class LengthCheckingDateFormat extends SimpleDateFormat {
public LengthCheckingDateFormat(String pattern) { super(pattern); }
@Override
public Date parse(String s, ParsePosition p) {
if (s == null || (s.length() - p.getIndex()) < toPattern().length()) {
p.setErrorIndex(p.getIndex());
return null;
}
return super.parse(s, p);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With