我在使用JTextField
创建固定日期格式时遇到问题。 JTextField
是否有办法使用固定的日期格式?
答案 0 :(得分:6)
您可以将JFormattedTextField与SimpleDateFormat
一起使用DateFormat format = new SimpleDateFormat("your_format");
JFormattedTextField dateTextField = new JFormattedTextField(format);
答案 1 :(得分:2)
你应该看看
首先......
答案 2 :(得分:1)
如果您正在使用Swing,请将JFormattedTextField添加到您的JFrame。在“属性”中,单击“formatterFactory”。在对话框中,选择“日期类别”,然后选择“格式”。现在您的格式将被强制执行。
答案 3 :(得分:0)
答案 4 :(得分:0)
正如评论中所述,您可能希望查看日期选择器组件而不是文本字段。日期选择器组件将使用户免于使用日期语法的麻烦。
我建议您使用java.time(现代的Java日期和时间API)进行日期工作。因此,对于偏爱文本字段作为日期的任何人,我做了一个小实验,将JFormattedTextField
与java.time中的LocalDate
类结合使用。对于文本字段,我发现最好编写一个子类来指定我们从日期字段中获得的对象类型为LocalDate
:
public class DateField extends JFormattedTextField {
private static final long serialVersionUID = -4070878851012651987L;
public DateField(DateTimeFormatter dateFormatter) {
super(dateFormatter.toFormat(LocalDate::from));
setPreferredSize(new Dimension(100, 26));
}
@Override
public LocalDate getValue() {
return (LocalDate) super.getValue();
}
}
JFormattedTextField
接受java.text.Format
对象以格式化和解析值。来自java.time的DateTimeFormatter
有两个重载的toFormat
方法,这些方法为我们提供了java.text.Format
。甚至我们可以指定从Format
获得的对象类型的一个。
要尝试此日期字段类:
public class TestFrame extends JFrame {
public TestFrame() {
super("Test");
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.forLanguageTag("es"));
DateField dateField = new DateField(dateFormatter);
add(dateField);
dateField.setValue(LocalDate.now(ZoneId.systemDefault()));
JButton okButton = new JButton("OK");
okButton.addActionListener(ev -> JOptionPane.showMessageDialog(TestFrame.this,
"Date entered is " + dateField.getValue()));
add(okButton );
pack();
}
public static void main(String[] args) {
new TestFrame().setVisible(true);
}
}
我指定了西班牙语格式,只是为了清楚地说明格式化和解析正在进行中。在这里您可以指定自己您的用户喜欢的格式。例如DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
或DateTimeFormatter.ofPattern("dd/MM/uu")
。考虑一种简短的格式,因为大多数用户不喜欢输入多余的内容。
现在JFrame
看起来像这样:
我输入11 ago. 2020
而不是今天的日期,然后单击“确定”:
Oracle tutorial: Date Time解释了如何使用java.time。
答案 5 :(得分:-2)
我认为最好的是使用JFormatedTextField。
我有这个代码尝试这个:
package your_package;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class.....{
private String getdate(){
DateFormat format = new SimpleDateFormat("MM/DD/YYYY"); //display your format.
Date date = new Date();//puts the date in variable.
return dateformat.format(date); //returns the format to the date variable.
}
public your_app{
.....
String date = new getdate();
txtDate.setvalue(date);
}
}
希望这会给你一个想法并帮助......:)