Java JFormattedTextField用于输入日期 [英] Java JFormattedTextField for typing dates

查看:224
本文介绍了Java JFormattedTextField用于输入日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使JFormattedTextField使用格式为dd / MM / yyyy的日期。具体来说,当用户键入时,光标应该跳转斜杠,直接进入下一个数字位置。



此外,JFormattedTextField必须验证输入的日期是有效的,如果日期无效,或者将其正确到有效日期,例如用户输入13作为月份,则将其拒绝,将其设置为01,并在该年度添加+1。 / p>

我尝试用JFormattedTextField的validate()方法使用掩码(## / ## / ####)来检查日期是否有效,但是看来,这两个不能很好的一起工作(或者我在Java上太绿了,知道如何... :),然后用户可以在字段上输入任何内容。



任何帮助都非常感激!谢谢!

解决方案

您可能需要使用常规JTextField并使用自定义文档调用setDocument()。我建议扩展PlainDocument,这样可以在文档更改时轻松验证输入,并根据需要添加斜杠。


I've been having trouble to make a JFormattedTextField to use dates with the format 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.

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.

Any help is really appreciated! Thanks!

解决方案

You may have to use a regular JTextField and call setDocument() with a custom document. I recommend extending PlainDocument, this makes it easy to validate input as the document changes, and add slashes as appropriate.

这篇关于Java JFormattedTextField用于输入日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆