views:

597

answers:

1

I have a class derived from JTree with custom TreeCellRenderers. I have implemented drag and drop in that tree, so a user can rearrange tree nodes.

The drop mode is DropMode.ON_OR_INSERT, so the user can drop nodes on or between other nodes. While the user is dragging the node, if the pointer points between nodes, a blue line is drawn indicating a location where the node will be inserted. If the pointer is on a node, there is no indication of where the node will be added. This only happens when I use my custom TreeCellRenderer. If I use a DefaultTreeCellRenderer, the drop node gets highlighted during the drag.

I found a few examples on the web, where people store the node that is currently highlighted in the JTree and query it from the TreeCellRenderer, rendering the node in different color if TreeCellRenderer is called for the node that is supposed to be highlighted.

Is there a more elegant solution for highlighting the drop node? I haven't managed to figure out how DefaultTreeRenderer does this - there seem to be no hooks in it to drag and drop functionality.

+2  A: 

I figured it out, so just in case anybody cares:

The answer is right here: in javadoc for TreeCellRenderer

The TreeCellRenderer is also responsible for rendering the the cell representing the tree's current DnD drop location if it has one. If this renderer cares about rendering the DnD drop location, it should query the tree directly to see if the given row represents the drop location:

 JTree.DropLocation dropLocation = tree.getDropLocation();
 if (dropLocation != null
         && dropLocation.getChildIndex() == -1
         && tree.getRowForPath(dropLocation.getPath()) == row) {

     // this row represents the current drop location
     // so render it specially, perhaps with a different color
 }

The code above should be added to getTreeCellRendererComponent() method.