0

我正在使用解决方案中的代码在 toedter 的 JCalendar 中将特定日期的颜色设置为Add specific background colors to JDaychooser Dates。这个解决方案的问题在于它为每个月设置了不同的日期,因为每个月的第一天是不同的。

在我的示例中,我在事件数组列表中添加了 5 月 4 日和 9 月 4 日。+9 从 5 月工作的那一天开始,但在 9 月它将选择 7,因为该月的第一天从 +6 开始。

我想知道是否有办法获取当月的开始日期,但我似乎无法在 API 文档中找到执行此操作的方法。

在此处输入图像描述

这是我的代码:

Calendar cal = Calendar.getInstance();
cal.setTime(calendar.getDate());
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);

JPanel jpanel = calendar.getDayChooser().getDayPanel();
Component component[] = jpanel.getComponents();

//arraylist of events
for(int i = 0; i < events.size(); i++)
{
    //selected month and year on JCalendar
    if(month == events.get(i).getMonth() && year == events.get(i).getYear())
    {
        //this value will differ from each month due to first days of each month
         component[ events.get(i).getDay() + 9 ].setBackground(Color.blue); 
    }
}
4

3 回答 3

2

您需要的是获取该月第一天的偏移量。分析你知道这与星期几相关的日历。

Calendar cal = Calendar.getInstance();
cal.setTime(calendar.getDate());
int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);

JPanel jpanel = calendar.getDayChooser().getDayPanel();
Component component[] = jpanel.getComponents();

//arraylist of events
for(int i = 0; i < events.size(); i++)
{
    //selected month and year on JCalendar
    if(month == events.get(i).getMonth() && year == events.get(i).getYear())
    {
         // Calculate the offset of the first day of the month
         cal.set(Calendar.DAY_OF_MONTH,1);
         int offset = cal.get(Calendar.DAY_OF_WEEK) - 1;

        //this value will differ from each month due to first days of each month
         component[ events.get(i).getDay() + offset ].setBackground(Color.blue); 
    }
}

那有意义吗?

于 2013-05-23T02:39:58.097 回答
0

一个简单的解决方案是你必须在日历中获得每个敢于的面板,然后你可以轻松地改变它的颜色。

看下面的简单示例。

jPanel2 = jCalendar1.getDayChooser().getDayPanel();
Component component[] = jPanel2.getComponents();


  for (int i = 1; i <8 ; i++) {
         component[i].setBackground(Color.red);
    }

这会有所帮助。

于 2013-11-14T09:44:43.913 回答
0

I added a constant for the seven first objects of panel (Sunday to Saturday)

component[ events.get(i).getDay() + offset + 7].setBackground(Color.blue); 

and it worked for me

于 2013-06-27T05:34:55.263 回答