Archive for April, 2010


April 11, 2010 Leave a comment

Just a quick post about a great online tool I was shown (thanks Eric) called Colorbrewer.

There are numerous books and articles online about color palette design, usually from a web-design / aesthetic standpoint.  But there is more to the use of color than mere aesthetics; color can be used as an effective tool in scientific data visualization.  One of the few books on the topic describes its contents as a guide to “how scientists and engineers can use color to help gain insight into their data sets through true color, false color, and pseudocolor imaging.”  While the content of the book is a bit beyond the scope of this post, it’s clear that color gets a lot of use in charts and graphs, and being able to better pick colors is beneficial.
ColorBrewer is designed to help users pick a set of colors that is best used to show data on a map.  Unlike most color scheme choosers where you pick whether you want muted colors, bright colors, pastel colors, etc., ColorBrewer starts by asking whether the data you are visualizing is sequential, diverging, or qualitative.  Sequential and diverging both have to do with quantitative data, e.g. average salaries.  Sequential is the more familiar for data; darker colors usually indicate a higher value on whatever metric is measured.  Diverging, on the other hand, treats the average as a neutral color and then uses colors with sharply contrasting hues for the high and low ends.  Qualitative could also be labeled as ‘categorical’; it means about the same thing.

Among its other features, ColorBrewer can exclude colors that would not come out well when photocopied, as well as those that would be confused by people with color blindness.  It also has mechanisms for exporting the RGB/Hex color codes of the generated color palettes for use in other applications.

Categories: UI Tags: , , ,

Java Swing Drag and Drop Troubleshooting

April 11, 2010 Leave a comment

Dragging domain objects between JTables

Drag and drop Troubleshooting

Drag and drop is an ubiquitous UI metaphor in common desktop/web applications.  I am in the process of finally learning how to accomplish drag and drop in Java through Swing; it hasn’t been an easy process.  I have been keeping track of some of the problems I have run into along the way, and will be updating this post as I find more.  Make sure you read through the whole set of Drag and Drop tutorials before you attempt to implement Drag and Drop; a lot of my mistakes came from jumping the gun and not reading through the whole document.  I will be making a post later with more complete source code illustrating how to drag and drop domain objects between components (the tutorials online usually show text being dragged and dropped rather than class instances).

Problem: When I attempt to drag an item out of the table, nothing happens

  • Did you remember to call “component.setDragEnabled(true)” first?
  • Make sure you are not using a DataFlavor constructed with default constructor; if it is the drag action will not occur

Problem: When I complete a drag and drop, I get a class cast exception
Solution: Make sure you have created the DataFlavor correctly; you should define the class of the serialized object within the constructor to the DataFlavor.  E.g. if you are sending an instance of a class named, you could create a DataFlavor as follows:

public class Foo implements Transferable, Serializable {

    public static final DataFlavor DATA_FLAVOR = new DataFlavor(Foo.class, "Foo");

    public DataFlavor[] getTransferDataFlavors() {
         return new DataFlavor[]{DATA_FLAVOR};

    public boolean isDataFlavorSupported(DataFlavor flavor) {
        return flavor == FLAVOR;

    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
        return this;

Problem: When I attempt to drop an item onto a table, nothing happens
If the table is empty, make sure you called “JTable.setFillsViewportHeight(true)” first?  Explanation:

JTable.setFillsViewportHeight(true)is invoked to set the fillsViewportHeight property. When this property is true the table uses the entire height of the container, even if the table doesn’t have enough rows to use the whole vertical space. This makes it easier to use the table as a drag-and-drop target. (

See more info about and drag and drop with respect to empty tables.

Problem: When I move an item from one table to another, the item isn’t deleted from the first table
Solution: Make sure you do the modification to the underlying table model in the exportDone method.

For instance:

public void exportDone(JComponent c, Transferable t, int action) {
    if (action == TransferHandler.MOVE) {
        JTable table = (JTable) c;
Categories: Java, programming, UI Tags: , , ,

NetBeans Platform Lessons Learned/Gotchas – Part 1

April 1, 2010 3 comments

As I stated in a previous post, NetBeans is my IDE of choice.  I find it extremely powerful and capable; it is the program I spend most of my day working in.  Fortunately the hard work that went into the NetBeans IDE can be leveraged by average users through the use of the NetBeans Platform (NBP for brevity here).  You can create standalone desktop clients using all the same features of the NetBeans editor (syntax highlighting, robust docking framework, property editors, etc.), without having to worry about coding all these complex features from scratch.  With such a powerful and complex API to learn, there are bound to be stumbling blocks.  This is the first in what’s sure to be a series of lessons I’ve learned while working in the NetBeans Platform.

Learning resources

I purchased a book to learn the NetBeans Platform, but I was getting nowhere with it.  Sometimes you need to be handheld through the process of doing something the first few times, and the book just omitted too many steps.  For instance, there are oftentimes you must add dependencies to your project that the book omits.  I highly recommend the NetBeans Platform Learning Trail, particularly the series of tutorials starting with Managing Selection.  There is a concept of a Lookup in the NetBeans Platform which is just a map from Class to the set of instances of that class; it is used extensively in NBP and understanding it is extremely important.  The section in the book did not do it justice; going through the tutorials methodically did the trick.

Lookup Woes

I’m not going to repeat what is said in the tutorial, but I do want to point out one gotcha that had me hung up for awhile.

Rather than keeping track of which windows have focus and reacting to this, you can instead use a Lookup that proxies whatever window has focus.  So if user clicks from editor window to an output window, you can react to this.  Here is the description:

Utilities.actionsGlobalContext() is a Lookup which proxies the Lookup of whichever TopComponent currently has keyboard focus, and fires changes when focus moves to a different component.

The example they give is as follows:

private Lookup.Result result = null;
public void componentOpened() {
    Lookup.Template tpl = new Lookup.Template (APIObject.class);
    result = Utilities.actionsGlobalContext().lookup(tpl);
    result.addLookupListener (this);

Why is this useful?  Let’s use the Properties window as an example.  When you have the properties window open, it always displays the properties of the currently focused window.

When the editor is focused, details about the source file are provided

When the Files menu is focused, details of the currently selected node are provided

The tutorial does not show how you would listen to the Lookup of just a single topcomponent.  Why would you want to do that?  Say you are writing a custom control which somehow edits aspects of the object(s) returned by the lookup returned by Utilities.actionsGlobalContext().  As soon as you click into your custom component, the focus changes, and the lookup now points to a different object (or none at all), meaning you can’t edit the properties you were trying to.  (Somehow the built in properties panel avoid this problem; I don’t know what they do).  But regardless, sometimes you would like to listen to just the lookup of a single window.  To do this you might expect something like:

private Lookup.Result result = null;
public void componentOpened() {
    Lookup.Template tpl = new Lookup.Template (APIObject.class);
    // TopComponent implements LookupProvider

    TopComponent componentToTrack = TheTopComponent.getInstance();
    Lookup toTrack = componentToTrack.getLookup();
    result = toTrack.lookup(tpl);
    result.addLookupListener (this);

And that would be a good first effort.  Unfortunately, following their pattern doesn’t work.  You have to add a call to allItems() or allInstances() before you actually receive Lookup events.  Pretty crazy huh?  The only way I found this out (I don’t see it in the Javadocs at all) is through a lot of googling; the page in question is here.  The correct code is thus

private Lookup.Result result = null;
public void componentOpened() {
    Lookup.Template tpl = new Lookup.Template (APIObject.class);
    // TopComponent implements LookupProvider

    TopComponent componentToTrack = TheTopComponent.getInstance();
    Lookup toTrack = componentToTrack.getLookup();
    toTrack.allItems(); // allInstances() seems to work too
    result = toTrack.lookup(tpl);
    result.addLookupListener (this);

That issue really stymied me for awhile, so hopefully someone can save some frustration due to this post.  It reminds me of problems I had with Android; the workaround is just as unintuitive.

Wrapping Libraries

Unlike standard Java programs, you cannot just add jars to a libraries folder and expect to be able to use them in a NetBeans Platform project.  Instead, you must create a Module that wraps each jar you want to use.  See the Dev FAQ page for more info.  Fortunately they make it pretty easy to do this; you can just right click the Modules folder, choose Add New Library, then follow the steps in the wizard.

Let’s make this concrete; let’s say I need to use apache-commons-beanutils in a project.  I download the jar and wrap it.

I now have a module in my project that merely wraps the jar.

I start using the bean classes:

As you can see, it won’t compile.  This is because we have not indicated that the API module depends on the commons-beanutils module.

After adding the dependency, everything compiles.

You might expect everything to be fine at this point, but you’d be wrong.  If you ran this example, you would get a ClassPathNotFoundException for some Apache Commons Logging components.  If you had read carefully the dependencies page, you wouldn’t be surprised.  But you probably were surprised that you didn’t see any warnings of any kind.  The secret is you have to choose “Build” on the wrapped jar file.

If you do, you will see a few warnings like the following:

Warning: org.apache.commons.beanutils.BeanComparator cannot access org.apache.commons.collections.comparators.ComparableComparator
Warning: org.apache.commons.beanutils.BeanMap cannot access org.apache.commons.collections.Transformer
Warning: org.apache.commons.beanutils.BeanMap cannot access org.apache.commons.collections.set.UnmodifiableSet
Warning: org.apache.commons.beanutils.BeanMap cannot access org.apache.commons.collections.list.UnmodifiableList
Warning: org.apache.commons.beanutils.BeanMap$2 cannot access org.apache.commons.collections.Transformer
Warning: org.apache.commons.beanutils.BeanMap$3 cannot access org.apache.commons.collections.Transformer
Warning: org.apache.commons.beanutils.BeanMap$4 cannot access org.apache.commons.collections.Transformer
Warning: org.apache.commons.beanutils.BeanMap$5 cannot access org.apache.commons.collections.Transformer
Warning: org.apache.commons.beanutils.BeanMap$6 cannot access org.apache.commons.collections.Transformer
Warning: org.apache.commons.beanutils.BeanMap$7 cannot access org.apache.commons.collections.Transformer
(additional warnings not reported)

Those warnings should tell you pretty unequivocally that things are going to go terribly wrong if you attempt to use the jar as it is.  You need to add the dependency to the wrapped library jar, in the same way that you added the dependency to the beanutils wrapper module to the API module.

The reason I went through this example is that nowhere online did I see a real world example like this where wrapped library modules themselves need to have their dependencies resolved; the tutorials always have the ideal world of “A depends on B, so A must declare a dependency on B’s wrapper module”.

If you’ve done all this and still have class path not found exceptions, I would advise that you do a full clean build of the project, perhaps replacing the jars with new builds of them as well.  That was the only way I got my dependency problems resolved in one hairy instance.

The moral of the story is ALWAYS attempt to build wrapped module jars.  If you don’t, everything will compile fine but you will get nasty runtime exceptions later.  Don’t ignore the warnings!

Property Sheets

As mentioned earlier, one of the strengths of the NetBeans platform is that you can use the Swing components that NetBeans have developed in your own project.  One of the most useful one of these is the PropertySheetView.  If you’ve designed interfaces in the Matisse GUI builder, you’re no doubt familiar with this.  See earlier in this post for some screenshots of the PropertySheetView component.  It’s fairly simple, merely a two column view of key value pairs.  Properties that cannot be edited are greyed out.  There are mechanisms for creating custom editors (e.g. you can make a color picker pop up when a color is modified, rather than typing in RGB values), and you get a lot of functionality from this component.

In order for the PropertySheetView to display anything, it needs to be associated with a Node.  As the Javadocs say:

This class is a view to use it properly you need to add it into a component which implements ExplorerManager.Provider. Good examples of that can be found in ExplorerUtils. Then just use ExplorerManager.Provider.getExplorerManager() call to get the ExplorerManager and control its state.

It’s slightly confusing and complicated, but just follow the examples here and in the previous tutorials.

To definine what shows up when a node is displayed in a PropertySheetVIew, you must override the createSheet method.  The general pattern is as follows:

protected Sheet createSheet() {

    Sheet sheet = Sheet.createDefault();
    Sheet.Set set = Sheet.createPropertiesSet();
    // Replace with whatever object you're wrapping with this node; make sure that your
    // lookup is set correctly
    APIObject obj = getLookup().lookup (APIObject.class);

       // Here is where the hard part is. How do you define these?
    Property[] properties = ...;
    return sheet;

Generally, what you want to display in a property sheet view is all the properties of the node, e.g. those variables exposed via getters and/or setters.  I won’t rehash how to do this here; the previously mentionedNodes API Tutorial shows how to expose a few properties.

The reason I mention this is because I glanced over part of the source code they provided:

protected Sheet createSheet() {

    Sheet sheet = Sheet.createDefault();
    Sheet.Set set = Sheet.createPropertiesSet();
    APIObject obj = getLookup().lookup(APIObject.class);

    try {

        Property indexProp = new PropertySupport.Reflection(obj, Integer.class, "getIndex", null);
        Property dateProp = new PropertySupport.Reflection(obj, Date.class, "getDate", null);



    } catch (NoSuchMethodException ex) {

    return sheet;


Did you miss it too?


If you forget the call to setName on a node, your properties will not show up in the property sheet view.  Why is that?  A careful reading of the javadoc for the put methods reveals the answer:


public Node.Property<?> put(Node.Property<?> p) Add a property to this set, replacing any old one with the same name.
Parameters:p – the property to add Returns:the property with the same name that was replaced, or null for a fresh insertion


public void put(Node.Property<?>[] ar) Add several properties to this set, replacing old ones with the same names.
Parameters:ar – properties to add

My problem was that I was calling setDisplayName on the Property object, without the corresponding setName call.  Thus only the last property I added ended up showing up in the view, because all the Property objects had the same name field (null).  I was led down a false trail when I noticed that all the Property objects had the same hashcode (0).  I reimplemented the hash function to ensure it would be different for all, but the set still only contained one object.  In hindsight, the hashcode of 0 should have tipped me off to a null field rather than assuming that the creators had messed up the hashCode function.


NetBeans Platform is an extremely powerful framework for building Java applications.  The learning curve is very steep, and I hope you can learn from my mistakes.  To recap, the big takeaways were

  • Use the online tutorials rather than a book.  They show each step in detail, instead of glossing over crucial steps
  • You have to add a call to allItems() or allInstances() before you actually receive Lookup events from a LookupListener
  • When dealing with wrapped libraries, make sure you build them to catch any warnings about inaccessible classes
  • When dealing with properties, you must call setName() on them in order to have them show up in a PropertySheetView
    • Read the JavaDocs carefully before you go off and start doing stupid things like reimplementing hash functions.  Chances are, it’s not broken, you’re just not using it right.  To borrow a phrase, “If you hear hoofbeats, think horses, not zebras”