我正在使用JCalendar
datepicker,想知道是否有办法只通过JDateChooser
组件选择某些工作日(例如星期一)吗?
有谁知道怎么做?
答案 0 :(得分:0)
下面是将其实现为DayOfWeekEvaluator
接受DayOfWeek
对象列表的示例:
import com.toedter.calendar.IDateEvaluator;
import java.awt.Color;
import java.time.DayOfWeek;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class DayOfWeekEvaluator implements IDateEvaluator {
private final List<DayOfWeek> validDaysOfWeek;
public DayOfWeekEvaluator(List<DayOfWeek> validDaysOfWeek) {
this.validDaysOfWeek = validDaysOfWeek;
}
private DayOfWeek determineDayOfWeek(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
return DayOfWeek.of(convertSundayFirstToMondayFirst(dayOfWeek));
}
private int convertSundayFirstToMondayFirst(int sundayFirstValue) {
// Converts from weeks that are Sunday-Saturday (1-7)
// to weeks that are Monday-Sunday (1-7)
if (sundayFirstValue == 1) {
return 7;
}
return sundayFirstValue - 1;
}
@Override
public boolean isSpecial(Date date) {
return false;
}
@Override
public Color getSpecialForegroundColor() {
return null;
}
@Override
public Color getSpecialBackroundColor() {
return null;
}
@Override
public String getSpecialTooltip() {
return null;
}
@Override
public boolean isInvalid(Date date) {
DayOfWeek dayOfWeek = determineDayOfWeek(date);
return !validDaysOfWeek.contains(dayOfWeek);
}
@Override
public Color getInvalidForegroundColor() {
return null;
}
@Override
public Color getInvalidBackroundColor() {
return null;
}
@Override
public String getInvalidTooltip() {
return null;
}
}
该逻辑位于isInvalid
中使用的私有方法中。用法示例例如可以是:
List<DayOfWeek> validDaysOfWeek = Arrays.asList(DayOfWeek.MONDAY, DayOfWeek.THURSDAY);
JCalendar c = new JCalendar();
c.getDayChooser().addDateEvaluator(new DayOfWeekEvaluator(validDaysOfWeek));
c.setCalendar(Calendar.getInstance());
要查看完整的示例(使用main方法),请参见this example gist。