JFormattedTextField中严格的24小时时间

Fur*_*ers 6 java swing simpledateformat jformattedtextfield

我正在尝试创建一个只接受24小时时间的JFormattedTextField.

我非常接近解决方案,但有一个案例,其中以下代码示例不起作用.

如果输入时间"222"并从字段中更改焦点,则时间将更正为"2202".我希望它只接受一个完整的4位数24小时时间.除了我刚刚提到的那个代码之外,这个代码几乎在所有情况下都能正常工作.有什么建议?

    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);
    }
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 5

正如其他人所提到的,你最好的选择可能是验证输入字符串的长度.我首选的方法是子类化SimpleDateFormat以将所有解析逻辑保存在一个地方:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)