1

我有一个用于选择出生日期的 JDateChooser。它以空日期值开始,让用户使用文本字段或打开 Jcalendar 的 jdatechooser 按钮选择出生日期。

我想要做的是将 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;
}

截屏

4

2 回答 2

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());

您可以更新 a 中的另一个空文本字段PropertyChangeListener,如下所示;属性名称是"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);
        …
    }
}

图片

于 2015-03-27T16:29:16.007 回答
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);
于 2015-03-27T14:47:04.307 回答