Calendar source code – Part 2

After a fair bit of interest in the java calendar source code (here), I thought I’d make it available and explain it’s methods. Firstly, how does it work? Essentially it’s a bunch of standard swing components (JTable, JComboBoxes) used to create a calendar the user can pick a date from. The combo boxes have the month and years (they’re hard coded in, but you should probably dynamically fetch them based on whatever your specific needs are – like if you want previous years for dates of birth, or a longer forward looking timespan).

The user selects the month and year, and our swing calendar does the hard work of figuring out which days go where. For the heavy lifting, we use a GregorianCalendar instance, and then use the day of week to arrange the dates properly in the JTable. Note that the week starts on Monday.

Run the Swing Calendar as an Applet :



So here’s the methods and a rundown of what they do:

  1. createCalendarData() – pretty obvious. We create the data for the SELECTED month and year, and then insert it into the proper cells of the JTable. This method is called every time an ItemStateChanged event is fired from the 2 combo boxes. This is the most important method for the calendar widget.
  2. getSelectedDate() – again pretty obvious. It returns the selected date or null if no date is selected in the calendar. You should call this method whenever you want to get the selected date. In the example, there’s a MouseClicked event fired when the user clicks on the calendar JTable which changes the dates in the textfield. NOTE : The date only sets the selected year, month and day. It is ignorant of the time, which is set as teh local system time. you should set this if you want a specific time to be set for each date picked.
  3. initComponents() – this initializes all the components in the swing panel. The code was autogenerated from Netbeans GUI designer, and is irrelevant to functionality.

Grab the jar file here.