private void calculateCalendar() {
        // clear the selected date
        if (null != selectedDay) {
            selectedDay.setBackground(white);
            selectedDay = null;
        }

        // get the first day of the selected year and month
        final GregorianCalendar c = new GregorianCalendar(
                selectedDate.get(Calendar.YEAR),
                selectedDate.get(Calendar.MONTH),
                1);
        c.setMinimalDaysInFirstWeek(1);// fix for different locales
        c.setFirstDayOfWeek(Calendar.SUNDAY);

        // figure out the maximum number of days in the month
        final int maxDay = calculateDaysInMonth(c);

        // figure out the day that should be selected in this month
        // based on the previously selected day and the maximum number
        // of days in the month
        final int selectedDay = Math.min(maxDay, selectedDate.get(
                Calendar.DATE));

        // clear the days up to the first day of the month
        int dow = c.get(Calendar.DAY_OF_WEEK);
        for (int dd = 0; dd < dow; dd++) {
            daysInMonth[0][dd].setText("");
            daysInMonth[0][dd].setBackground(gray);
        }

        // construct the days in the selected month
        int week;
        do {
            week = c.get(Calendar.WEEK_OF_MONTH);
            dow = c.get(Calendar.DAY_OF_WEEK);
            final JTextField fld = this.daysInMonth[week - 1][dow - 1];
            fld.setText(Integer.toString(c.get(Calendar.DATE)));
            if (selectedDay == c.get(Calendar.DATE)) {
                fld.setBackground(highlight);
                this.selectedDay = fld;
            } else
                fld.setBackground(white);
            if (c.get(Calendar.DATE) >= maxDay)
                break;
            c.add(Calendar.DATE, 1);
        } while (c.get(Calendar.DATE) <= maxDay);

        // clear all the days after the last day of the month
        week--;
        for (int ww = week; ww < daysInMonth.length; ww++) {
            for (int dd = dow; dd < daysInMonth[ww].length; dd++) {
                daysInMonth[ww][dd].setText("");
                daysInMonth[ww][dd].setBackground(gray);
            }
            dow = 0;
        }

        // set the currently selected date
        c.set(Calendar.DATE, selectedDay);
        selectedDate = c;
    }