Download NetBeans!

20080423 Wednesday April 23, 2008

Hello Code Generator

I click Alt-Insert and I see this:

Here's the code:

import com.sun.source.util.TreePath;
import java.io.IOException;
import java.util.Collections;
import javax.swing.JOptionPane;
import javax.swing.text.JTextComponent;
import org.netbeans.api.java.source.CompilationController;
import org.netbeans.modules.java.editor.codegen.CodeGenerator;

public class HelloGenerator implements CodeGenerator {

    public static class Factory implements CodeGenerator.Factory {

        public Factory() {
        }

        @Override
        public Iterable<? extends CodeGenerator> create
                (CompilationController controller, TreePath path) throws IOException {
            return Collections.singleton(new HelloGenerator());
        }
    }

    @Override
    public String getDisplayName() {
        return "Hello World";
    }

    @Override
    public void invoke(JTextComponent arg0) {
        JOptionPane.showMessageDialog(null, "Hello World!");
    }

}

Doesn't do anything yet, but gives you a starting point. Register it like this:

<filesystem>
    <folder name="Editors">
        <folder name="text">
            <folder name="x-java">
                <folder name="codegenerators">
                    <file name="org-netbeans-modules-my-codegen-HelloGenerator$Factory.instance">
                        <attr name="position" intvalue="10"/>
                    </file>
                </folder>
            </folder>
        </folder>
    </folder>
</filesystem>

Dependencies: Javac API Wrapper, Java Editor (implementation dependency, because the above is not a public API yet), and Java Source.

Apr 23 2008, 12:46:38 AM PDT Permalink

Trackback URL: http://blogs.sun.com/geertjan/entry/hello_code_generator
Comments:

Geertjan - Where can we find the CodeGenerator class? I added the library dependencies as you mentioned, but the CodeGenerator class with the above mentioned package can't seem to be found. Am I missing something simple?

Posted by Adam Myatt on April 23, 2008 at 10:41 AM PDT #

Adam, please read the last sentence again. In other words, you need to set an implementation dependency on "Java Editor". The CodeGenerator class is not public yet. So, in the Libraries panel, right-click the "Java Editor" entry and then set "Implementation Version". Then the CodeGenerator class will be exposed. Hope to see you at JavaOne (are you doing a book signing, if so when)?

Posted by Geertjan on April 23, 2008 at 11:17 AM PDT #

Ah ha! Guess I read over that too quickly. Thanks! works now.

Posted by Adam Myatt on April 23, 2008 at 03:03 PM PDT #

Post a Comment:

Name:
E-Mail:
URL:

Your Comment:

HTML Syntax: NOT allowed