FeaturesPluginsDocs & SupportCommunityPartners

NetBeans Code Snippet Module Tutorial

This tutorial demonstrates how to add code snippets to the HTML/JSP Component Palette. Code snippets are small pieces of code that can be dragged from a component palette and dropped in the Source Editor. They serve to speed up coding. The HTML/JSP Component Palette has several code snippets already, but you might want to add some additional ones and share them with others. When you use the IDE to create a NetBeans module that contains your code snippets, the IDE provides facilities for creating a binary NetBeans Module (NBM) file, distributing it, and having its recipients install it via the Update Center.


The tutorial you are now reading was written for NetBeans IDE 5.5. If you are using NetBeans IDE 6.0, please use the 6.0 version of this tutorial instead.


To create a code snippet, you use the NetBeans Palette API. A code snippet requires the following files:

  • A Java class that defines the piece of code to be dragged into the Source Editor.
  • A Java class that defines how the piece of code should be inserted. For example, indentation and formatting are defined here.
  • A properties file that defines the labels and tooltips.
  • A 16x16 pixel image for the 'Small Icon' display.
  • A 32x32 pixel image for the 'Big Icon' display.

After you have created or added the above files to the NetBeans module, you declare them in a resource declaration XML file, which you register in the NetBeans System Filesystem by using the layer.xml file.

The following topics are covered below:

Once the software is installed, this tutorial can be completed in 20 minutes.

For more information on working with modules, see the NetBeans Development Project home on the NetBeans website. If you have questions, visit the NetBeans Developer FAQ or use the feedback link at the top of this page.


Installing the Software

Before you begin, you need to install the following software on your computer:


Installing the Sample

Take the following steps to install the sample:

  1. Unzip the attached file.

  2. In the IDE, choose File > Open Project and browse to the folder that contains the unzipped file. Open the module project. It should look as follows:

    All source files.

  3. Right-click the project node and choose Install/Reload in Target Platform. The target platform opens and the module is installed.

  4. Verify that the module is correctly installed:

    • Right-click the newhtmlsnippets project node, choose New > File/Folder, and select HTML File in the Other category. Click Next and then click Finish. The HTML file opens, displaying the Component Palette with one additional code snippet, with a tooltip that displays the result of dragging-and-dropping the item:

      new snippet in component palette

    • Drag the 'New Line' item into the Source Editor and notice that a new <br> tag is inserted at the cursor.

    • Right-click in the Component Palette and choose Show Big Icons. Notice that all the icons increase in size.

Now that you know what the end result looks like, you will create the module from scratch and learn about each part while creating it.


Setting up the Module Project

Before you start writing the module, you have to make sure you that your project is set up correctly. NetBeans IDE 5.x provides a wizard that sets up all the basic files needed for a module.

Creating the Module Project

  1. Choose File > New Project (Ctrl-Shift-N). Under Categories, select NetBeans Plug-in Modules. Under projects, select Module Project and click Next.
  2. In the Name and Location panel, type newhtmlsnippets in Project Name. Change the Project Location to any directory on your computer, such as c:\mymodules. Leave the Standalone Module radiobutton and the Set as Main Project checkbox selected. Click Next.

  3. In the Basic Module Configuration panel, replace yourorghere in Code Name Base with org.netbeans.modules, so that the whole code name base is org.netbeans.modules.newhtmlsnippets. Leave the location of the localizing bundle and XML layer, so that they will be stored in a package with the name org/netbeans/modules/newhtmlsnippets. Click Finish.

The IDE creates the newhtmlsnippets project. The project contains all of your sources and project metadata, such as the project's Ant build script. The project opens in the IDE. You can view its logical structure in the Projects window (Ctrl-1) and its file structure in the Files window (Ctrl-2). For example, the Projects window should now look as follows:

Initial Projects window.

For basic information on each of the files above, see the Introduction to NetBeans Module Development.

Specifying the Module's Dependencies

You will need to subclass three classes that belong to NetBeans APIs. Each has to be declared as a Module dependency. Use the Project Properties dialog box for this purpose.

  1. In the Projects window, right-click the newhtmlsnippets project node and choose Properties. In the Project Properties dialog box, click Libraries.
  2. For each of the following APIs, click "Add...", select the name from the Module list, and then click OK to confirm it:

    Project Properties dialog box.

  3. Click OK to exit the Project Properties dialog box.

  4. In the Projects window, expand the Important Files node, double-click the Project Metadata node, and note that the APIs you selected have been declared as Module dependencies:
  5. <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://www.netbeans.org/ns/project/1">
        <type>org.netbeans.modules.apisupport.project</type>
        <configuration>
            <data xmlns="http://www.netbeans.org/ns/nb-module-project/2">
                <code-name-base>org.netbeans.modules.newhtmlsnippets</code-name-base>
                <standalone/>
                <module-dependencies>
                    <dependency>
                        <code-name-base>org.netbeans.modules.editor.lib</code-name-base>
                        <build-prerequisite/>
                        <compile-dependency/>
                        <run-dependency>
                            <release-version>1</release-version>
                            <specification-version>1.9.0.1</specification-version>
                        </run-dependency>
                    </dependency>
                    <dependency>
                        <code-name-base>org.netbeans.spi.palette</code-name-base>
                        <build-prerequisite/>
                        <compile-dependency/>
                        <run-dependency>
                            <release-version>0</release-version>
                            <specification-version>1.5</specification-version>
                        </run-dependency>
                    </dependency>
                    <dependency>
                        <code-name-base>org.openide.text</code-name-base>
                        <build-prerequisite/>
                        <compile-dependency/>
                        <run-dependency>
                            <specification-version>6.9</specification-version>
                        </run-dependency>
                    </dependency>
                </module-dependencies>
                <public-packages/>
            </data>
        </configuration>
    </project>

Coding the Module


Creating the Code Snippet

  1. Right-click the org.netbeans.modules.newhtmlsnippets node and choose New > Java Class. Type BR in Class Name, make sure that the org.netbeans.modules.newhtmlsnippets package is selected in the Package drop-down list, and click Finish.
  2. Replace the default content of the BR.java file with the following:

    package org.netbeans.modules.newhtmlsnippets;
    
    import javax.swing.text.BadLocationException;
    import javax.swing.text.JTextComponent;
    import org.netbeans.modules.newhtmlsnippets.HTMLPaletteUtilities;
    import org.openide.text.ActiveEditorDrop;
    
    public class BR implements  ActiveEditorDrop {
        
        public BR() {
        }
        
        private String createBody() {
            String Br = "<br>";
            return Br;
        }
        
        public boolean handleTransfer(JTextComponent targetComponent) {
            String body = createBody();
            try {
                HTMLPaletteUtilities.insert(body, targetComponent);
            } catch (BadLocationException ble) {
                return false;
            }
            return true;
        }
        
    }

    Right-click in the Source Editor and choose Reformat Code (Ctrl-Shift-F).

Defining the Insertion and Formatting

  1. Right-click the org.netbeans.modules.newhtmlsnippets node and choose New > Java Class. Type HTMLPaletteUtilities in Class Name, make sure that the org.netbeans.modules.newhtmlsnippets package is selected in the Package drop-down list, and click Finish.
  2. Replace the default content of the HTMLPaletteUtilities.java file with the following:

    package org.netbeans.modules.newhtmlsnippets;
    
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Caret;
    import javax.swing.text.Document;
    import javax.swing.text.JTextComponent;
    import org.netbeans.editor.BaseDocument;
    import org.netbeans.editor.Formatter;
    
    public class HTMLPaletteUtilities {
        public static void insert(String s, JTextComponent target)
        throws BadLocationException {
            insert(s, target, true);
        }
        
        public static void insert(String s, JTextComponent target, boolean reformat)
        throws BadLocationException {
            
            if (s == null)
                s = "";
            
            Document doc = target.getDocument();
            if (doc == null)
                return;
            
            if (doc instanceof BaseDocument)
                ((BaseDocument)doc).atomicLock();
            
            int start = insert(s, target, doc);
            
            if (reformat && start >= 0 && doc instanceof BaseDocument) {  // format the inserted text
                int end = start + s.length();
                Formatter f = ((BaseDocument)doc).getFormatter();
                f.reformat((BaseDocument)doc, start, end);
            }
            
            if (doc instanceof BaseDocument)
                ((BaseDocument)doc).atomicUnlock();
            
        }
        
        private static int insert(String s, JTextComponent target, Document doc)
        throws BadLocationException {
            
            int start = -1;
            try {
                //at first, find selected text range
                Caret caret = target.getCaret();
                int p0 = Math.min(caret.getDot(), caret.getMark());
                int p1 = Math.max(caret.getDot(), caret.getMark());
                doc.remove(p0, p1 - p0);
                
                //replace selected text by the inserted one
                start = caret.getDot();
                doc.insertString(start, s, null);
            } catch (BadLocationException ble) {}
            
            return start;
        }
    }

    Right-click in the Source Editor and choose Reformat Code (Ctrl-Shift-F).


Registering the Module


Declaring the Resources

  1. Right-click the org.netbeans.modules.newhtmlsnippets node and choose New > File/Folder. Select XML Document in the XML folder and click Next. Type BR in File Name. Type \resources at the end of src\org\netbeans\modules\newhtmlsnippets in Folder. Click Finish.
  2. Replace the default content of the BR.xml file with the following:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE editor_palette_item PUBLIC "-//NetBeans//Editor Palette Item 1.0//EN"
      "http://www.netbeans.org/dtds/editor-palette-item-1_0.dtd">
    
    <editor_palette_item version="1.0">
        <class name="org.netbeans.modules.newhtmlsnippets.BR" />
    
        <icon16 urlvalue="org/netbeans/modules/newhtmlsnippets/resources/BR16.png" />
        <icon32 urlvalue="org/netbeans/modules/newhtmlsnippets/resources/BR32.png" />
        <description localizing-bundle="org.netbeans.modules.newhtmlsnippets.Bundle"
                   display-name-key="NAME_html-BR"
                   tooltip-key="HINT_html-BR" />
    </editor_palette_item>

    Right-click in the Source Editor and choose Reformat Code (Ctrl-Shift-F).

  3. Add a 16x16 pixel icon and a 32x32 pixel icon to the new resources folder. Name them BR16.png and BR32.png. They can also be in other icon formats, such as GIF or JPG. Make sure that the resource is correctly declared in the BR.xml file.

  4. Add the following to the Bundle.properties file:

    new bundle keys

    Make sure that the label and hint are correctly declared in the BR.xml file.

Registering the Resources

  1. Add the following tags to the layer.xml file, between the <filesystem> tags:

    <folder name="HTMLPalette">
       <folder name="HTML">
          <file name="BR.xml" url="resources/BR.xml"/>
       </folder>
    </folder>

  2. Expand the Important Files node, expand the XML Layer node, and wait for the subnodes to be displayed.

  3. Expand <this layer in context>. A folder appears for every folder declared by every layer.xml file of every module registered in the IDE. Notice that the HTMLPalette folder is marked in bold. This is where you added a folder in your own layer.xml file. Expand the folder and notice that its subfolder, HTML, is also in bold. Expand the HTML folder and notice that the BR.xml resource declaration file that you declared has been added to the resource declaration files provided by other modules. When you right-click on the node, several options are available:

    layer in context

  4. Drag the BR.xml node and drop it right below the TABLE.xml node. Double-click the Layer XML node in the Important Files node, and notice that two new tags have been added, one before and one after the <file name="BR.xml" url="resources/BR.xml"/> line:

    layer in context

    When you dragged and dropped the BR.xml node in the <this layer in context> node, the IDE created <attr> tags for positioning the new component snippet between the existing component snippets.


Building and Installing the Module

The IDE uses an Ant build script to build and install your module. The build script is created for you when you create the module project.

Installing the Module

  • In the Projects window, right-click the newhtmlsnippets project and choose Install/Reload in Target Platform.

    The module is built and installed in the target platform. The target platform opens so that you can try out your new module. The default target platform is the installation used by the current instance of the development IDE.

Using the Module

Verify that the module is correctly installed:

  1. Right-click the newhtmlsnippets project node, choose New > File/Folder, and select HTML File in the Other category. Click Next and then click Finish. The HTML file opens, displaying the Component Palette with one additional code snippet, with a tooltip that displays the result of dragging-and-dropping the item:

    new snippet in component palette

  2. Drag the 'New Line' item into the Source Editor and notice that a new <br> tag is inserted at the cursor.

  3. Right-click in the Component Palette and choose Show Big Icons. Notice that all the icons increase in size.

Creating a Shareable Module Binary

  1. In the Projects window, right-click the newhtmlsnippet project and choose Create NBM.

    The NBM file is created and you can view it in the Files window (Ctrl-2):

    Shareable NBM.

  2. Make the module available to others via, for example, e-mail.

  3. The recipient can install the module by using the Update Center. Choose Tools > Update Center from the main menu.



Next Steps

For more information about creating and developing NetBeans modules, see the following resources:


Versioning

Version
Date
Changes
Open Issues
1 28 November 2005 Initial version
  • Is it the same for Swing/AWT Components?
  • How could formatting/indentation be different?
  • Need to add explanation for adding own dialog box for predefining values.
  • Need new screenshot of the Component Palette, to show the new snippet under the existing Table snippet.
  • Explanatory text for the use of the NetBeans APIs to be added.
  • Show how to share snippets between palettes via shadow files.
2 2 December 2005
3 8 December 2005


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   Virtual Box - full virtualizer  Open ESB - The Open Enterprise Service Bus Powered by