NetBeans offers a real cool feature called Code Templates. This feature is available throughout the whole IDE. In my series, I explain it within the context of Java EE, but you might use it anywhere.

A code template is a code fragment enriched with special tags, which can be inserted into your code by typing an abbreviation followed by a special key to expand it. By default this is the Tab key. You might have used code templates to speed up your editing. For example, if you type “St” (without quotation marks) followed by the Tab key, NetBeans will expand this to “String”. Or “sout” will be expanded to “System.out.println(“”);”. And the cursor is placed between the quotation marks.

The real cool stuff is to define your own templates to avoid annoying tasks. In the context of Java EE you might develop your frontend using JSF. Let’s assume, we need a table to display some data. NetBeans supports us by its code completion. As we type “<h:data” the code completion offers “<h:dataTable” and as we go on and close the tag by “>”, Netbeans offers the closing tag “</h:dataTable>”. But we still have to define our data, columns, and more. Let’s automate this task by creating a code template.

  • Open Tools, Options
    NetBeans opens the options dialog
  • Choose Editor, Code Templates
    NetBeans displays the appropriate editor

CodeTemplates

  • As Language select “XHTML”
  • Click onto New
    NetBeans queries an abbreviation
  • Type in “dt” (without quotation marks) and click onto OK
    NetBeans adds the abbreviation to the list and displays an empty editor.
  • Now enter the following text:
   <h:dataTable value="#{${myBean.list}}" var="${myVar}"
                         rowClasses="row1, row2">

   <h:column id="colTitle">
       <f:facet name="header">
           <h:outputLabel value="${cursor}"/>
       </f:facet>
       <h:inputText value="#{${myVar}.${property}}"
   </h:column>

</h:dataTable>
  • Click onto OK and close the options dialog
  • Within your JSF page (xhtml file), type “dt” followed by Tab and watch the result

NetBeans will insert the template into your source. More than this, the cursor is placed onto myBean.list. You can replace this by the bean and the property you want to refer to. After pressing Enter, NetBeans places the cursor onto myVar. As you key in a variable name, NetBeans automatically renames myVar for the inputText too.

${…} is treated as a variable name. Every first occurrence is treated as a stop position, where you can enter a feasible name. Other recurrences are renamed as you enter a new name. The reserved parameter name ${cursor} is the last stop position: Here the cursor is placed after you entered all other parameters.

Enjoy!