因此,我使用 JSpinner.DateEditor 创建了一个微调器,并稍微更改了格式化程序以验证用户输入。
JSpinner sp1 = new JSpinner(sm);
JSpinner.DateEditor de = new JSpinner.DateEditor(sp1, "hh:mm:ss a");
JFormattedTextField ftf = de.getTextField();
DateFormatter formatter = (DateFormatter) ftf.getFormatter();
formatter.setAllowsInvalid(false);
formatter.setOverwriteMode(true);
sp1.setEditor(de);
除了一件事之外,它工作得很好。例如时间是 上午 11:32:12
如果我将光标放在 32 到 12 之间的冒号之前。我得到 上午 11:02:12
但我想得到 上午 11:30:12
对此有什么帮助吗? 谢谢
最佳答案
根据这个问题的标题和所描述的行为,这一行解释了正在发生的事情:
DateFormatter formatter = (DateFormatter) ftf.getFormatter();
formatter.setAllowsInvalid(false); // here is the key
根据 DefaultFormatter#setAllowsInvalid()文档:
public void setAllowsInvalid(boolean allowsInvalid)
Sets whether or not the value being edited is allowed to be invalid for a length of time (that is,
stringToValue
throws aParseException
). It is often convenient to allow the user to temporarily input an invalid value.
当您将此属性设置为 false
时,您不允许用户键入无效值(例如通过删除某些字符,或者在这种特殊情况下插入一些非数字字符),因此格式化程序会尝试获取最接近的有效值。
这不是意外行为,而是为了与此方法提供的契约(Contract)保持一致所必需的。
关于java - 具有 DateFormatter 删除行为的 JSpinner,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24514060/