【问题标题】:JCalendar set specific date colorsJCalendar 设置特定日期颜色
【发布时间】:2013-05-23 01:51:03
【问题描述】:

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

在我的示例中,我在事件数组列表中添加了 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); 
    }
}

【问题讨论】:

  • 或者,实现IDateEvaluator,如图所示here

标签: java swing jcalendar


【解决方案1】:

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

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); 
    }
}

这有意义吗?

【讨论】:

  • 这有意义吗?是的,但我只使用代码源而不是从编译的 jar 中提取方法或 JComponent 的另一个原因
【解决方案2】:

我为面板的前七个对象(周日到周六)添加了一个常量

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

它对我有用

【讨论】:

    【解决方案3】:

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

    看下面的简单示例。

    jPanel2 = jCalendar1.getDayChooser().getDayPanel();
    Component component[] = jPanel2.getComponents();
    
    
      for (int i = 1; i <8 ; i++) {
             component[i].setBackground(Color.red);
        }
    

    这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多