DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Tools Topics

article thumbnail
IntelliJ Keymap for NetBeans IDE
Have been using IntelliJ for about 5 years now. It is still the Roll Royce of all IDEs, and of that there is no doubt. But having said that, you should once in a while jump the ship, and try out something different and it is with this intention that I am currently trying out NetBeans IDE 6.1. I was a NetBeans IDE user starting from its “Forte for Java” days to about 2003, and did also develop some plugins on it. So it feels great to be back home. Well not quite. Though NetBeans IDE has now added almost every trick in the bag, it is still challenging even for a veteran, to pick up from where they left off. To ease this pain of transition, here is the link to an IntelliJ Key Map, which when applied to NetBeans IDE, will make it feel more like IntelliJ to you. If you find yourself pressing CTRL+ALT+L, CTRL+ALT+O and CTRL+F12, this keymap will be a real time saver. From: IntelliJ Keymap for NetBeans
July 14, 2008
by Swapnonil Mukherjee
· 10,932 Views
article thumbnail
Python Development in NetBeans IDE
The nbPython project aims to provide support for Python development to NetBeans IDE. Below follow the step-by-step instructions for getting started! The bits are available (milestone releases) for download now as NetBeans modules (nbms). Let us get started: Download/lnstall the M3 NBMs from here. Fire up NetBeans IDE. Go to Tools -> Plugins -> Downloaded Tab. Click on "Add Plugins" and select all the NBM files in the unzipped directory. Now, you will see all the chosen modules along with their descriptions. You should see something like this: Press the "Install" button. Using NetBeans IDE 6.1, I get a dependency error: Then, I downloaded a latest build NetBeans IDE Build 200806220002 from here and repeated the above steps. This time there was no dependency problem. You will get a "Validation Warning". Press "Continue": The installation will continue and will be over without any further user interaction required. Creating a New Python Project Go to File-> New Project-> Python-> Python Project. Choose a Project Name- say "HelloNbPython". Click on Finish. A new project gets created and is visible in the Project Explorer window. No default file is created. Right Click on the project name, and select New-> Empty Python File. Enter a name, say- HelloWorld. A Python script will be generated for you which will simply print "Hello World". The project tree is now as follows: HelloNbPython/ pyproject/ project.properties src/ HelloWorld.py Runing a Python Script Right Click on HelloWorld.py in the project explorer and click "Run Python Script". First time I did this, I got the following exception message: java.io.IOException: Cannot run program "/home/amit/netbeans-dev-200806220002/nbpython/jython-2.5/bin/jython" (in directory "/home/amit/NetBeansProjects/HelloNbPython"): java.io.IOException: error=13, Permission denied So I checked the file permission of the 'jython' executable: $ ls -l jython -rw-r--r-- 1 amit amit 5101 2008-06-22 15:05 jython As you can see there is no executable permission for 'jython' as indicated by the absence of the 'x' flag So, I made the 'jython' executable by: chmod +x jython Run the script again and you should get "Hello World" in the output window.
June 22, 2008
by Amit Saha
· 33,213 Views
article thumbnail
Easy Unwrapping with IntelliJ IDEA
In complicated code constructs that contain numerous nested statements, you sometimes need to accurately get rid of the enclosing parts. When you try to manually delete such statements, it is too easy to break the syntax of the whole construct. With the new IntelliJ IDEA’s unwrapping feature, this task becomes just a snap. Consider the following example, where a string variable is being analyzed: [img_assist|nid=3370|title=|desc=|link=none|align=left|width=640|height=299] Let’s remove one of the branches. To do that, place the cursor at the branch containing the statement, and press Ctrl+ Shift+Delete. IntelliJ IDEA shows you which results you can obtain: the part that will remain is displayed on the blue background, while the grey background denotes the pieces of code to be deleted: [img_assist|nid=3371|title=|desc=|link=none|align=left|width=640|height=258] After clicking the Remove ‘else…’ option, we get the promised results: [img_assist|nid=3372|title=|desc=|link=none|align=left|width=640|height=226] As you see, all parentheses are properly balanced, and the syntax is correct. However, Java developers are not the only ones who can enjoy this powerful feature. The same “stripping” can be done in XML or HTML code. Consider a situation when you have to clean up some HTML code and get rid of inline styles, for example, remove bold fonts. What will you do in this case – delete an opening tag, then delete the closing tag, with the real possibility to lose something in process. With IntelliJ IDEA, all you have to do is to place the caret somewhere inside the tags, and press Ctrl+Shift+Delete. The unnecessary tags are removed silently. This facility is even more helpful for XML constructs, which can have deep nesting. You can sequentially remove enclosing tags level by level, until getting to the innermost one you want to preserve. Do I need to mention that such unwrapping can be undone? Enjoy!
June 7, 2008
by Irina Megorskaya
· 10,369 Views · 1 Like
article thumbnail
Obfuscating a NetBeans Java Application Project
Some time ago I found a couple of posts talking about how to obfuscate a NetBeans RCP module (here and here). Getting some parts of the ant targets presented in the previous post, this one presents a simple target that allows to obfuscate a normal Java library. For this, you need to have installed the obfuscator ProGuard. Take into account I am talking about obfuscating a Java library. This implies the obfuscation is lighter than if you obfuscate a closed application, that is, all public methods and interfaces must maintain its name (if not you can call your library methods anymore). Open your build.xml Java application file and paste this target: Special attention to these couple of lines:
April 30, 2008
by Antonio Santiago
· 46,010 Views · 1 Like
article thumbnail
Quick Start: Creating Language Tools In NetBeans IDE
NetBeans IDE is one of the main free Java editors in the market. In fact, it can be used to program in many other computer languages, like C/C++, Ajax, Javascript. NetBeans IDE can be extended by adding modules that add new features. So... you can have a programming editor customized to your needs. This tutorial can be of interest for all those who want to create a module that adds support for a new language inside NetBeans IDE. Original article: http://hiperia3d.blogspot.com/2008/04/netbeans-tutorial.html (the original article has coloring that makes reading easier. If you have some dificulty reading it here, you can go there). The process of creating the first of the modules that compose my X3DV Module Suite was similar to the one described here. We will learn how to make a module that has these features: Syntax highlighting that is specific for the language we will define. Brace completion and auto-indentation. Icons for the new files of that language. To be able to create new files written in our new language. Template for the new files written in that language. Just download the last version of NetBeans IDE (download NetBeans IDE 6.1 Beta). Then, follow all the steps described here. This tutorial is valid for the 6.1 version of NetBeans IDE, which has many improvements that make module building easier. This tutorial takes a fictional language called Foo Language as a sample. I suggest to follow the tutorial as it is, and later, adapt it to your needs. This is not a highly technical tutorial, but a quickstart guide that can be very easy for newcomers. First Steps With Your Module Create a new NetBeans project: Choose NetBeans Modules in Categories and Module in Projects: Fill in your project Name, locate the directory where its project folder will be placed, and mark it as a Standalone Module. Fill the info for your module. You just have to fill the two first text boxes: change the Code Name Base to what is appropriate for your module and choose a Display Name. The project will be created. Now we will add the basic: support files for the new file type. New File Type Support Over the project name, right click and select New/File Type: In the dialog that appears, you must enter some data so the NetbBeans IDE recognizes the new file type. In MIME Type you must enter text/x- usually followed by the main extension of the file type. Why does it say text/x-? As you may note, what you enter is not the true MIME type. For the IDE, all the extensions we create are text files. In Extension(s) you must enter them separated with spaces. In our example, there's only one extensions for Foo Files: .foo In Class Name Prefix, you enter the name of the file type, so all classes generated by the IDE for this module will start with it. In Icon, you must locate in your hard drive a gif icon of 16x16 pixels. In our example, it's this: Although in some tutorials they say that jpg and png images can also be used, I found that sometimes they're not displayed. So I recommend using gif images, as they are less error-prone. The IDE will copy your icon to the project directory. At this point, a bunch of files will be created by NetBeans IDE and opened in the code editor. Close them all, you don't need to edit them. Now our module is ready to recognize and create the new file types. But we want the new files to have a default content. So we will edit the generated template. Locate the file named: Edit it and write the content that you want to be the default when you create a new file. Locate the XML Layer in the module. The XML Layer file is the soul of our module. It controls most of the things that a module can do. Locate these lines: The next step is to create a description of the new supported file type that will be displayed when you want to create it, in the New File Wizard. This description will be stored in a file called "Description.html" (strange... uh?). Add this line after the one highlighted in blue, modifying it to your project url: This line we added describes where the Description of the new file is. Right click over your project and select New/Other. Select Other/HTML file. Name the file "Description", and leave the rest as it is. Replace all the contents of the generated file with this: Creates a foo file that is useful for nothing at all. This is what we will see as a result of these steps once the module is finished and we want to create a Foo file. Create the Language Support Now that we have the new files recognized, we will add syntax coloring and other features to our language module. To be able to support language features, we must do the following: right click over your project and choose "Properties". The properties of your module will be displayed. Click over libraries (on the left) and then the "Add..." button. In the list, search for the entry called "Generic Languages Framework", and add it. Now, right click over your project and select New/Other. In Categories, select "Module Development", and on the right, select "Language Support". Then enter the MIME Type and Extensions as we did in the first section of our tutorial. You will see that the XML Layer has changed and now has more things added. Between them, there's a new file that describes our language. That file is called "language.nbs". As the XML Layer has been modified, the icon of our files may have disappeared, so we need to add something to the XML Layer file to recover it. Close all the opened files. Locate the file called XML Layer, and open it. Locate the line highlighted in blue in this image, that says And replace that entire line with: Editing The Language File The default language.nbs file is filled with contents that may be a good start point for a scripting language. For declarative languages like VRML or X3D, or markup languages like HTML or similar, these contents are not useful. In our example of the Foo Language, we will use a very simple language definition. This way you will understand the basics of defining languages. So delete all the contents of the file language.nbs, and replace them with this: # To change this template, choose Tools | Templates # and open the template in the editor. # definition of tokens TOKEN:header:( "# foo language v1.0" ) TOKEN:line_comment: ( "#"[^ "\n" "\r"]* | "//"[^ "\n" "\r"]* ) TOKEN:keyword:( "foo_function" | "foo_command" ) TOKEN:field:( "foo_value" ) # all that follows is useful for mostly all languages TOKEN:identifier: ( ["a"-"z" "A"-"Z"] ["a"-"z" "A"-"Z" "0"-"9" "_"]* ) TOKEN:number: (["0"-"9"]*) TOKEN:operator: ( ":" | "*" | "?" | "+" | "-" | "[" | "]" | "<" | ">" | "^" | "|" | "{" | "}" | "(" | ")" | "," | "=" | ";" | "." | "$" ) TOKEN:string:( "\"" ( [^ "\"" "\\" "\r" "\n"] | ("\\" ["r" "n" "t" "\\" "\'" "\""]) | ("\\" "u" ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"]) )* "\"" ) TOKEN:string:( "\'" ( [^ "\'" "\\" "\r" "\n"] | ("\\" ["r" "n" "t" "\\" "\'" "\""]) | ("\\" "u" ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"] ["0"-"9" "a"-"f" "A"-"F"]) )* "\'" ) TOKEN:whitespace:( [" " "\t" "\n" "\r"]+ ) # colors COLOR:header:{ foreground_color:"orange"; background_color:"black"; font_type:"bold"; } COLOR:line_comment:{ foreground_color:"#969696"; } COLOR:keyword:{ foreground_color:"red"; font_type:"bold"; } COLOR:field:{ foreground_color:"#25A613"; font_type:"bold"; } # parser should ignore whitespaces SKIP:whitespace # brace completion COMPLETE "{:}" COMPLETE "(:)" COMPLETE "\":\"" COMPLETE "\':\'" # brace matching BRACE "{:}" BRACE "(:)" # indentation support INDENT "{:}" INDENT "(:)" Now, create a Foo file, using a plain text editor, and save it with the extension .foo These will be its contents: # foo language v1.0 # comment // another comment foo_function { foo_command ( foo_value 1 0 1 ); } Now let's see the language.nbs file and understand the basic parts. TOKEN:header:( "# foo language v1.0" ) TOKEN:keyword:( "foo_function" | "foo_command" ) The Tokens are the words that are part of your language, and you want them colored. They define types of words that have something in common in your language. You group them into a category, that is a token. The words are between double quotes, and separated by a | sign. COLOR:header:{ foreground_color:"orange"; background_color:"black"; font_type:"bold"; } COLOR:line_comment:{ foreground_color:"#969696"; } This defines the colors used for each token. You can specify more properties for colors, but these are the basic ones. All these properties are very easy to understand by their own names, as you see. The colors can be specified by their names (although it recognizes only a few) or by its number. # brace completion COMPLETE "{:}" What these lines do is that when you type a { sign, the editor automatically will type } after your caret, speeding your work and making it less error-prone. # brace matching BRACE "{:}" # indentation support INDENT "{:}" This sentences make that when you place the caret over a brace, the matching brace will be highlighted, and that lines after those signs will be indented. Final Note Now you know all that is needed to create the basic support for a new file type and language syntax highlighting. You can add anything you like to your module, that you think is important for you and that could make your work easier. There's much more than can be done with NetBeans IDE. I invite just to test it, join its huge community of users, and experience it by yourself. -Jordi R. Cardona- X3D/VRML Worldbuilder Java Programmer X3DV Module Suite Developer. Hiperia3D News © 2008 by Jordi R. Cardona. The images and text of this post were added by the author to dzone. The author has granted dzone.com with exclusivity to use these images and text for the only purpose to spread this article. If you want to promote this tutorial, you can link to the original one at: http://hiperia3d.blogspot.com/2008/04/netbeans-tutorial.html
April 14, 2008
by Jordi R Cardona
· 40,075 Views
article thumbnail
Ant Build File Changes for Java Web Projects in NetBeans IDE 6.1
While working with a Java Web Application in NetBeans, I noticed some slight changes in the Ant build file for my project between NetBeans 6.0 and 6.1. This article explores some of the problems these changes caused to help out anyone with similar issues. I started with a Java Web Application that was created in NetBeans 6.0.1. After adding some JSP files and several Java source files, I committed everything in the project to my CVS repository. For some of my projects, I utilize the Hudson continuous integration build server. Using a standard deployment of Hudson, I configured the project to poll the SCM every 60 minutes, check out the code from CVS (if changes had been committed), and trigger the NetBeans project’s Ant build file (calling several specific targets like compile, dist, and so on. My builds have been functioning correctly for several weeks using this standard setup. I recently opened one of those projects in NetBeans 6.1 Beta and have been thoroughly enjoying the new features (faster startup, better JSP parsing in the Source Editor). After adding some JAR files as libraries and making several configuration changes, I committed the entire project (particularly the build-related files in the nbproject directory). Suddenly, my build for that project started failing. The console output reported by Hudson was : -init-check: BUILD FAILED D:/projects/hudson-server/data/jobs/MyWebProjectl/workspace/nbproject/build-impl.xml:149: The Java EE server classpath is not correctly set up. Your active server type is Tomcat55. Either open the project in the IDE and assign the server or setup the server classpath manually. For example like this: ant -Duser.properties.file= (where you put the property “j2ee.platform.classpath” in a .properties file) or ant -Dj2ee.platform.classpath= (where no properties file is used) Total time: 2 seconds finished: FAILURE I undid the configuration changes one by one, but the build failed regardless of what I reset. Apparently the property j2ee.platform.classpath is now required. I did a DIFF on the nbproject/build-impl.xml file and discovered several changes. The -init-check target includes property checks including this new one : The Java EE server classpath is not correctly set up. Your active server type is ${j2ee.server.type}.Either open the project in the IDE and assign the server or setup the server classpath manually.For example like this: ant -Duser.properties.file= (where you put the property “j2ee.platform.classpath” in a .properties file) or ant -Dj2ee.platform.classpath= (where no properties file is used) I hadn’t really taken notice of this property in the build file before, but it is referenced in a number of other targets such as: -init-macrodef-javac, -init-macrodef-junit, -init-macrodef-java, -init-macrodef-nbjpda, -init-macrodef-debug, compile-jsps, -do-compile-single-jsp, connect-debugger, javadoc-build, -do-compile-test, -do-compile-test-single Not being able to find a definition of the property anywhere in the build file, I looked through the project’s project.properties file among the list of defined properties. The property j2ee.platform.classpath was not defined. Thus, I’m assuming this is passed into the build file dynamically by NetBeans? In general I wouldn’t care, but when running the build file via Ant inside Hudson, the property j2ee.platform.classpath is never passed in. Hudson DOES allow you to pass properties and values to the build file, so I suppose I can specify the value manually, but I would like to keep the number of per project customizations to a minimum to maintain a low level of maintenance. Unless this causes some problem with the project properties in the build system, I would suggest the following fix for anyone who is experiencing a similar issue. Open your project’s project.properties file. Navigate to the section that contains these properties: j2ee.platform=1.4 j2ee.server.type=Tomcat55 Add a new line that specifies a blank j2ee.platform.classpath property such as this: j2ee.platform=1.4 j2ee.platform.classpath= j2ee.server.type=Tomcat55 Now, if the project.properties file is committed to CVS, a Hudson build can be triggered, and the FAIL check in the build-impl.xml file will pass. I ran some quick tests with the project, and everything with the project inside NetBeans still seems to work fine. I would propose to the NetBeans team to have the j2ee.platform.classpath property automatically added to the project.properties file.
March 26, 2008
by Adam Myatt
· 15,663 Views
article thumbnail
Patching from Local History
Using patches is a popular way to share changes between the teammates or supply updates to software products to the customers. With IntelliJ IDEA, creating and applying versioned patches is quite simple and intuitive: you can do it from the main Version Control menu, or from the Changes tool window. However, IntelliJ IDEA suggests an additional way to create and apply your “personal” patches. As we have discussed earlier, numerous changes pass unnoticed by the version control systems, because you just do not check in every change you make to your files while working. You know that IntelliJ IDEA keeps your own “personal version control” – the local history. Besides the possibility to roll back to a certain revision, you can also create a patch on the base of a revision or action, share it with your colleagues, and apply it when necessary. Local history applies to the folders, files, members and fragments of text, but the technique of creating a patch is common in all cases. Let’s see how it’s done. Select a folder in the Project tool window, and choose Local History on its context menu. In the Local History view, right-click the desired revision, and choose Create Patch: [img_assist|nid=1204|title=|desc=|link=none|align=left|width=505|height=357] In the dialog box that opens, specify the name and location of the patch file: [img_assist|nid=1205|title=|desc=|link=none|align=left|width=415|height=136] An interesting possibility is suggested by the Reverse patch checkbox. If you check this option, IntelliJ IDEA will create a patch that rolls back the selected action. For example, it you have created a file, the patch will delete it. Applying your “personal” patch is done as usual, using the Apply Patch command on the main Version Control menu. If a patch file is stored in project, you can invoke this command on the context menu of the patch file in the Project tool window: [img_assist|nid=1206|title=|desc=|link=none|align=left|width=249|height=195]
February 21, 2008
by Irina Megorskaya
· 9,839 Views
article thumbnail
Binding a JTable to Swing Controls in NetBeans IDE
Here is an outline of a scenario that binds Swing controls to columns in a JTable, via the tools that NetBeans IDE provides.
February 20, 2008
by Geertjan Wielenga
· 183,946 Views
article thumbnail
How to Create Visual Applications in Java?
My excellent colleague Java evangelist Chuk Munn Lee wrote me an e-mail in response to my description yesterday of how to create JConsole plugins: "I did not know that the visual library can be used outside of NetBeans. Do you need a special build of the library? Do I need to build it myself or is there a standalone version that I can download?" This is a good question and the answer is illustrative of how interwoven NetBeans IDE is with the NetBeans Platform. Look in your NetBeans installation folder and you'll find a folder called "platform7", with this content: In other words, literally, the content of the folder above is the NetBeans Platform. Many of the JARs that make up the NetBeans Platform can be used outside a NetBeans Platform application. Last October I wrote about this, in a blog entry entitled NetBeans APIs Outside of the NetBeans Platform. Follow the steps in that tutorial and you'll have a standard Java application that makes use of some of the typical JARs from the NetBeans Platform. In other words, several typical scenarios developed on the NetBeans Platform can also be developed outside of it. Another similar scenario is illustrated in the article I wrote yesterday, How to Get Started with JConsole Plugins, where the Visual Library API is used to inject some graph functionality into the JConsole. And so, in response to Chuk's questions "Do you need a special build of the library? Do I need to build it myself or is there a standalone version that I can download?", the answer is: "No, you don't." Download NetBeans IDE, take the two JARs that are highlighted in the screenshot above, put them on your app's classpath, and you're ready to create visual Java applications: Let's get started for real now. To create visual applications, you need some kind of Swing container within which you need a JScrollPane. Then you create your visual "scene" within that JScrollPane. There are several interesting classes that you can extend to make your visual application. Have a look at the Javadoc or take a stroll through the tutorial, though not all of the tutorial is intended for use outside of the NetBeans Platform. Now that you have a Swing container with a JScrollPane, create a new Java class that extends GraphScene. Fill it out as follows: package demo; import java.awt.Image; import java.awt.Point; import java.util.Random; import javax.swing.ImageIcon; import org.netbeans.api.visual.graph.GraphScene; import org.netbeans.api.visual.widget.LayerWidget; import org.netbeans.api.visual.widget.Widget; import org.netbeans.api.visual.widget.general.IconNodeWidget; import org.openide.util.Utilities; public class DemoGraphScene extends GraphScene { private LayerWidget mainLayer; private Image image; private Random r = new Random(); public DemoGraphScene() { mainLayer = new LayerWidget(this); addChild(mainLayer); image = Utilities.icon2Image( new ImageIcon(getClass().getResource("/demo/chuk.png"))); addNode("Chuk"); } @Override protected Widget attachNodeWidget(Object arg0) { IconNodeWidget widget = new IconNodeWidget(this); widget.setImage(image); widget.setPreferredLocation(new Point(10, 20)); mainLayer.addChild(widget); return widget; } @Override protected Widget attachEdgeWidget(Object arg0) { return null; } @Override protected void attachEdgeSourceAnchor(Object arg0, Object arg1, Object arg2) { } @Override protected void attachEdgeTargetAnchor(Object arg0, Object arg1, Object arg2) { } } Most of the above code is self-explanatory, I believe. You have a LayerWidget which you add to the scene. Then you add an IconWidget, which you add to the layer. One interesting thing to note is how the icon is converted to an image, via a utility method from the NetBeans Utilities API, which you have already put on your classpath, together with the Visual Library API. In other words, there's a bunch of stuff that NetBeans Platform developers use that can also be used in your own smaller Java applications, as is the case here. To wrap up, we need to instantiate the GraphScene class from our JFrame and then set the JScrollPane so that its port view will contain the "scene". Here's how we do that, nice and easy via the JFrame constructor: private DemoGraphScene scene = new DemoGraphScene(); public DemoVisualFrame() { initComponents(); jScrollPane1.setViewportView(scene.createView()); } Next, I added a pic of Chuk to my app's source structure and then ran the application. And here's the result: Next, let's turn Chuk into a movable object. The user should be able to drag and drop him with their mouse. Hmmm. That will mean a lot of coding, right? Wrong. Here's all I needed to add, i.e., just line 6 below: protected Widget attachNodeWidget(Object arg0) { IconNodeWidget widget = new IconNodeWidget(this); widget.setImage(image); widget.setPreferredLocation(new Point(10, 20)); //I only needed to add this line: widget.getActions().addAction(ActionFactory.createMoveAction()); mainLayer.addChild(widget); return widget; } And now, when I run my app, I can use my mouse to drag Chuk to a different location: A MoveAction can only mean one thing, i.e., it can only mean that you want to move the widget. However, other actions could be implemented in a variety of ways, hence there is no default. You need to provide the content of the action yourself, as in the case of the LabelTextFieldEditor. Here, we begin by defining a class-level LabelTextFieldEditor: private WidgetAction editorAction = ActionFactory.createInplaceEditorAction(new LabelTextFieldEditor()); Next, we define out LabelTextFieldEditor, extending the TextFieldInplaceEditor class: private class LabelTextFieldEditor implements TextFieldInplaceEditor { public boolean isEnabled(Widget widget) { return true; } public String getText(Widget widget) { return ((LabelWidget) widget).getLabel(); } public void setText(Widget widget, String text) { ((LabelWidget) widget).setLabel(text); } } Finally, we add a label to our widget. We also assign the editor action defined above to our widget. Here we go, just line 7 and 8 below: @Override protected Widget attachNodeWidget(Object arg0) { IconNodeWidget widget = new IconNodeWidget(this); widget.setImage(image); widget.setPreferredLocation(new Point(10, 20)); //I added the following two lines: widget.setLabel("Chuk"); widget.getLabelWidget().getActions().addAction(editorAction); widget.getActions().addAction(ActionFactory.createMoveAction()); mainLayer.addChild(widget); return widget; } That's it. Let's run our app again. You now have a label which you can click and then it is editable: When you press Enter, the label is changed. But what's the point of having just Chuk in our application? Let's add another evangelist, Gregg Sporar: private Image CHUK = Utilities.icon2Image(new ImageIcon(getClass().getResource("/demo/chuk.png"))); private Image GREGG = Utilities.icon2Image(new ImageIcon(getClass().getResource("/demo/gregg.png"))); Next, we'll create a hash table, so that we can manipulate them more effectively: private final Hashtable mapping; { mapping = new Hashtable(); mapping.put("Chuk", CHUK); mapping.put("Gregg", GREGG); } Then, we'll add them both, rather than just one: public DemoGraphScene() { mainLayer = new LayerWidget(this); addChild(mainLayer); //Here we create our two evangelists: addNode("Chuk"); addNode("Gregg"); getActions().addAction(editorAction); } We'll need to rewrite our earlier method just a bit, so that it is more generic, because now it will have to handle both Chuk and Gregg: @Override protected Widget attachNodeWidget(Object node) { Image image = (Image) mapping.get(node); if (image != null) { return createNewWidget(node, image); } throw new IllegalArgumentException(node.toString()); } And we move all the code from the previous implementation of the above method to a new one: protected Widget createNewWidget(Object label, Image image) { IconNodeWidget widget = new IconNodeWidget(this); widget.setImage(image); widget.setPreferredLocation(new Point(10, 20)); widget.setLabel(label.toString()); widget.getLabelWidget().getActions().addAction(editorAction); widget.getActions().addAction(ActionFactory.createMoveAction()); mainLayer.addChild(widget); return widget; } Run the app again and now you'll have two evangelists in your "scene", instead of just one, with the same properties because they're both the same widget, as you can see from the code above: You might now think about connecting them together, which we can look at in a future article. In general, there's a lot more that can be done, of course, and the documentation on all of this goes into it all. Here's the homepage of the library. I also highly recommend Fabrizio Giudici's Creative use of the NetBeans Visual Library: the Light Table. In summary, you don't even need to like NetBeans IDE to benefit from its graph library. Just download the IDE, get the two JARs specified above, and then add them to your classpath. That's all. And then code in whatever IDE has your preference.
January 29, 2008
by Geertjan Wielenga
· 198,533 Views · 1 Like
article thumbnail
FreeMarker in NetBeans IDE 6.0: First Scenario
NetBeans IDE 6.0 provides support for FreeMarker, on many levels, covering a variety of scenarios. To not confuse things, I'll deal with each scenario in a separate article. The first scenario is aimed at NetBeans plugin authors. Authors of plugins frequently need to provide file templates to the users of their plugins. In short, FreeMarker is the language you can use to define these file templates. Your users will not deal with these file templates, at least not necessarily. Instead, they will use a wizard that will generate a file. Under the hood, the wizard will pass the values typed by the user (in the wizard's panels) to a FreeMarker file template for processing. In this article, I will show how you create such a file template and how to hook it into a wizard. In short, you will create a NetBeans module that provides a wizard that passes values to a FreeMarker template to generate a document when the user clicks "Finish" in the wizard. Take the steps below: Install the FreeMarker plugin. Install the FreeMarker Template Sample into NetBeans IDE 6.0. When you do this, you will be providing a sample project that will install syntax coloring and code completion for FreeMarker. (The sample plugin will also install other things, but so as not to confuse things, we won't look at these other features in this article.) Get the sample and install it. After you install the above plugin, go to Samples | NetBeans Modules in the New Project wizard (Ctrl-Shift-N). There you will find "FreeMarker Support Sample". Complete the wizard by clicking Next and Finish. Right-click the project node and install it. Now, all files that end in "ftl" or "template" will have FreeMarker syntax coloring and code completion. We will see this in action in a future step below. Create the plugin's initial source structure. Create a new module project, choosing NetBeans Modules | Module in the New Project wizard, and then completing the wizard, giving the project any name and code name base you like. In this case, I am interested in creating a module containing file templates for the "ItsNat" web framework. Therefore, I've called the module "ItsNatFileTemplates" and the code name base "org.netbeans.modules.itsnatfiletemplates". Generate a wizard. Let's generate the wizard's structure. Right-click the project node and choose New | Other. In the New Project wizard, choose Module Development | Wizard. Click Next. Choose "New File" and type "1" in "Number of Wizard Panels". Click Next. Type something in the class name prefix, such as "ItsNatServlet". Set something appropriate in the Category, Icon, and Package fields. Click Finish. Here's my source structure at this point: We don't need to know much about the generated code. We'll deal with the files one by one, as we need them. First, we will work with the iterator class, above it is called "ItsNatServletWizardIterator". We are going to modify it in such a way that we will add an existing panel, from the NetBeans sources, to our sequence of panels. Currently, we only have one and it is blank (look at "ItsNatServletVisualPanel1" in Design mode). So, we are going to replace this panel with an existing panel. The existing panel provides the fields "Class Name", "Project", and "Package", which we therefore will not need to create ourselves. Before continuing, open the layer file and add one attribute below the other attributes (or anywhere in the list) that modify the file template, to specify that we will be making use of the FreeMarker template engine: Set dependencies. In the next steps, we'll be adding code to the wizard iterator. Before doing so, we need to set some dependencies on modules that provide the NetBeans APIs that we will need. Therefore, set dependencies on the following: 'Java Project Support', 'Project API', and 'Project UI API' (right-click the project in the Projects window, choose Properties, click Libraries, then set dependencies on the above three and click OK). Specify our wizard panel. The first lines of the "getPanels()" method in the "ItsNatServletWizardIterator" are as follows: private WizardDescriptor.Panel[] getPanels() { if (panels == null) { panels = new WizardDescriptor.Panel[]{ new ItsNatServletWizardPanel1() }; Replace the above lines with these: private WizardDescriptor.Panel packageChooserPanel; private WizardDescriptor.Panel[] getPanels() { Project project = Templates.getProject(wizard); Sources sources = (Sources)project.getLookup().lookup(Sources.class); SourceGroup[] groups = sources.getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA); packageChooserPanel = JavaTemplates.createPackageChooser(project,groups); if (panels == null) { panels = new WizardDescriptor.Panel[] { packageChooserPanel, }; The above is a bit of magic that replaces the wizard panel that we created with a panel that all Java source file wizards have in NetBeans IDE. Clean up. Fix imports (Ctrl-Shift-I), making sure to select "org.netbeans.spi.project.ui.templates.support.Templates" from the Fix All Imports box. You can now delete the two classes that form the panel. That is, just delete the wizard panel and the visual panel. You don't need them. Then, having a nice little module which includes just one Java class, just install it. Try the plugin. Now, remember the category you selected, back in step 4, when you created the wizard? If not, look in the layer.xml file, which should give you a clue. Now that you have installed your plugin, you should be able to find your new wizard in the New File wizard and invoke it from there. You should see something that looks like this: Create the FreeMarker file template. When you click Finish above, nothing happens. That's what this step is all about. Let's create our FreeMarker template. Right-click the package where your Java class is found, choose New | Other and then, in the New File wizard, choose Other | Empty File. (You'll see a FreeMarker category, installed by the plugin that we installed in step 1 above, but let's leave that for a future article.) Type "ItsNatServlet.ftl" (or something else, so long as the extension is ".ftl"). Then... specify your FreeMarker template, as shown in the screenshot below. And now you can see the syntax coloring and code completion provided by NetBeans IDE 6.0, via the plugin you installed at the start of this tutorial. (It is at this point that FreeMarker becomes relevant, so apologies for the time it took to get here, but this is the exact context where FreeMarker begins to be useful in this scenario.) Hook the FreeMarker file template into the plugin. Now that our FreeMarker template is done, let's hook it into our wizard so that, when Finish is clicked by the user, it is used to create the user's file. First, open the layer.xml file and add a "URL" attribute to the file name definition of the template, pointing to the location of our FreeMarker template, and changing the extension of the file name to specify that we wll create a file with the ".java" file extension: Back in the iterator, i.e., our Java class, look at the instantiate method: public Set instantiate() throws IOException { return Collections.EMPTY_SET; } First, set dependencies on "File System API", "Datasystems API", and "Nodes API". Then change the above method to the following: public Set instantiate() throws IOException { String className = Templates.getTargetName(wizard); FileObject pkg = Templates.getTargetFolder(wizard); DataFolder targetFolder = DataFolder.findFolder(pkg); TemplateWizard template = (TemplateWizard) wizard; DataObject doTemplate = template.getTemplate(); doTemplate.createFromTemplate(targetFolder, className); FileObject createdFile = doTemplate.getPrimaryFile(); return Collections.singleton(createdFile); } Now install the module again. This time, when you complete the wizard, you will have a new "ItsNat" servlet: If you don't have the "ItsNat" JAR files on the classpath, you'll also have... helpful red error marks in the editor. At this point, there are several open items to explore in the next part of this series—for example, we defined a set of variables in the FreeMarker template. They were magically replaced when we created the file via the wizard. How did that happen? Also, the FreeMarker template starts with lines of code that seem to relate to a project license. But... when the file was created, there was no project license. Why? These two questions and others will be handled in the next part of this series.
January 21, 2008
by Geertjan Wielenga
· 34,001 Views
  • Previous
  • ...
  • 311
  • 312
  • 313
  • 314
  • 315
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×