繁体   English   中英

如何更改 JCalendar 中特定日期的颜色?

[英]How to change colors of specific dates in JCalendar?

我在更改 JCalendar 中特定日期的颜色时遇到问题。 在某些情况下,我可以正确更改日面板的颜色,如下所示:

如图所示

它正确地突出显示了我从数据库中检索到的 10 月 5 日和 13 日。

但大多数情况下,突出显示的日期是不正确的,如下所示:

如图所示

它应该突出显示 2017 年 12 月 10 日而不是 5 日。 它似乎没有计算周日到周四的空组件,这就是为什么它显示第 5 个。

我尝试按照此处的解决方案进行操作但我不明白该怎么做。 如果您能帮我解决这个问题而无需过多更改代码,我将不胜感激。

conn=sqlconn.ConnectDB();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH,1);
int offset = cal.get(Calendar.DAY_OF_WEEK);
int mon = calendar.getMonthChooser().getMonth() + 1;
int yr = calendar.getYearChooser().getYear();
JPanel jPanel = calendar.getDayChooser().getDayPanel();
Component component[] = jPanel.getComponents();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

String sql = "SELECT DAYOFMONTH(reserve_date) as day, MONTH(reserve_date) as month, YEAR(reserve_date) as year  FROM reservation";
    try
    {
    pst = conn.prepareStatement(sql);
    rs = pst.executeQuery();
    text.setText("");
    while(rs.next()){
        int dayOfMonth = rs.getInt("day");
        int month = rs.getInt("month");
        int year = rs.getInt("year");

        if(mon == month && yr == year){
            component[dayOfMonth + offset].setBackground(Color.green);
        }

    }
    pst.close();
    rs.close();
}
catch(Exception e)
{
    JOptionPane.showMessageDialog(null, e);
}
finally{
        try{
            rs.close();
            pst.close();
        }catch(Exception e){JOptionPane.showMessageDialog(null, e);}
    }

我通过在本月的第 1 周找到隐形组件来解决这个问题。

 for(int i = 7; i < 14; i++){
            if(component[i].isVisible() == false){
                ctr++;
            }
        }

然后我只是将 ctr 的值添加到数组元素中:

if(mon == month && yr == year){
        component[dayOfMonth + offset + ctr].setBackground(Color.green);
    }

一切都在正常工作。 我希望这可以帮助别人!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM