Strict 24 hour time in JFormattedTextField

I am trying to create a JFormattedTextField that only accepts 24 hour time.

I am very close to a solution, but I have one case where the following code example does not work.

If you enter the time "222" and change the focus from the field, the time will be corrected to "2202". I would like it to take only 4-digit 24-hour time. This code works the way I want in almost all cases except the ones 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); } 
+6
source share
2 answers

As others have pointed out, the best option is probably checking the length of the input string. My preferred approach would be to subclass 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); } } 
+5
source

Interesting, as DateFormatter seems to do almost all the tricks.

So why don’t you override its method, which does the final check and formatting to process all entered String that are too short as empty String .

  DateFormatter dateFormatter = new DateFormatter(dateFormat) { @Override public Object stringToValue(String text) throws ParseException { if(!getFormattedTextField().hasFocus()) if (text.length() != 4) { return null; } return super.stringToValue(text); } }; 

EDIT:

As @nIcE cOw suggested, the easiest way to serve it is with focus:

  final JFormattedTextField textField = new JFormattedTextField(dateFormatter); textField.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { super.focusLost(e); if(textField.getText().length() != 4) textField.setText(""); } }); 
+2
source

Source: https://habr.com/ru/post/918179/


All Articles