【发布时间】:2012-09-29 19:34:05
【问题描述】:
我无法使用JTextField 创建固定日期格式。 JTextField 有没有固定日期格式的方法?
【问题讨论】:
-
或者使用更现代的 UI 组件,例如
JXDatePicker
标签: java swing date jtextfield
我无法使用JTextField 创建固定日期格式。 JTextField 有没有固定日期格式的方法?
【问题讨论】:
JXDatePicker
标签: java swing date jtextfield
您可以将 JFormattedTextField 与 SimpleDateFormat 一起使用
DateFormat format = new SimpleDateFormat("your_format");
JFormattedTextField dateTextField = new JFormattedTextField(format);
【讨论】:
你应该看看
对于初学者...
【讨论】:
如果您使用的是 Swing,请将 JFormattedTextField 添加到您的 JFrame。在属性中,单击 formatterFactory。在对话框中,选择日期类别,然后选择格式。现在您的格式将被强制执行。
【讨论】:
正如 cmets 中所说,您可能更喜欢查看日期选择器组件而不是文本字段。日期选择器组件将使用户免于为日期语法而苦恼。
我建议您使用现代 Java 日期和时间 API java.time 进行日期工作。因此,对于喜欢使用文本字段作为日期的任何人,我做了一个小实验,将 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。
【讨论】:
我认为最好的方法是使用 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);
}
}
希望这会给你一个想法和帮助... :)
【讨论】: