我有一个JDateChooser,用于选择出生日期。它从null日期值开始,让用户使用textfield或jdatechooser按钮打开Jcalendar来选择出生日期。
我要做的是将JCalendar的日期设置为当前日期的-10年。默认情况下,JCalendar正在设置当前年份的日期。我尝试了这段代码,但它不起作用 - 它仍然将日期设置为当前日期。任何帮助都可以。谢谢!
dcBirthDateNew = new JDateChooser();
dcBirthDateNew.setDateFormatString("MM/dd/yyyy");
dcBirthDateNew.getDateEditor().getUiComponent().addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent evt) {
if (evt.getSource() instanceof JTextComponent) {
final JTextComponent textComponent=((JTextComponent)evt.getSource());
SwingUtilities.invokeLater(new Runnable(){
public void run() {
textComponent.selectAll();
}});
}
}
});
JCalendar calx = dcBirthDateNew.getJCalendar();
calx.setCalendar(getPrevDate());
private static Calendar getPrevDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date myDate = new Date(System.currentTimeMillis());
System.out.println("result is "+ dateFormat.format(myDate));
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.add(Calendar.YEAR, -10);
System.out.println(dateFormat.format(cal.getTime()));
return cal;
}
答案 0 :(得分:4)
这似乎工作正常。
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, -10);
JDateChooser chooser = new JDateChooser(c.getTime());
this.add(chooser);
附录:弹出式编辑器的日期默认为JDateChooser
中的值;如果您明确设置它,它将成为默认值:
JDateChooser chooser = new JDateChooser();
chooser.getDateEditor().setDate(c.getTime());
您可以更新PropertyChangeListener
中的另一个空文本字段,如图here所示;属性名称为"date"
。
附录:仔细观察,JDateChooser
ActionListener
实施处理上述默认日期。您可以覆盖它,替换下面显示的行,以创建不同的默认值。
JDateChooser chooser = new MyDateChooser();
this.add(chooser);
…
private static class MyDateChooser extends JDateChooser {
@Override
public void actionPerformed(ActionEvent e) {
…
Date date = dateEditor.getDate();
if (date == null) {
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, -10);
calendar.setTime(c.getTime());
} else {
calendar.setTime(date);
}
jcalendar.setCalendar(calendar);
…
}
}
答案 1 :(得分:0)
也许有另一种方法可以做到这一点,但这就是我所拥有的:
Date date = new Date();
Calendar calendar = Calendar.getInstance();
int subtractYearValue = 10;
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
int currentDate= Calendar.getInstance().get(Calendar.DATE);
calendar.set(currentYear - subtractYearValue , currentMonth , currentDate);
date.setTime(calendar.getTimeInMillis());
dateChooser.setDate(date);