JTree之间的drag/drop

浏览:29日期:2023-02-11
内容: 关于JTree 之间的drag/drop一直找不到合适的方法。现通过鼠标事件的相应实现了该过程。希望和大家一起学习。源码如下:import javax.swing.*;import javax.swing.event.*;import java.awt.datatransfer.*;import java.awt.dnd.*;import javax.swing.tree.*; public class DragDropTree implements MouseMotionListener,MouseListener, DragGestureListener,DragSourceListener { private JTree tree1=null; private JTree tree2=null; Object lastNode; Vector vet=new Vector(); TreeSelectionModel selectionModel=tree1.getSelectionModel(); Vector vetnew=new Vector(); private boolean drag=false; public DragDropTree(JTree t1,JTree t2) { tree1=t1; tree2=t2; DragSource dragSource = DragSource.getDefaultDragSource(); dragSource.createDefaultDragGestureRecognizer( tree1, // component where drag originates DnDConstants.ACTION_COPY_OR_MOVE, // actions this); // drag gesture recognizer dragSource.createDefaultDragGestureRecognizer( tree2, // component where drag originates DnDConstants.ACTION_COPY_OR_MOVE, // actions this); // drag gesture recognizer tree1.addMouseMotionListener(this); tree1.addMouseListener(this); tree2.addMouseMotionListener(this); tree2.addMouseListener(this); } public void mouseEntered(MouseEvent e) { JTree selecttree=(JTree)e.getSource(); TreePath path=selecttree.getPathForLocation(e.getX(), e.getY()); if(path!=null) { if(drag&vet!=null) { drag=false; String str=path.getPathComponent(1).toString(); MutableTreeNode parent,node=(MutableTreeNode)path.getLastPathComponent(); if(node.isLeaf()) parent=(MutableTreeNode)node.getParent(); else parent=node; int index=parent.getIndex(node)+1; System.out.println('now node is in '+index+'level'); DefaultTreeModel model=(DefaultTreeModel)tree2.getModel(); int j=0; while(j1) { if(vetnew!=null){ System.out.println(vetnew.size()+'have so much path'); for(int n=0;n
相关文章: