http://www.developer.com/

Back to article

Using Javascript Components in Java Studio Creator


June 2, 2005

Sun's Java Studio Creator is based around the use of easy, pre-defined controls and components. There is a useful set of these included with the product, but they only go so far; for example, some of the more obvious omissions are popup calendars, sortable grids, and tree components.

The idea is that in time, third parties will write and sell component add-ins, or they will be provided in future versions of Creator. Indeed, some companies, such as Software FX and Soft Aspects, have some pretty good components out there, and although it's early days, these can help fill in the gaps.

As shown in my last article about using JSTL in Creator, other possibilities exist than just buying third-party JSF components, however. JSTL is a great way of creating completely custom HTML pages in Creator. Another option that you will explore in this article is drawing on the large number of JavaScript components and add-ins to help fill in some of the blanks in the Creator component and control library.

The inclusion of JavaScript into a Creator project is no big deal, but learning the rules of how to make these components interact with Creator code is the real target of this article. It is important to know the handles used for fields on the page so that the JavaScript can get and set values and so forth.

Please download the accompanying demo project for this from here.

Before running this project for the first time, be sure to do a full re-build (Build->Build Project from the menu) because I have removed various transitional build files to keep the zip file size small, and a full re-build will restore the missing files.

Demonstration Components

For this article, I located an excellent example library of JavaScript components developed by Matt Kruse. He kindly agreed to let me use the components in writing this article. I am using the Calendar and Tree components in this article, but I would strongly recommend visiting his page and seeing what other components are available there, and please, if you use them, consider donating something to Matt.

The Calendar component I am using is a perfect fit in Creator, which has no calendar pop-up of its own. The Calendar component is very slick, using a DHTML div to make the popup appear instantly, and good use of CSS to make it look nice.

The Tree component is similarly slick, working on a standard HTML list and making it collapsible. Combined with JSTL usage (see my previous article for more details on this), it will be possible to create a completely dynamic data-driven tree.

This article is only going to cover the basic usage of these Javascript components in Creator, and does not deal with the subject of making custom controls from them that can be added to the palette. I aim to cover that subject in a future article.

About the Demo Project

As with the previous article, I have provided an example project that demonstrates the ideas and principles described here. This is not a click-along article, but rather a coverage of the main points, for brevity.

Calendar popup

The first demo is the inclusion of a calendar popup for an ordinary text control on a page. The basic approach is this:

  1. Include the necessary JavaScript libraries into the project.
  2. Add a text field on a new page with a date time converter on it to interpret the string edited using the popup.
  3. Using the source view of the page, include the necessary JavaScript and link to attach the popup to the text field.
  4. Add other components to submit the page and echo back the date selected.

Adding the JavaScript libraries

The calendar popup can be downloaded from Matt's calendar page; the one linked here is the combined script. That means that the one file has all of the javascript necessary—I recommend this because it makes it easier to deploy the single file for the calendar popup.

Add the JavaScript to the Creator project as follows:

  1. In the project view, right-click on the Web Pages section and select new folder from the options.
  2. Create a folder called javascript.
  3. Find the new folder by using Windows Explorer (or Linux equivalent) and copy the JavaScript calendar file into that folder, and call the file CalendarPopup.js.

This same approach can be used for any JavaScript library you want to use. To include the script in Creator, you then can use the path javascript/MyScript.js to find it.

Add a Text Field with a Date Time Converter

Before you can enable the popup, you need a text field on the page that can be bound to a date field in the page bean. To bind a text field to a date, a Date Time converter is needed. This is done as follows:

  1. Create a java.util.Date field in the page bean first (find the page bean, open it to find the Bean Patterns view, then right-click and add a new property). I called the property startDate in my example project.
  2. Go to the page view.
  3. I recommend creating a group panel to hold the text area and popup link; this lets you keep the text area and popup together and move them around—see my demo project for an example. Call the group panel something like dateGroup.
  4. Next, drop a new Text Field into the new group. It doesn't matter what it is called.
  5. Select the new Text Field, and in the properties choose new DateTimeConverter for the converter field.
  6. Now, in the Application outline panel (bottom left), find the new DateTimeConverter1 (or whatever it is called) and select it.
  7. In the properties pane (top right), you need to enter a pattern for the date display/parsing that the popup and date time converter can agree on (this is crucial; the popup will put the date into the text field using this format, so the converter has to use the same standard form to correctly interpret the date). I used MM/dd/yyyy in my demo (month/day/4-digit year).
  8. You also need an HTML link to attach the popup to, so drag and drop a Hyperlink into the date group next to the text area.
  9. Set the text in the new hyperlink to be Select.
  10. In the application outline, find and select the new hyperlink (probably called hyperlink1; it has an icon of a chain link) and change the name to anchor1. This will form the anchor position for the popup.

Use Source View to Include the JavaScript

That's about as far as you can take the popup with the WYSIWYG view of the page. You now have to use the source view to proceed:

  1. Switch to the source view of the page (JSP source tab at the bottom of the edit area).
  2. Inside the head section of the page, just after the line that says
  3. <link href="resources/stylesheet.css" rel="stylesheet"
          type="text/css"/>
    
  4. Add the lines:
  5. <link href="resources/stylesheet.css" rel="stylesheet"
          type="text/css"/>
    <script language="javascript" src="javascript/CalendarPopup.js">
       var fake=null;
    </script>
    <script language="javascript">
       document.write(getCalendarStyles());
    </script>
    
  6. Some notes on this:
    1. Gotcha: The var fake=null line inside the first JavaScript include is to work around an apparent bug in Creator where a simple <script language="javascript" src="javascript/CalendarPopup.js"/> does not get parsed properly when the page is converted to HTML, and ends up with broken JavaScript on the page. This simple workaround makes it work just fine.
    2. The second line is a call to insert some default style definitions into the page to make the popup calendar look nice. It is a call to a method already defined in the included JavaScript, and is written in-line into the document.
  7. Next, inside the form definition of the page, you need to create a JavaScript method that will pop up the calendar. Add the following code just after the line that reads <h:form binding="#{DateDemo.form1}" id="form1">:
  8. <script language="javascript">
       function popupCalendar() {
          var myform      = document.forms[0];
          var myDateField = myform['form1:date1'];
          var cal1        = new CalendarPopup('testdiv1');
          cal1.showNavigationDropdowns();
          cal1.select(myDateField,'form1:anchor1','MM/dd/yyyy');
        }
    </script>
    

    Notes on this code:

    1. You have to look up the DOM element for the text area to attach the popup to it logically. Gotcha: Creator gives each DOM element the name of the control prepended by the name of the form the control is in and with a colon delimiter. Hence, the field date1 is actually called form1:date1 and must be looked up by using the array notation in JavaScript (the colon means it cannot be looked up with simple dot notation).
    2. The 'testdiv1' referenced in the CalendarPopup call is a DHTML DIV that we have yet to define. It is the actual popup DIV that will be revealed when the link is clicked.
    3. The form1:anchor attaches the popup to the anchor1 hyperlink on the page to give it the right position on the page.
    4. Finally, note the 'MM/dd/yyyy' format in the select call. This should match the DateTimeConverter format defined for the text area that the popup is attached to.
  9. Next, edit the hyperlink definition to call the JavaScript method when the link is clicked: <h:outputLink binding="#{DateDemo.anchor1}" id="anchor1" onclick="popupCalendar(); return false;" value="#">.
  10. The final step is to create the DIV that will be used for the popup, put this just before the closing body tag at the end of the document.

There is a lot to digest here. If you are confused about any of this, look at the demo project and satisfy yourself how everything goes together by looking at the page source there.

Add Other Components

As a finishing touch, I added a submit button and a text output field with another date time converter on it that was bound to the same date field. That way, after a date is selected, and the submit button clicked, the selected date will be output on the screen, confirming that the whole thing works.

Run the Demo

Okay; you have covered the basic steps to use the JavaScript calendar popup on the page. Run the demo project to see it in action. I think you will agree that the effect is very slick. To make life easier on yourself, you can use code clips to store the various pieces of code and make it quicker and easier to make new pages with these popups on. Don't forget, though, that the DOM element names must be correct in the JavaScript, so if you use different names on other pages for the controls, remember to update the JavaScript.

JSTL Tree

In the second JavaScript demo, I am going to combine some of the JSTL approach from my previous article with a very simple JavaScript tree implementation to make a tree "bound" to data from a map of lists within the page bean.

The steps involved are:

  1. Download and include the necessary files for the JavaScript tree into the demo project.
  2. Add JSTL support to the page, and use JSTL to populate the lists that will make up the tree (this is all done in the source view of the page).

Download and Include JavaScript Tree Files

The JavaScript tree available from Matt Kruse's DHTML Tree page is a study in what JavaScript and DHTML should be—as invisible and easy to use as possible.

In a nutshell, after including the necessary files in the project, it is only necessary to include the CSS and JavaScript files, and then create nested UL HTML lists with the top one having a particular mktree class; otherwise, the trees use completely standard HTML, very nice.

To prepare a project to use the tree:

  1. Download all the files for the above link.
  2. Place the mktree.js file into the javascript folder in the project.
  3. Place the mktree.css file into the Resources folder in the project.
  4. Place the three GIF files directly under the Web Pages folder in the project.

That's all you need to do to make the tree available to the app.

Add JSTL Support to the Page

Add the xmlns:c="http://java.sun.com/jstl/core" into the jsp:root tag. This imports the JSTL core tag library into the "c" namespace for the page. Refer to my previous article on JSTL for more details, and how to set up deployment of a JSTL project.

Populate the Tree Using JSTL

To populate the tree, you need to make nested UL and LI constructs in the page. For example:

<ul id="tree1" class="mktree">
   <li>Header 1
      <ul>
         <li>Sub 1</li>
         <li>Sub 2</li>
         <li>Sub 3</li>
      </ul>
   </li>
   <li>Header 2
      <ul>
         <li>Sub 4</li>
         <li>Sub 5</li>
      </ul>
   </li>
</ul>

Using JSTL to do this means looping over some arbitrary structure from the page bean. In this case, I am using a Hashmap with the values being Lists; this results in a tree of only two levels, headers and sub lists. There is no reason this same principle could not be applied to arbitrarily deep tree data.

The JSTL code to loop over the data and create the tree is:

<ul class="mktree" id="tree1">
   <c:forEach items="${TreeDemo.tree}" var="treeEntry">
      <c:set var="sublinks" value="${treeEntry.value}"/>
      <li><c:out value="${treeEntry.key}"/>
        <ul>
          <c:forEach items="${sublinks}" var="sublink">
            <li><c:out value="${sublink}"/></li>
          </c:forEach>
        </ul>
      </li>
   </c:forEach>
</ul>

You will notice that the top-level UL tag is using the class="mktree". This is the piece of magic that turns this otherwise ordinary set of nested lists into a collapsible tree.

Much more information about this tree component can be found on the DHTML tree documentation page. I recommend reading this page if you want the tree to do more.

Conclusion

This article demonstrates an approach to including and using JavaScript components within Creator. Although not as easy as dragging and dropping JSF components onto a page, it does open up the possibility of using a large number of existing JavaScript components that are available now. The examples here are just the beginning. By using the approach outlined in this article, you should be able to harness any JavaScript libraries and components you want to use under Creator. In future articles, I may investigate constructing custom JSF controls that harness some of these third-party JavaScript libraries.

Bibliography

About the Author

Dick Wall is a Lead Software Engineer for NewEnergy Associates, A Siemens Company based in Atlanta, GA that provides energy IT and consulting solutions for decision support and energy operations. He can be reached for comment on this and other matters at dick.wall@newenergyassoc.com, or check out his blog at http://www.voiceoftheresistance.com.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date