FeaturesPluginsDocs & SupportCommunityPartners

Using the Calendar Component

This tutorial describes how to work with the JSF 1.2 (Woodstock) Calendar component in NetBeans IDE 6.0 and 6.1. This tutorial shows how to set the minimum and maximum calendar date and how to verify that a date that the user selects falls within this range.

Contents

Content on this page applies to NetBeans IDE 6.0 and 6.1

Image file used in this tutorial

ยป table_title_solid.gif

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required
NetBeans IDE version 6.1 or
version 6.0
Java Developer Kit (JDK) version 6 or
version 5
JavaServer Faces Components/
Java EE Platform
1.2 with Java EE 5* or
1.1 with J2EE 1.4
GlassFish Application Server V2
Travel Database Not required

* To take advantage of NetBeans IDE's Java EE 5 capabilities, use an application server that is fully compliant with the Java EE 5 specification, such as the GlassFish Application Server V2 UR2. If you are using a different server, consult the Release Notes and FAQs for known problems and workarounds. For detailed information about the supported servers and Java EE platform, see the Release Notes.

Note for NetBeans IDE 6.1 users:

  • Creating a project in NetBeans 6.1 includes new options which can be left at the default. For example, the Use Dedicated Folder for Storing Libraries checkbox may be left unselected.
  • NetBeans IDE 6.1 features on-demand binding. Where components require Java coding, you must now manually add the binding attribute to components in a Visual Web JSF application. To do so, right-click each component and choose Add Binding Attribute. For more information, see the On-demand Binding Attribute Wiki.

Picking a Calendar Date

This tutorial uses the JSF 1.2 Calendar component found in the Basic section of the Palette. You begin by adding the Calendar to your project. You then add code to validate that the date the user picks falls within a default minimum and maximum Calendar range.


Note: NetBeans IDE 6.1 features on-demand binding. Where components require Java coding, you must now manually add the binding attribute to components in a Visual Web JSF application. To do so, right-click each component and choose Add Binding Attribute. For more information, see the On-demand Binding Attribute Wiki.

  1. Create a new Visual Web JSF application project, name it CalendarExample, and enable the Visual Web JavaServer Faces framework.

    You design the page as shown in the following figure.

    Calendar Format Page Design
  2. From the Woodstock Basic section of the Palette, drag a Calendar component onto the page.
  3. In the Properties window, set the the following values:

    Property     Value
    id startCalendar
    dateFormatPatternHelp MM/dd/yyyy
    label Start Date:
    required Checkmark icon for True
  4. Place a Message component to the right of the Calendar component. Press the Ctrl-Shift keys and drag a line from the Message Component to the Calendar component.

    This action enables the Message component to display error messages for the Calendar.
  5. Place a Static Text component below the Calendar component. Set the id property to validationMsgStaticText.
  6. Place a Button component below the Static Text component, type Validate, and press Enter. In the Properties window, set the id property to validateButton.
  7. Double-click the Validate button, and add the following code to the validateButton action method:

    Code Sample 1: Code to Validate Calendar Date
    public String validateButton_action() {
            validationMsgStaticText.setText(
                    (String)DateFormat.getDateInstance(
                    DateFormat.MEDIUM).format(startCalendar.getSelectedDate())
                    + " is a valid date.");
            return null;
        }

    This code gets the date that the user entered into the Calendar. If the date is between the minimum and maximum dates set for the Calendar, then the Static Text displays the date and indicates that it is valid.
  8. Right-click, then choose Fix Imports from the pop-up menu to resolve the DateFormat not found error.
  9. Deploy and run the application, and then open the pop-up calendar.

    The Calendar displays the current month and year. By default, the earliest valid date that you can select is 100 years before the current date, and the last valid date is 100 years after the current date.
  10. Choose a date from the pop-up calendar and then click the Validate button.

    If the date you selected falls within the default minimum and maxium dates, the Static Text displays a valid message, as shown in the following figure. If you choose a date outside this range, you see a validation error message.

    Calendar Date Format

Setting the Minimum and Maximum Calendar Dates

By default, the Calendar spans just over 200 years. In most cases, however, you want to define a span specific to your application. In this section, you limit the Calendar span to one year by setting the minimum property to today's date and the maximum property to one year from today.


Note: NetBeans IDE 6.1 features on-demand binding. Where components require Java coding, you must now manually add the binding attribute to components in a Visual Web JSF application. To do so, right-click each component and choose Add Binding Attribute. For more information, see the On-demand Binding Attribute Wiki.

  1. In the Java Editor, scroll to the preprocess method. Add the following code (shown in bold) to clear the existing message in the Static Text component.

    Code Sample 2: Clear Old Valid Date Message
    public void preprocess() {
            // Clear out old valid date message before start
            // new validations
            validationMsgStaticText.setText("");
    }
  2. Find the prerender method. Add the following code to pre-populate the Calendar text field with today's date.

    Code Sample 3: Set Default Start Date
    public void prerender() {
            // Set default start date, if not
            // already entered
            java.util.Calendar date = GregorianCalendar.getInstance();
            if (startCalendar.getSelectedDate() == null) {
                startCalendar.setSelectedDate(date.getTime());
            }
    }

    The code displays an error because it cannot find the GregorianCalendar variable. You add an import statement for this class later in this section.
  3. Add the following two methods above the validateButton action method.

    Code Sample 4: Set Minimum and Maximum Calendar Dates
    private Date minCalDate;
    
         public Date getMinCalDate() {
           java.util.Calendar date = java.util.Calendar.getInstance
               (FacesContext.getCurrentInstance().getViewRoot().getLocale());
           // Have to zero out the time because
           // the date comparison is time sensitive
           date.set(java.util.Calendar.HOUR_OF_DAY, 0);
           date.set(java.util.Calendar.MINUTE, 0);
           date.set(java.util.Calendar.SECOND, 0);
           date.set(java.util.Calendar.MILLISECOND, 0);
           return date.getTime();
       }
    
        private Date maxCalDate;
    
        public Date getMaxCalDate() {
            java.util.Calendar date = GregorianCalendar.getInstance();
            date.set(java.util.Calendar.HOUR_OF_DAY, 0);
            //here is where you adjust your time period
            date.add(java.util.Calendar.YEAR, 1);
    		SimpleDateFormat formatter
                    = new SimpleDateFormat("EEE, MMM d, yyyy 'at' hh:mm:ss a zzz");
            error(formatter.format(date.getTime()));
            maxCalDate = date.getTime();
            return maxCalDate;
        }

    The getMinCalDate method sets the Calendar's minimum date to today. In the getMaxCalDate method, the line date.add(java.util.Calendar.YEAR, 1); sets the maximum date to one year from today. For more examples on setting the minimum and maximum dates, including how to set the calendar to display past years, see the section of this tutorial titled Tips for Using the Calendar Component .
  4. Right-click in the Java Editor and choose Fix Imports from the pop-up menu. Ensure that java.util.Date appears in the Date field and click OK.
  5. Return to the Visual Designer, right-click the Calendar component, and choose Property Bindings from the pop-up menu.
  6. In the Property Bindings dialog box, bind the Calendar's minDate property to Page 1's minCalDate, as shown in the following figure. Click Apply.

    Binding for mindate property
  7. Bind the Calendar's maxDate property to Page 1's maxCalDate, and click Apply. Click Close to close the dialog box.
  8. Run the application. The selected value renders today's date. Open the Calendar pop-up and note that today's date is highlighted. Also note that the Calendar now spans from January of the current year through December of the following year.
  9. Choose any date in the Calendar and then click the Validate button.

    If the date is within one year of today's date, the application displays a valid message. If you pick a date before or after this range, the application displays an error message.

Validating a Calendar Range

Now suppose you are developing a travel program. You want users to select a starting date and ending date for a trip, and the trip must be at least one week long. In this section, you add an End Calendar to the application. You add code to validate that the date the user sets in the End Calendar is at least one week after the date set in the Start Calendar.


Note: NetBeans IDE 6.1 features on-demand binding. Where components require Java coding, you must now manually add the binding attribute to components in a Visual Web JSF application. To do so, right-click each component and choose Add Binding Attribute. For more information, see the On-demand Binding Attribute Wiki.

  1. Place a Calendar component on the page directly underneath the Start Calendar. Adjust the other components as necesary. Following is the page you design in this section.

    Page that includes an end calendar
  2. In the Properties window for the new Calendar, set the following values:

    Property     Value
    id endCalendar
    dateFormatPatternHelp MM/dd/yyyy
    label End Date:
    required Checkmark icon for True
  3. Place a Message component to the right of the Calendar component. Press the Ctrl-Shift keys and drag a line from the Message Component to the Calendar component.
  4. Right-click the End Calendar component and choose Property Bindings from the pop-up menu.
  5. Bind the End Calendar's minDate property to the Page 1's minCalDate. Click Apply.
  6. Bind the End Calendar's maxDate property to Page1's maxCalDate. Click Apply, then close the Property bindings dialog box.
  7. In the Visual Designer, right-click the End Calendar component and choose Edit Event Handler > validate.

    Note: NetBeans IDE 6.1 features on-demand binding. If you are using NetBeans IDE 6.1, you must manually add a binding attribute to the endCalendar component on Page 1. To do so, right-click each component and choose Add Binding Attribute. For more information, see the On-demand Binding Attribute Wiki.

  8. Add the following code to the endCalendar_validate() method. This code ensures that the end date is at least one week after the start date.

    Code Sample 5: Code to Validate Start Date
    public void endCalendar_validate(FacesContext context,
               UIComponent component, Object value) {
            java.util.Calendar endDate = GregorianCalendar.getInstance();
            endDate.setTime((Date)value);
            java.util.Calendar startDate = GregorianCalendar.getInstance();
            startDate.setTime(startCalendar.getSelectedDate());
            if (startCalendar.getSelectedDate() != null) {
                if (startDate.after(endDate)) {
                    throw new ValidatorException(new FacesMessage
                            ("End date must be after start date."));
                } else {
                    startDate.add(java.util.Calendar.DATE, 7);
                    if (startDate.after(endDate)) {
                        throw new ValidatorException(new FacesMessage
                             ("End date must be at least one week after the start date."));
                    }
    
                }
            }
        }
  9. Right-click in the Java Editor and choose Fix Imports to fix the FacesMessage and ValidatorExeception errors.
  10. Modify the validateButton action method to include validation for the End Calendar date:

    Code Sample 6: Code to Validate End Date
    public String validateButton_action() {
                SimpleDateFormat formatter
                    = new SimpleDateFormat("EEE, MMM d, yyyy");
            validationMsgStaticText.setText(
                    formatter.format(startCalendar.getSelectedDate())
                    +
                    " - "
                    +
                    formatter.format(endCalendar.getSelectedDate())
                    + " is a valid date range.");
            return null;
        }
  11. Run the application. Choose a Start Date and End Date and then click the Validate button.

    If the dates are between the minimum and maximum dates (today and one year from today), and if the end date is more than one week past the start date, the application displays a valid message as shown in the following figure. Otherwise, the application displays an error message as shown in the figure below.

    Calendar Range - Invalid Results

Changing the Calendar Style

You can change the color and style of the Calendar component. Here you change the appearance of the table title in the Calendar component.

  1. Save the image table_title_solid.gif to your projects_directory\CalendarExample\web\resources directory.
  2. In the Projects window, double-click the CalendarExample > Web Pages > resources node > stylesheet.css node. Add the code in either Code Sample 7 or 8, depending on which version of JavaServer Faces components you are using.

    Code Sample 7: Stylesheet Code for JavaServerFaces 1.1 Calendar
    .CalPopDiv .DatSelDiv{
    background-image:url(table_title_solid.gif);
    }
    
    .CalPopDiv .DatDayHdrTxt {
    color: red
    }
      

    Code Sample 8: Stylesheet Code for JavaServer Faces 1.2 Calendar
    .CalPopDiv_sun4 .DatSelDiv_sun4 {
    background-image:url(table_title_solid.gif);
    }
    
    .CalPopDiv_sun4 .DatDayHdrTxt_sun4 {
    color: red
    }
    
      

    The first style class sets a new background image for the pop-up Calendar title. The second style class sets the color of the day header text to red.

    A complete list of CSS styles for the Calendar component is available in the NetBeans online help. Choose Help > Help Contents from the main menu and search for the topic Calendar Component CSS Classes.
  3. Deploy and run the application, then open the pop-up Calendar.

Tips for Using the Calendar Component

  • Code Sample 4 includes the following code in the getMaxCalDate method to set the maximum value to one year from the minimum value:
    date.add(java.util.Calendar.YEAR, 1);
    To adjust the time period for a number of days, such as a week, use code similar to the following:
    date.add(java.util.Calendar.DATE, 7);
  • Code Sample 4 also includes code in the getMinCalDate method to set the minimum date to today. To display past years in the calendar, use code similar to the following. This code displays the past ten calendar years:
    date.add(java.util.Calendar.YEAR, -10);
    
  • To change the Calendar's date format, click the ellipsis button in the dateFormatPattern property and select a predefined date format. If the Property Editor does not include the format you want, you may create your own. The values you can enter are limited to some combination of yyyy for the year, MM for the month, and dd for the day. Typical separator characters are slash (/), period (.), and dash (-).

Summary

In this tutorial, you added a Calendar component to a Visual Web JSF Page, and then set the minimum and maximum dates. You also add a Validator component, and added code to validate that the date the user sets in the End Calendar is at least one week after the date set in the Start Calendar. You also changed the style of the calendar.


See Also


This page was last modified: April 15, 2008


Bookmark this page

del.icio.us furl simpy slashdot technorati digg
Companion
Projects:
MySQL Database Server   Open JDK: an Open SourceJDK   GlassFish Community: an Open Source Application Server    Mobile & Embedded Community    Open Solaris   java.net - The Source for Java Technology Collaboration   Open ESB - The Open Enterprise Service Bus Powered by