如何获取选定的行,包括 JTree 的 child 行
How to get selected rows including child rows of a JTree
我正在使用 TransferHandler
在 JTree 组件上实现拖放功能。我在 CodeRanch 上使用了 this 旧线程,这几乎是唯一明显的资源,每当任何论坛中出现与此相关的任何问题时,它都会被链接到。
我已经让它与我的数据和我的 UI 一起很好地工作,因此可以轻松地拖放 leaf-Nodes。问题来了,当我尝试拖动具有 children 的节点时。覆盖的布尔函数 canImport(TransferSupport support)
returns false,因为它检查树上的 selected 行。因此,然后我测试了我是否可以 CTRL + Click
手动 select child 节点 select 我的拖动操作的“根”节点后,它工作得很好并且节点,包括它的所有 children 被拖放。
我的问题是:要获得 selected 行,我调用 tree.getSelectionRows()
并将该值保存到整数数组。如何将 child-rows 放入该整数数组?我知道我可能会重写我的 TransferHandler
的其他部分,但由于其他一切都很好,如果它实际上 select 我预期的行,我觉得这就是更简单的方法。
所以,拖放是……复杂的。您需要注意很多问题。
在链接示例中,您应该注意它处理的是 DefaultMutableTreeNode
而不是 TreeNode
,这可能不是问题,但您可能需要牢记这一点。
如果未选择子元素,haveCompleteNode
似乎会阻止您移动分支节点……这对我来说似乎有些奇怪。
此外,它后面的代码似乎会阻止您 moving/copying 将节点移动到高于源节点当前级别的位置...出于某种原因
我也不确定我是否会保留所选节点的两个副本,这是我,但防御副本似乎有点过头(可能是一个特殊的边缘情况,但我会担心如果树可以在拖动操作期间更新,但我就是这样)。
那么,这里的教训是什么?
您在网络上找到的任何代码都需要您花一些时间实际弄清楚它在做什么。它可能一开始很适合您的需要,但在某个时间点,您将不得不挽起袖子并深入研究以根据自己的需要对其进行修改。
您应该做的第一件事是充分了解 Drag and Drop and Data Transfer 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);
}
}
}
}
就“我在网上找到的代码”而言,这还不错。
我正在使用 TransferHandler
在 JTree 组件上实现拖放功能。我在 CodeRanch 上使用了 this 旧线程,这几乎是唯一明显的资源,每当任何论坛中出现与此相关的任何问题时,它都会被链接到。
我已经让它与我的数据和我的 UI 一起很好地工作,因此可以轻松地拖放 leaf-Nodes。问题来了,当我尝试拖动具有 children 的节点时。覆盖的布尔函数 canImport(TransferSupport support)
returns false,因为它检查树上的 selected 行。因此,然后我测试了我是否可以 CTRL + Click
手动 select child 节点 select 我的拖动操作的“根”节点后,它工作得很好并且节点,包括它的所有 children 被拖放。
我的问题是:要获得 selected 行,我调用 tree.getSelectionRows()
并将该值保存到整数数组。如何将 child-rows 放入该整数数组?我知道我可能会重写我的 TransferHandler
的其他部分,但由于其他一切都很好,如果它实际上 select 我预期的行,我觉得这就是更简单的方法。
所以,拖放是……复杂的。您需要注意很多问题。
在链接示例中,您应该注意它处理的是 DefaultMutableTreeNode
而不是 TreeNode
,这可能不是问题,但您可能需要牢记这一点。
如果未选择子元素,haveCompleteNode
似乎会阻止您移动分支节点……这对我来说似乎有些奇怪。
此外,它后面的代码似乎会阻止您 moving/copying 将节点移动到高于源节点当前级别的位置...出于某种原因
我也不确定我是否会保留所选节点的两个副本,这是我,但防御副本似乎有点过头(可能是一个特殊的边缘情况,但我会担心如果树可以在拖动操作期间更新,但我就是这样)。
那么,这里的教训是什么?
您在网络上找到的任何代码都需要您花一些时间实际弄清楚它在做什么。它可能一开始很适合您的需要,但在某个时间点,您将不得不挽起袖子并深入研究以根据自己的需要对其进行修改。
您应该做的第一件事是充分了解 Drag and Drop and Data Transfer 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);
}
}
}
}
就“我在网上找到的代码”而言,这还不错。