简体   繁体   English

使用自定义TreeCellRenderer(Java,Swing)将反馈拖放到JTree中

[英]Drag and drop feedback in a JTree with custom TreeCellRenderer (Java, Swing)

I have a class derived from JTree with custom TreeCellRenderers. 我有一个使用自定义TreeCellRenderers从JTree派生的类。 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. 放置模式为DropMode.ON_OR_INSERT ,因此用户可以在其他节点上或其他节点之间放置节点。 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. 这仅在我使用自定义TreeCellRenderer时发生。 If I use a DefaultTreeCellRenderer, the drop node gets highlighted during the drag. 如果使用DefaultTreeCellRenderer,则放置节点在拖动过程中将突出显示。

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. 我在网络上找到了一些示例,人们在其中存储当前在JTree中突出显示的节点,并从TreeCellRenderer查询该节点,如果为应该突出显示的节点调用TreeCellRenderer,则以不同的颜色呈现该节点。

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. 我还没有弄清楚DefaultTreeRenderer是如何做到的-似乎没有挂钩可以拖放功能。

I figured it out, so just in case anybody cares: 我想通了,以防万一有人在乎:

The answer is right here: in javadoc for TreeCellRenderer 答案就在这里: TreeCellRenderer在javadoc中

The TreeCellRenderer is also responsible for rendering the the cell representing the tree's current DnD drop location if it has one. TreeCellRenderer还负责渲染表示树的当前DnD放置位置(如果有)的单元。 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: 如果此渲染器关心渲染DnD放置位置,则应直接查询树以查看给定的行是否表示放置位置:

 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. 上面的代码应添加到getTreeCellRendererComponent()方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM