各位,如果在JTree上实现右键拖放?本人试过如果用左键可以,但如果同时按下shift再左键拖放就失效了,本人想知如何用右键拖放一个jtree上的数据到一个jtable,或者用右键拖放Jtree上的数据到jtable?

解决方案 »

  1.   

    import java.awt.BorderLayout;
    import java.awt.Point;
    import java.awt.event.MouseEvent;import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTree;
    import javax.swing.SwingUtilities;
    import javax.swing.TransferHandler;
    import javax.swing.event.MouseInputAdapter;
    import javax.swing.tree.TreePath;
    public class T
    {
    public static void main(String[] args)
    {
    DragHandler dragHandler = new DragHandler();

    JTree tree = new JTree();
    tree.setTransferHandler(new TransferHandler("selectionPath"));
    tree.addMouseListener(dragHandler);
    tree.addMouseMotionListener(dragHandler); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, 
    new JScrollPane(tree), new JScrollPane(new TestTable()));

    JFrame f = new JFrame();
    f.getContentPane().add(splitPane, BorderLayout.CENTER);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
    }
    }
    class DragHandler extends MouseInputAdapter
    {
    private TreePath path;
    private Point location; @Override
    public void mousePressed(MouseEvent e)
    {
    if (SwingUtilities.isRightMouseButton(e)) {
    JTree tree = (JTree) e.getSource();
    path = tree.getPathForLocation(e.getX(), e.getY());
    if (path != null) {
    tree.setSelectionPath(path);
    location = e.getPoint();
    }
    else {
    path = null;
    location = null;
    }
    }
    }

    @Override
    public void mouseDragged(MouseEvent e)
    {
    if (SwingUtilities.isRightMouseButton(e) && path != null && location != null) {
    if ((location.x - e.getX()) * (location.x - e.getX()) + 
    (location.y - e.getY()) * (location.y - e.getY()) > 10 * 10) {
    JTree tree = (JTree) e.getSource();
    TransferHandler transferHandler = tree.getTransferHandler();
    if (transferHandler != null) {
    transferHandler.exportAsDrag(tree, e, TransferHandler.COPY);
    path = null;
    location = null;
    }
    }
    }
    }
    }
      

  2.   

    import javax.swing.JTable;
    import javax.swing.TransferHandler;
    import javax.swing.tree.TreePath;public class TestTable extends JTable
    {
    public TestTable()
    {
    super(5, 5);
    setTransferHandler(new TransferHandler("treePath"));
    }

    public TreePath getTreePath()
    {
    return null;
    }

    public void setTreePath(TreePath treePath)
    {
    JTable.DropLocation dropLoc = getDropLocation();
    setValueAt(treePath.getLastPathComponent().toString(), dropLoc.getRow(), dropLoc.getColumn());
    }
    }