如何在JCalendar中禁用或突出显示日期

问题描述 投票:2回答:1

在我的情况下,我想在Java日历中禁用或突出显示日期。我使用JCalendarDateChooserCombo,但找不到办法。最后,我尝试了以下代码,但也没有成功。

例如:我想禁用从14-09-1323-09-13的所有日期。

DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
try {
     Date d1 = formatter.parse("2013-09-14");
     Date d2 = formatter.parse("2013-09-23");
     jCalendar1.setSelectableDateRange(d1, d2);
 } catch (ParseException ex) {
    ex.printStackTrace();
 }
java swing simpledateformat jcalendar jdatechooser
1个回答
7
投票

我知道这已经暂停了一段时间,但希望它对某人有用。这里的关键是实现IDateEvaluator接口,用于验证日期是特殊的还是无效的。不幸的是,JCalendar库只提供了一个具体实现,它是MinMaxDateEvaluatorclass,但以此为起点并不是那么复杂。

RangeEvaluator

以下是实施示例,请特别注意isInvalid(Date date)方法。您也可以查看DateUtil类,它也是JCalendar库的一部分。

class RangeEvaluator implements IDateEvaluator {

    private DateUtil dateUtil = new DateUtil();

    @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) {
        return dateUtil.checkDate(date);
        // if the given date is in the range then is invalid
    }        

    /**
     * Sets the initial date in the range to be validated.
     * @param startDate 
     */
    public void setStartDate(Date startDate) {
        dateUtil.setMinSelectableDate(startDate);
    }

    /**
     * @return the initial date in the range to be validated.
     */
    public Date getStartDate() {
        return dateUtil.getMinSelectableDate();
    }

    /**
     * Sets the final date in the range to be validated.
     * @param endDate 
     */
    public void setEndDate(Date endDate) {
        dateUtil.setMaxSelectableDate(endDate);
    }

    /**
     * @return the final date in the range to be validated.
     */
    public Date getEndDate() {
        return dateUtil.getMaxSelectableDate();
    }        
}

Using RangeEvaluatorclass

下面有一个使用RangeEvaluator类的例子。请注意,9月14日至9月23日的停车场将被禁用。

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

RangeEvaluator evaluator = new RangeEvaluator();
evaluator.setStartDate(dateFormat.parse("2013-09-14"));
evaluator.setEndDate(dateFormat.parse("2013-09-23"));

JCalendar calendar = new JCalendar(Locale.US);
calendar.getDayChooser().addDateEvaluator(evaluator); // evaluator must be added to a JDayChooser object

Screenshot

© www.soinside.com 2019 - 2024. All rights reserved.