Disable past dates and 2 weeks from now in JCalendar

谁都会走 提交于 2019-12-02 18:59:54

问题


I want to disable past dates and 2 weeks from now from a JCalendar.

I already have this code:

jDateChooser1.getJCalendar().setMinSelectableDate(new Date());
((JTextFieldDateEditor)jDateChooser1.getDateEditor()).setEditable(false);

I already can disable past dates but how about disabling future dates like 2 weeks from now?


回答1:


As shown here, you can use an IDateEvaluator like MinMaxDateEvaluator to invalidate a range of dates:

private static class RangeEvaluator extends MinMaxDateEvaluator {

    @Override
    public boolean isInvalid(Date date) {
        return !super.isInvalid(date);
    }
}

Then you can specify a range of invalid dates, e.g. a day before and two weeks after:

    Calendar min = Calendar.getInstance();
    min.add(Calendar.DAY_OF_MONTH, -1);
    Calendar max = Calendar.getInstance();
    max.add(Calendar.DAY_OF_MONTH, 13);
    RangeEvaluator re = new RangeEvaluator();
    re.setMinSelectableDate(min.getTime());
    re.setMaxSelectableDate(max.getTime());
    JCalendar jc = new JCalendar();
    jc.getDayChooser().addDateEvaluator(re);
    jc.setCalendar(jc.getCalendar());

Note that you can add multiple instances of RangeEvaluator to handle different ranges.




回答2:


I haven't tried this but I imagine using a date in the future would do this:

Date d = new Date();
d.setTime(d.getTime() + 14 * 86400 * 1000); -- set the date 14 days forward
jDateChooser1.getJCalendar().setMinSelectableDate(d);
((JTextFieldDateEditor)jDateChooser1.getDateEditor()).setEditable(false);

Instead of working with a Date object and having to use setTime(milliseconds) you might want to use a proper Calendar object which has better methods for altering the date and so on.

Calendar cal = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 14);
Date twoweeks = calendar.getTime();



回答3:


I already have answered my own question by the help of trashgod's code.

Here:

Calendar min = Calendar.getInstance();
min.add(Calendar.DAY_OF_MONTH, 15);
Calendar max = Calendar.getInstance();
max.add(Calendar.DAY_OF_MONTH, 2000000);
RangeEvaluator re = new RangeEvaluator();
re.setMinSelectableDate(min.getTime());
re.setMaxSelectableDate(max.getTime());
// JCalendar jc = new JCalendar();


 jDateChooser1.getJCalendar().setMinSelectableDate(min.getTime());
 jDateChooser1.getJCalendar().setMaxSelectableDate(max.getTime());
((JTextFieldDateEditor)jDateChooser1.getDateEditor()).setEditable(false);

Thanks! :D



来源:https://stackoverflow.com/questions/26321454/disable-past-dates-and-2-weeks-from-now-in-jcalendar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!