Background color on specific dates using JCalendar

烈酒焚心 提交于 2019-12-02 06:29:12

One solution that uses the JCalendar API is to create your own instance of IDateEvaluator and checks if a date has anything "special" about it.

1. Converting

First I suggest getting your dates (yyyy-MM-dd) into a list and convert them to Date objects. For example:

List<String> mysqlDates = Arrays.asList("2019-02-14", "2019-03-06"); // Assume you've got this info somehow
List<Date> specialDates = convertToDates(mysqlDates);

With the help of the following function:

public static List<Date> convertToDates(List<String> dateStrings) throws ParseException {
    List<Date> dates = new ArrayList<>();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    for (String dateString : dateStrings) {
        dates.add(df.parse(dateString));
    }

    return dates;
}

2. Create your SpecialDateEvaluator

Then you need to create your own date evaluator that takes in the Date objects that are going to be handled differently. A simple example would be the following:

public class SpecialDateEvaluator implements IDateEvaluator {

    private final List<Date> specialDates;

    public SpecialDateEvaluator(List<Date> specialDates) {
        this.specialDates = specialDates;
    }

    @Override
    public boolean isSpecial(Date date) {
        for (Date d : specialDates) {
            if (d.equals(date)) {
                return true;
            }
        }

        return false;
    }

    @Override
    public Color getSpecialForegroundColor() {
        return Color.black;
    }

    @Override
    public Color getSpecialBackroundColor() {
        return Color.red;
    }

    @Override
    public String getSpecialTooltip() {
        return null;
    }

    @Override
    public boolean isInvalid(Date date) {
        return false;
    }

    @Override
    public Color getInvalidForegroundColor() {
        return null;
    }

    @Override
    public Color getInvalidBackroundColor() {
        return null;
    }

    @Override
    public String getInvalidTooltip() {
        return null;
    }
}

3. Utilize the date evaluator

To utilize the evaluator you need to add it to the JDayChooser, taking in the list of Date objects and then setting the Calendar again to refresh the view. For example:

JCalendar c = new JCalendar();
c.getDayChooser().addDateEvaluator(new SpecialDateEvaluator(specialDates));
c.setCalendar(Calendar.getInstance());

To see a full example of this (with a main method), see this example gist.

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