Drag and drop feedback in JTree using custom TreeCellRenderer (Java, Swing)

I have a class derived from JTree with custom TreeCellRenderers. I implemented drag and drop in this tree, so the user can change the nodes of the tree.

Reset mode DropMode.ON_OR_INSERT, so the user can delete nodes on other nodes or between them. While the user is dragging the node, if the pointer points between the nodes, a blue line is displayed indicating the location at which the node value will be inserted. If the pointer is on a node, then it is not indicated where the node will be added. This only happens when I use my own TreeCellRenderer. If I use DefaultTreeCellRenderer, the drop node will highlight during drag and drop.

I found several examples on the Internet where people store a node that is currently highlighted in JTree and requests it from a TreeCellRenderer, with the node having a different color if the TreeCellRenderer is called for the node to be allocated.

Is there a more elegant drop node highlighting solution? I was not able to figure out how DefaultTreeRenderer does it - there are no hooks in it to drag functionality.

+3
source share
1 answer

I realized this, so just in case someone cares:

The answer is here: in javadoc for TreeCellRenderer

TreeCellRenderer , DnD, . DnD, , , drop:

 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
 }

getTreeCellRendererComponent().

+7

Source: https://habr.com/ru/post/1714603/


All Articles