我正在实现拖拽&在JTree组件上通过使用TransferHandler
。我在CodeRanch上使用了这个旧线程,它几乎是唯一明显的资源,每当在任何论坛上出现任何关于这个问题的链接。
我已经让它很好地与我的数据和我的UI工作,所以叶节点可以很容易地拖放。当我试图拖动有子节点时,问题就来了。覆盖的布尔函数canImport(TransferSupport support)
返回false,因为它检查树上的选定行。因此,我随后测试了是否我可以CTRL + Click
手动选择我的拖动操作的"根"节点后选择子节点,这工作得很好,节点,包括它的所有子节点得到拖放。
我的问题是:获得选定的行,我调用tree.getSelectionRows()
并将该值保存到一个整数数组。如何将子行放入整数数组中?我知道我可能会重写我的TransferHandler
的其他部分,但因为其他一切都工作得很好,如果只有它会实际选择行我预期它,我觉得这是更简单的方法。
所以,拖放是…复杂。有很多陷阱你需要注意。
在链接的示例中,您应该注意它处理的是DefaultMutableTreeNode
s而不是TreeNode
s,这可能不是问题,但您可能要记住它。
haveCompleteNode
似乎阻止你移动分支节点,如果它的子元素没有被选中…这对我来说有点奇怪。
此外,它后面的代码似乎阻止您移动/复制节点到源节点当前级别之上的位置…出于某种原因
我也不确定我是否会保留所选节点的两个副本,这是我,但是防御性副本似乎有点过了(可能是一个特殊的边缘情况,但我担心树是否可以在拖动操作期间更新,但那是我)。
那么,这里的教训是什么呢?
你在网上找到的任何代码都需要你花一些时间来弄清楚它在做什么。它可能一开始很适合你的需要,但在某些时候,你将不得不挽起袖子,深入研究修改它以满足你自己的需要。
你应该做的第一件事是很好地理解拖放和数据传输api。
下面是你链接的代码的修改示例,它将允许你移动分支节点(及其子节点),并允许你将它们移动到"上面的位置;它们的源深度
但是,你需要花时间去理解代码在做什么,并准备根据你的需要修改它
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.swing.DropMode;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.TransferHandler;
import static javax.swing.TransferHandler.COPY_OR_MOVE;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
public class TreeDragAndDrop {
private JScrollPane getContent() {
JTree tree = new JTree();
tree.setDragEnabled(true);
tree.setDropMode(DropMode.ON_OR_INSERT);
tree.setTransferHandler(new TreeTransferHandler());
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
expandTree(tree);
return new JScrollPane(tree);
}
private void expandTree(JTree tree) {
DefaultMutableTreeNode root
= (DefaultMutableTreeNode) tree.getModel().getRoot();
Enumeration e = root.breadthFirstEnumeration();
while (e.hasMoreElements()) {
DefaultMutableTreeNode node
= (DefaultMutableTreeNode) e.nextElement();
if (node.isLeaf()) {
continue;
}
int row = tree.getRowForPath(new TreePath(node.getPath()));
tree.expandRow(row);
}
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new TreeDragAndDrop().getContent());
f.setSize(400, 400);
f.setLocation(200, 200);
f.setVisible(true);
}
class TreeTransferHandler extends TransferHandler {
DataFlavor nodesFlavor;
DataFlavor[] flavors = new DataFlavor[1];
public TreeTransferHandler() {
try {
String mimeType = DataFlavor.javaJVMLocalObjectMimeType
+ ";class=""
+ javax.swing.tree.DefaultMutableTreeNode[].class.getName()
+ """;
nodesFlavor = new DataFlavor(mimeType);
flavors[0] = nodesFlavor;
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFound: " + e.getMessage());
}
}
public boolean canImport(TransferHandler.TransferSupport support) {
if (!support.isDrop()) {
return false;
}
support.setShowDropLocation(true);
if (!support.isDataFlavorSupported(nodesFlavor)) {
System.out.println("Unsupported flavor");
return false;
}
// Do not allow a drop on the drag source selections.
JTree.DropLocation dl
= (JTree.DropLocation) support.getDropLocation();
JTree tree = (JTree) support.getComponent();
int dropRow = tree.getRowForPath(dl.getPath());
int[] selRows = tree.getSelectionRows();
for (int i = 0; i < selRows.length; i++) {
if (selRows[i] == dropRow) {
return false;
}
}
// This seems to stop the node from been copied to a level above itself?!
// TreePath dest = dl.getPath();
// DefaultMutableTreeNode target = (DefaultMutableTreeNode) dest.getLastPathComponent();
// TreePath path = tree.getPathForRow(selRows[0]);
// DefaultMutableTreeNode firstNode = (DefaultMutableTreeNode) path.getLastPathComponent();
// if (firstNode.getChildCount() > 0 && target.getLevel() < firstNode.getLevel()) {
// return false;
// }
return true;
}
protected Transferable createTransferable(JComponent c) {
JTree tree = (JTree) c;
TreePath[] paths = tree.getSelectionPaths();
if (paths != null) {
// Make up a node array of copies for transfer and
// another for/of the nodes that will be removed in
// exportDone after a successful drop.
List<DefaultMutableTreeNode> copies = new ArrayList<DefaultMutableTreeNode>();
for (int i = 0; i < paths.length; i++) {
DefaultMutableTreeNode next = (DefaultMutableTreeNode) paths[i].getLastPathComponent();
System.out.println("Selected = " + next.getUserObject());
copies.add(next);
}
DefaultMutableTreeNode[] nodes = copies.toArray(new DefaultMutableTreeNode[copies.size()]);
return new NodesTransferable(nodes);
}
return null;
}
/**
* Defensive copy used in createTransferable.
*/
private DefaultMutableTreeNode copy(TreeNode node) {
return new DefaultMutableTreeNode(node);
}
protected void exportDone(JComponent source, Transferable data, int action) {
// Already dealt with this
}
public int getSourceActions(JComponent c) {
return COPY_OR_MOVE;
}
public boolean importData(TransferHandler.TransferSupport support) {
System.out.println("Import here");
if (!canImport(support)) {
return false;
}
// Extract transfer data.
DefaultMutableTreeNode[] nodes = null;
try {
Transferable t = support.getTransferable();
nodes = (DefaultMutableTreeNode[]) t.getTransferData(nodesFlavor);
} catch (UnsupportedFlavorException ufe) {
System.out.println("UnsupportedFlavor: " + ufe.getMessage());
} catch (java.io.IOException ioe) {
System.out.println("I/O error: " + ioe.getMessage());
}
// Get drop location info.
JTree.DropLocation dl = (JTree.DropLocation) support.getDropLocation();
int childIndex = dl.getChildIndex();
TreePath dest = dl.getPath();
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) dest.getLastPathComponent();
JTree tree = (JTree) support.getComponent();
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
// Configure for drop mode.
int index = childIndex; // DropMode.INSERT
if (childIndex == -1) { // DropMode.ON
index = parent.getChildCount();
}
// One consideration to consider is what to do if it's a different
// source model ... and it's only a "copy" operation
// Might want to look into that
for (DefaultMutableTreeNode node : nodes) {
model.removeNodeFromParent(node);
}
// Add data to model.
for (DefaultMutableTreeNode node : nodes) {
model.insertNodeInto(node, parent, index++);
}
return true;
}
public String toString() {
return getClass().getName();
}
public class NodesTransferable implements Transferable {
DefaultMutableTreeNode[] nodes;
public NodesTransferable(DefaultMutableTreeNode[] nodes) {
this.nodes = nodes;
}
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException {
if (!isDataFlavorSupported(flavor)) {
throw new UnsupportedFlavorException(flavor);
}
return nodes;
}
public DataFlavor[] getTransferDataFlavors() {
return flavors;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return nodesFlavor.equals(flavor);
}
}
}
}
就我在网上找到的代码而言,这还不算太糟。