gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:46:04 25 4
gpt4 key购买 nike

我正在使用JCalendar datepicker 并想知道是否有办法通过 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 中使用的私有(private)方法中。示例用法可以是:

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 .

关于java - 如何在 Java 的 JCalendar 中只选择星期一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47310130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com