问题
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