javamysqldatabasenetbeans-8jcalendar

How to change colors of specific dates in JCalendar?


I have a problem in changing the colors of the specific dates from JCalendar. There are some instance where I can change the color of the day panel correctly as shown here:

as shown here

It correctly highlighted the 5th and 13th of October that I retrieved from the database.

But most of the time the highlighted dates are incorrect as shown here:

as shown here

It's supposed to highlight the 10th of December 2017 and not the 5th. It seems like it doesn't count the empty components from Sunday to Thursday that's why it's showing the 5th.

I tried following the solution here but I can't understand how to do it. I would appreciate if you can help me figure this out without changing the code too much.

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

Solution

  • I solved this by finding the invisible component in the 1st week of the month.

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

    Then I just added the value of ctr to the array element:

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

    Everything is working as they should. I hope this helps someone!