简体   繁体   English

Java JFormattedTextField用于键入日期

[英]Java JFormattedTextField for typing dates

I've been having trouble to make a JFormattedTextField to use dates with the format dd/MM/yyyy. 我一直无法使JFormattedTextField使用格式为dd / MM / yyyy的日期。 Specifically, as the user types, the cursor should "jump" the slashes, and get directly to the next number position. 具体来说,当用户键入内容时,光标应“跳”斜线,并直接到达下一个数字位置。

Also, the JFormattedTextField must verify if the date entered is valid, and reject it somehow if the date is invalid, or "correct it" to a valid date, such as if the user input "13" as month, set it as "01" and add +1 to the year. 另外,JFormattedTextField必须验证输入的日期是否有效,如果日期无效,则以某种方式拒绝它,或者将其“更正”为有效日期,例如,如果用户输入“ 13”作为月份,则将其设置为“ 01”。 ”,然后在年份中加+1。

I tried using a mask ("##/##/####") with the validate() method of JFormattedTextField to check if the date is valid, but it appears that those two don't work well together (or I'm too green on Java to know how... :), and then the user can type anything on the field. 我尝试通过JFormattedTextField的validate()方法使用掩码(“ ## / ## / ####”)来检查日期是否有效,但是看来这两个不能很好地协同工作(或在Java上太绿色了,不知道怎么做... :),然后用户可以在字段中键入任何内容。

Any help is really appreciated! 任何帮助都非常感谢! Thanks! 谢谢!

尝试使用JCalendar

You may have to use a regular JTextField and call setDocument() with a custom document. 您可能必须使用常规JTextField并使用自定义文档调用setDocument()。 I recommend extending PlainDocument, this makes it easy to validate input as the document changes, and add slashes as appropriate. 我建议扩展PlainDocument,这样可以在文档更改时轻松验证输入,并在需要时添加斜杠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM