Java 如何从JFormattedTextField中读取SimpleDataFormat格式的日期?
我有一个Java 如何从JFormattedTextField中读取SimpleDataFormat格式的日期?,java,swing,date-format,jformattedtextfield,Java,Swing,Date Format,Jformattedtextfield,我有一个JFormattedTextField的代码,它接受用户输入的日期 DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); JFormattedTextField DOB = new JFormattedTextField(df); 现在,当用户提交表单时,如何从JFormattedTextField读取日期 例如,如果它是一个JTextField,我们使用fieldname.getText(),您可以使用getText,但这只会返回用户
JFormattedTextField
的代码,它接受用户输入的日期
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
JFormattedTextField DOB = new JFormattedTextField(df);
现在,当用户提交表单时,如何从JFormattedTextField
读取日期
例如,如果它是一个
JTextField
,我们使用fieldname.getText()
,您可以使用getText
,但这只会返回用户输入的值
如果调用getValue
,它将返回一个Date
对象(如果文本无效,则返回null
)
您可以使用
DateFormat
来设置Date
值的格式,但我会将其保留为Date
,直到您需要对其进行其他操作,这样做更加灵活您可以使用getValue()
并将其强制转换为太宽(我们不是帮助台),而无需SSCCE/MCVE、简短、可运行、可编译,阅读Oracle教程avoud JFormattedTextField和JSpinner(可能有更好的解释),因为除了XxxDateFormat没有返回值(getValue)之外,我是否只写DOB.getValue()
?这是我的选择,但显示了一个错误,说“对象无法转换为字符串”这将是一个日期,您需要强制转换它,所以我像这样强制转换它(SimpleDateFormat)DOB.getValue()
,它给出了一个新错误“java.lang.ClassCastException:java.util.Date不能强制转换为java.text.SimpleDateFormat”