如何在Java的JCalendar中只选择星期一?



我正在使用JCalendar日期选择器,想知道是否有办法通过JDateChooser组件仅选择某些工作日(例如星期一(?

有谁知道该怎么做?

下面是

一个在接受DayOfWeek对象列表DayOfWeekEvaluator实现它的示例:

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 方法(,请参阅此示例要点。

相关内容

  • 没有找到相关文章

最新更新