Strict 24-hour time in JFormattedTextField

你离开我真会死。 提交于 2019-12-22 05:19:31

问题


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);
    }

回答1:


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);
  }
}



回答2:


I wonder since the DateFormatter appears to do 'almost' all the trick.

Therefore, why don't you Override its method one that does the final validation and formatting to treat all entered Strings 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 suggested by @nIcE cOw the easiest will be to serve it on focus lost:

    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("");
        }
    });


来源:https://stackoverflow.com/questions/11051250/strict-24-hour-time-in-jformattedtextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!