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);
}
JTextField
, and usingDocumentFilter
:-) For DocumentFilter you can check this example – SupramolecularFocusLost
check the length if it's less than 4, then present oneJOptionPane
for the user to have a look at, or don't let this component to lose focus if length is less than 4 :-) – Supramolecular