Archive

Posts Tagged ‘netbeans’

NetBeans Platform – Duplicate pair in treePair error

March 5, 2011 Leave a comment

I have previously written about the NetBeans Platform
I’ve been using a lot recently at work and so have found a lot of pain points when using the APIs. I’ll try to document some of the more vexing problems here for other programmers who might be facing the same problem.

One problem you will probably face while using the NetBeans Platform is an inscrutable error message when you start up your application, something to the effect of:

java.lang.IllegalStateException: Duplicate pair in treePair1: java.lang.Object pair2: java.lang.Object index1: 55 index2: 55 item1: null item2: null id1: 16309239 id2: 4ecfe790

    at org.openide.util.lookup.ALPairComparator.compare(ALPairComparator.java:83)
    at org.openide.util.lookup.ALPairComparator.compare(ALPairComparator.java:54)
    at java.util.TreeMap.put(TreeMap.java:530)
    at java.util.TreeSet.add(TreeSet.java:238)
    at org.openide.util.lookup.AbstractLookup.getPairsAsLHS(AbstractLookup.java:322)
    at org.openide.util.lookup.MetaInfServicesLookup.beforeLookup(Met…

While it’s impossible to know from this error message, this really indicates that you had some sort of exception in the initializer of one or more of your TopComponents, leading to duplicate null entries in some internal set that NetBeans Platform maintains, leading to this error message. Fortunately, there is usually a “Previous” button on the exception window so you can see what caused the real problem.

NetBeans – Filter output

February 6, 2011 Leave a comment

Filter dialog box accessible via Ctrl + G shortcut in output window

NetBeans allows you to filter the logging output of an application, if you stumble upon the feature. I normally use the Find command in the Output window to search for occurrences of a string with the Ctrl + F (Command + F on Mac) shortcut, and then go to the next matching result with the Command + G shortcut when I’m searching for something in particular (e.g. a line logging the state of a variable in the program). I found that if you press Ctrl + G instead, you can filter the output to show only lines that match a given string or regular expression. This is an extremely useful feature, and one I only found by accident. I hope this helps any NetBeans developers out there.

Categories: NetBeans Tags: , ,

NetBeans Platform – how to register a class as a provider of multiple services

January 24, 2011 4 comments
In NetBeans Platform, there is an annotation called ‘ServiceProvider‘, which allows you to declare that your class provides a certain service (i.e., implements a given interface).   This ties directly into the previously blogged about topic of Lookups, as the class thus annotated is added to the global, default lookup.  Recall that a lookup is a nice wrapper around a Map<Class<E>, Collection<? extends E>>, and allows modules to decouple themselves from the service they request from the actual concrete implementation that they receive.  (A much more in-depth discussion can be found on the Dev FAQ section on lookups).

The issue I ran into is that the documentation is not very clear how you can register your class as providing more than one service (again, implementing more than one interface).  For instance, say I have two interfaces I want a class to fulfill:

public interface Foo {
    public String getFoo();
}

public interface Bar {
    public String getBar();
}

public class FooBar implements Foo, Bar {
    public String getFoo() { return "foo"; }

    public String getBar() { return "bar"; }
}
Since you cannot annotate a class twice, the naive solution fails:
// This is a mistake; you can't declare two annotations like this
@ServiceProvider(service=Foo.class)
@ServiceProvider(service=Bar.class)
public class FooBar implements Foo, Bar {
The correct solution is to use the ServiceProviders annotation, which allows you to provide a list of @ServiceProvider declarations.
@ServiceProviders(value={
    @ServiceProvider(service=Foo.class),
    @ServiceProvider(service=Bar.class)}
)
Now you can find the FooBar instance via either defined interface.

NetBeans – Reformat text

January 13, 2011 Leave a comment

The NetBeans IDE has a great shortcut for reformatting sourcecode.  Simply hit ⌃⇧F (ctrl shift f), and all the sourcecode in the current file will be reformatted.  This is a great feature, and I only stumbled upon it through a StackOverflow search.

Before reformatting. This is how the code looked on StackOverflow

After running the algorithm. Note how much more readable it is

(Sourcecode taken from this stackoverflow post)

The other time it’s useful is when working on a project where someone is using very large tab settings (e.g. 8 spaces per tab instead of 4).  This can make it very difficult to read.  By invoking this command, you’ll put the code into a much more readable format.

Reset windowing system in NetBeans Platform

January 5, 2011 3 comments
One of the benefits of building programs on top of NetBeans Platform is the powerful windowing and docking framework it provides out of the box.  Part of this functionality is persistence; when a user closes a NetBeans Platform application, the state of all the windows is saved.  The next time the application is started, the windowing state is restored.  This is why the NetBeans IDE (which is built on the NetBeans Platform) remembers which files you had loaded and how you had your windows arranged.
During development, it is sometimes beneficial to do a ‘factory reset’ and reset the windows back to the way they would look when the application is launched for the first time. For instance, you may have inadvertently closed some windows you wanted to have open, or you opened some windows that you wanted closed and don’t feel like manually restoring each window’s open/closed state. Or perhaps you moved some of the windows in a position that made sense for testing part of the application, but now you want to test another part that requires the original windowing setup.

Clean and build

There are two main ways to do this.  The easiest way is to do a full clean and build of the project (right click on the top level project node in NetBeans and choose Clean and build)

This works fine, but it has the drawback of.. cleaning and rebuilding the project.  This can take a long time for complex projects, and is a bit overkill if all you want to do is reset the windowing system.

Remove Windows2Local

The second way of accomplishing this is to remove a folder named “Windows2Local”.  If the root of your NetBeans Platform project is located at /path/to/Foo, then the folder to remove is /path/to/Foo/build/testuserdir/config/Windows2Local
You can delete the folder any way you see fit; I usually do a
rm -rf /path/to/Foo/build/testuserdir/config/Windows2Local
from the terminal.
This folder contains the saved information about the window placement and sizes; by removing it, you force NetBeans to recreate it when the application restarts.
This method is much faster, as nothing needs to be recompiled.  It is my preferred way of resetting the windowing system back to its default state when developing NetBeans Platform applications.

NetBeans Platform – ModuleInstall ClassNotFoundException

January 3, 2011 Leave a comment

In the NetBeans Platform, you can create an ModuleInstall class which handles the lifecycle of your module, and provides methods you can override to handle when your module is loaded and unloaded.  The standard way of creating this class is to use the wizard that NetBeans provides for this purpose, accessible by right clicking on the project and choosing New -> Other -> Module Development -> Module Installer

If you decide that you do not want to use the ModuleInstall mechanism any longer (the NetBeans Platform folks suggest you do NOT use it, as it will increase the startup time of the application), you might think you can just delete the Installer.java file that the wizard created.  Unfortunately, that’s not the case.  When you run the project you’ll get an exception like the following

org.netbeans.InvalidException:  
StandardModule:net.developmentality.moduleexample jarFile: ...
  java.lang.ClassNotFoundException:  net.developmentality.moduleexample.Installer starting from  ModuleCL@482...

The problem is that the wizard modified the manifest.mf file as well, and you need to manually clean up the file before your project will work again.

Open the manifest.mf file and you’ll see a line in the file like the following:

OpenIDE-Module-Install: net/developmentality/moduleexample/Installer.class

delete that line, and rebuild.  You should be ready to go.
In general, you need to be very careful about using any of the wizards that NetBeans provides.  They are extremely useful, but they end up changing XML files that you will need to manually edit later if you decide to refactor.  For instance, if you create an Action instance using the New Action Wizard, the action will be registered in the layer.xml file.  If you rename the action using the refactor command, the entries in the xml file are NOT modified, and you will get an exception at runtime unless you remember to edit that file.
Fortunately, the wizards are smart enough to at least tell you which files they are modifying.  It’s just a matter of remembering this further down the road when you need to refactor, move, or delete files.  Look for the modified files section in the wizard dialog:

 

Two shortcuts for NetBeans navigation

December 10, 2010 Leave a comment

NetBeans is my Java IDE of choice, and I have written about it a few times in the past.  There are a slew of features to make you more productive and today I will highlight two shortcuts that are essential to efficient navigation.  I will show you how to jump quickly to any file in any open project, and how to search for a string in any file.

Jump to any file in any open project
⌃⇧ O

Ctrl Shift O = Go to File
By typing this shortcut at any time, you launch the Go to File dialog.  This dialog allows you type pieces of any file name, and you will see results returned in near real time.  This is excellent for when you know the approximate name of the file you’re looking for (you can insert a ‘*’ character as a wildcard, so if you know the word ‘foo’ appears somewhere in the word, you would search for *foo.

Search results are returned instantly

This dialog is a great example of incremental search, a UI technique I blogged about previously.  The incremental search is beneficial because it gives you instant feedback on your search query, allowing you to modify it as necessary to find what you’re looking for.
Those of you who use TextMate might recognize this feature; in TextMate this dialog is accessible via ⌘T (Command T).
The difference is that TextMate’s search is faster, and it is more forgiving (you can search for just a few letters in the file you’re searching for and still find it; you don’t need to know the precise name).
In general it’s much faster to search for files than to navigate through the file hierarchies manually.

Search for string

The second shortcut is to search for text in all the open projects (or narrowing it down to a select few files if you prefer).  This command is easily accessible when right clicking on a project node, but it’s accessible any time via keyboard shortcut as well

⇧ ⌘ F – Find in projects
Shift Command F

This one’s pretty self explanatory, but it took me awhile to stumble onto the shortcut, and it’s a pretty helpful one to know.

I hope these two shortcuts make your time in NetBeans a little easier.

Increase heap size for NetBeans Platform project

December 9, 2010 4 comments

To increase the heap size in a NetBeans Platform project, you can edit the nbproject/platform.properties file and add the line

 

run.args.extra=-J-Xmx1G

 

, replacing the 1G piece with however much memory you’d like. (The other solutions I found did not work for me). Thanks to the NetBeans Forums for this solution.

If you’re curious about the -J piece, it’s necessary to ensure that the arguments are passed to the JVM rather than interpreted by NetBeans itself. This should work in general for whatever arguments you want to pass to the JVM upon launch of your NetBeans Platform project.

Customize code formatting in NetBeans

December 6, 2010 4 comments
Sometime recently, (perhaps 6.9?) NetBeans changed the default code formatting algorithms.  I prefer to write my if/else statements as follows:

if (cond1) {
}
else {
}
I found that, every time I put else on a new line by itself, the else was automatically unindented, along with the closed bracket.

Indentation problems

After unsuccessfully searching online, I eventually stumbled onto some settings that control this behavior.  By default, NetBeans wants to format your if/else statements as follows:

if (cond1) {
} else { // 'else' is on the same line as the closing brace
}

If you want to have a new line after your closing brace, as I do, you need to change some settings.

Go into Preferences -> Editor -> Formatting.  Change the language to Java, and the Category to alignment.

New line settings panel

Make sure the “else” checkbox is checked in the “new lines” section.  Customize the rest of it to suit your coding style.

Categories: NetBeans Tags: , ,

NetBeans Platform – how to customize the title bar and remove datestamp

November 10, 2010 8 comments

Problem:

When you create a NetBeans Platform project, the title bar includes a datestamp/version identifier which is visually distracting.  You’d like to customize the title bar.
Default title versioning

Right click on the project node, and choose Find.  In the dialog box, search for {0}.

In the results, double click on the first Bundle.properties, in branding/modules…

Replace the lines with {0} with what you desire the title to be:
relaunch the program.

Updated title bar

You can also change the title at runtime with the following code:
Frame f = WindowManager.getDefault().getMainWindow();
f.setTitle("My title");


These are modified instructions based off of a thread found here.  See instructions on how to change the versioning number, if that’s what you desire, here.

 

EDIT:

If you are attempting to change the window title programmatically from an Installer instance, you’ll find that this doesn’t work.  The problem is that you are changing the title too early in the lifecycle.  Instead, you need to do the following:

// Only change the window title when all the UI components are fully loaded.
        WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
            @Override
            public void run() {
                WindowManager.getDefault().getMainWindow().setTitle(windowTitle);
            }
        });