JTree Drag N Drop

Hello All,
I am implementing Drag and Drop between 2 JTrees in a JTabbedPane.
Tree 1 on tab 1 can drag nodes to Tree 2 on tab 2.
Tree 2 can also move nodes around itself using drag and drop.
The problem I am having is that I need to know the source of the drag such that if Tree 2 is the source and the destination the node should be cut and not copied.
How can I determine if Tree 2 should move the dragged node or simply copy it?
nes

I guess you could save some identifier for the drag-source when the drag-operation occurs, like:
private String treeNameForDrag = null;
public void dragGestureRecognized(DragGestureEvent dge) {
treeNameForDrag = ((JTree)dge.getSource()).getName();
dge.startDrag(par1, par2, par3);
and when you get the dropAction you look on the variable to see which tree that is the dragSource.You have to set the name for the trees (when you create them).
public void drop(DropTargetDropEvent dtde) {
if (treeNameForDrag.equals("tree2"))
//Perform cut operation
else
//Perform move operation
I hope I got your problem right, otherwise explain the problem again and I can have another look...
Good luck!

Similar Messages

  • JTree, drag n drop, easy or hard?

    I have rapidly looked at some examples and some old threads about Drag�n�drop in general and more specific for JTree�s.
    A quick (maybe to quick?) conclusion is that there is a lot of code for doing this. What I want to do is to move nodes in one single JTree. Do I really need that much code or can I just implement some nice interfaces to acheive this?

    I ran over a chapter, Adding Drag-and-Drop Functionality, in a book, Pro Java Programming. I think it has been very helpful for my understanding so far. Even though I haven�t produced any code yet.
    At first, it is rather much you have to learn, but I think when all pieces come together, its quite straight forward.
    A question: My intent is to create a drag-and-droppable JTree. Have I understood things right if I say that I need to create some kind of Flavor-thingie, that is a TreeNode (DefaultMutableTreeNode) flavor to make it work?
    My own answer Yes if that is what I want to transfer between the drag and the drop.
    Another question related to the first:
    The following code is from an Image Viewer app where I think you shall be able to move images. Does every node need this or just the tree?
    My own answer This is at least what I do at the tree. And since a node isnt a component, it is pretty obvious it is the tree.
    protected void addNewComponent(Component comp, Point location) {
      DragSource source = DragSource.getDefaultDragSource();
      source.createDefaultDragGestureRecognizer(comp,
          DnDConstants.ACTION_COPY_OR_MOVE,
          new MyGestureListener());
      comp.setLocation(location);
      comp.setSize(comp.getPreferredSize());
      add(comp);
      repaint();
    }Message was edited by:
    sandsater

  • JTree Drag and Drop (Multi Nodes)

    Hi All!
    I have been searching the forums for a few hours over the last few days and have found some nice examples and explanations on how to implement drag and drop for a jtree.
    However, I would love to know how this is accomplished when selecting multiple nodes.
    I want to be able to see all the selected nodes being dragged...
    Anyone implemented anything of the sort... or even just knows how to do this?
    Thanks in advance!!
    Aaron.

    When you drag get the [x,y] mouse position and use the JTree method:
    getRowForLocation(x, y) for node you at the also for the parent node location of the child node.
    Once the childY is less than childParentY, you stop the drag.
    Hope that helps?

  • JTree drag and drop

    Hi.. How can I drag and drop items from one JTree to another??? thanks!!!

    The following link might help you :
    http://forum.java.sun.com/thread.jspa?forumID=57&threa
    dID=296255Thanks! this thread has been useful. How can I manipulate the code so that I can have two different trees instead of just one tree? How can I make the drag and drop one-way???

  • JTree Drag and Drop question

    I have drag and drop working fairly well using jdk 1.4. I'm able to copy and move objects around in the tree and change the cursor as it moves over various objects in the tree. The only problem I'm having is when the user drops something into someplace that rejects the drop, for instance in the blank area of the JTree object. In this case, the drop never seems to complete. If I try to drag that same object again it throws an InvalidDnDOperationException saying that a DnD operation is already in progress. I noticed that the drop() operation is not being called when the user drops the object into a rejected area.
    I've searched the forums and haven't seen anyone else report this problem. Does anyone have any suggestions?

    I'd love it too if you would send me you code, or post it so others can benefit; there seems to be quite a number of people who want DnD JTree functionality. I've been going nuts trying to figure out the best way to implement DnD on a JTree. I started using the new TransferHandler and had reasonable success with it. But, I'm not sure how to get the cursor to change based on DropTarget (not all nodes are created equal in this regard). I need access to the DragSourceContext, but I don't know how to get it when using the TransferHandler method.
    I have other issues with the TransferHandler also, like trying to make DnD work consistently with Cut-And-Paste all in the same TransferHandler. Or, trying to deal with the fact that you can change a move-type DnD operation into a copy-type operation after you start dragging, but before you drop just by pressing the control-key. This sort of implies to me that the original createTransferable() should always make a copy, so that the only issue is whether to clean up in exportDone().

  • Problem with Drag and Drop on a JTree

    I would like to have a JTree with drag and drop support with the following characteristics:
    1) The JTree holds near 100 different kinds of TreeNodes
    2) The drag and drop operation uses TreeNodes as Transferable
    3) The drop operation adds a new TreeNode child on the TreeNode that accepts the drop
    4) There are some rules for a TreeNode to accept the drops by example:
         Type1 can accept Type2
         Type2 can accept Type3
         All other combinations are not allowed
    I am using the following classes to support this behavior
    JTree
    DataFlavor
    DragSourceListener
    DropTarget
    DropTargeListener
    DragSource
    GestureListener
    Transferable
    The question is:
    How to change the cursor shape when the mouse is over a node to show graphically the drop accepting rules.?
    I can not use the the following methods to change the cursor-shape
    DropTargetListener.dragEnter
    And
    DropTargetListener.dragOver
    Case they receive a DropTargetDragEvent witch don�t knows nothing about the TreeNode type dragged.
    I can not create a TreeNode on the method GestureListener.dragGestureRecognized cause this could not work when dragging between two diffents JVM.

    Hello,
    You might want to search this forum for this class : DNDTree.java. It pretty much does the job.

  • Drag and Drop Jtree

    hi
    this code in a jtree accepts stuff dropped over using drag and drop, but when it accepts drops, they register fine. but when i expand the node, and then drop on it it refuses to accept the drop, the drop just doesnt happen!
    can you help? im totaly stuck!
    i can see that the drop is happening from system.out.println but its not regiistering on the tree gui even when i repeatedly collapse/expand the node!
    once i touch a node it refuses to accept any drops henceforth!
    public void drop(DropTargetDropEvent dtde) {
              Point point = dtde.getLocation();
              int x = (int)point.getX();
              int y = (int)point.getY();
              numberDropped++;
              TreePath path = getPathForLocation(x,y);
              System.out.println(path);
              try {
                   selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
                   System.out.println(selectedNode.getUserObject());
                   for(int i=0;i<selectedNode.getChildCount();i++) {
                        System.out.println(((DefaultMutableTreeNode)selectedNode.getChildAt(i)).getUserObject());
              } catch(Exception e) {
                   System.out.println("No available node");
              System.out.println(selectedNode.getAllowsChildren());
              System.out.println(selectedNode.getChildCount());
              try {
                   DataFlavor stringFlavor = DataFlavor.stringFlavor;
                   Transferable tr = dtde.getTransferable();
                   if(dtde.isDataFlavorSupported(stringFlavor)) {
                        String filename = (String) tr.getTransferData(stringFlavor);
                        try {
                             URL picture = new URL(filename);
                             addImageToNode(selectedNode, picture);
                             System.out.println(filename + selectedNode);
                        }catch(Exception e){
                             e.printStackTrace();
                        dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                        dtde.dropComplete(true);
                   else {
                        dtde.rejectDrop();
                        System.out.println("Drop rejected");
              catch(UnsupportedFlavorException ufe) {
                   ufe.printStackTrace();
              catch(IOException ioe) {
                   ioe.printStackTrace();
         }this is the addImageTiNode method
    public void addImageToNode(DefaultMutableTreeNode givenNode, URL pictureLocation) {
              System.out.println("In aITN");
              System.out.println(givenNode.getUserObject());
              if(givenNode.getAllowsChildren()) {
                   DefaultMutableTreeNode image = new DefaultMutableTreeNode(pictureLocation, false);
                   givenNode.add(image);
                   this.repaint();
              else {
                   System.out.println("This node does not allow children");
              //System.out.println(selectedNode + " at " + pictureLocation);
         }

    You need to call DropTargetDragEvent.rejectDrag() in
    the dragOver() method of DropTargetListener.Thanks. I have done that but it doesn't change the cursor to the defaultNoMove cursor. Any other suggestions?
    Tiny

  • Drag and Drop in JTree

    Hello
    i have developped sucessfully the drag on drop operation in my JTree and it works well but now i will also change the cursor of the mouse.
    so if you drag and drop an object in a jtree you must view the movement of that object, i think that it may be possible to change the cursor of the mouse to do that but i don't know how it works
    Is it also possible that the entire structure under the moved node is visible during moving?
    I hope that somebody can help me
    Jeff R.

    here is the code for the drag and drop operation
    public class TreeListener implements TreeSelectionListener,MouseListener,                               DragGestureListener, DropTargetListener,DragSourceListener{
         private CatalogManagerFrameListener frame;
         private CatalogElement selectedElement;
         /** Variables needed for DnD */
         DragSource dragSource = DragSource.getDefaultDragSource() ;
         private TreePath selectedTreePath;
         /** DragGestureListener interface method */
         public void dragGestureRecognized(DragGestureEvent e) {
         JTree tree = (JTree)e.getComponent();
         //Get the selected node
         if (selectedElement != null) {
              //Get the Transferable Object
              Transferable transferable = (Transferable) selectedElement;
              //Select the appropriate cursor;
              Cursor cursor = DragSource.DefaultMoveDrop;
              tree.setCursor(cursor);
              //begin the drag
              dragSource.startDrag(e, cursor, transferable, this);
         /** DropTargetListener interface method - What we do when drag is released */
         public void drop(DropTargetDropEvent e) {
              JTree tree = (JTree)((DropTarget)e.getSource()).getComponent();
              try {
                   Transferable tr = e.getTransferable();
                   //flavor not supported, reject drop
                   if (!tr.isDataFlavorSupported(CatalogElement.INFO_FLAVOR)){
                        e.rejectDrop();
                   //get source
                   CatalogElement source = selectedElement;
                   //get new parent node
                   Point loc = e.getLocation();
                   TreePath destinationPath = tree.getPathForLocation(loc.x, loc.y);
                   CatalogElement destination = (CatalogElement) destinationPath.getLastPathComponent();
                   if (testDropTarget(destinationPath, selectedTreePath)) {
                        move(source,destination);          
                        destinationPath.pathByAddingChild(source);
                        tree.setSelectionPath(destinationPath);
                   else{
                        e.rejectDrop();
              catch(Exception ex){     
                   e.rejectDrop();

  • Drag and drop in JTree's

    Hello,
    How/can do you do drag and drop of elements within or between JTree's.
    I am working on a bookmark editor program and need a tree control for sorting bookmarks in a heirachy.
    I would like some sort of insert line to appear between elements as an element is dragged, showing where it would go when droped.
    Also I want to be able to mark multiple elements for dragging.
    And also to be able to drag elements between trees.
    Is this in Swing an if so how do you program it ? And if not, how/can you go about adding this facitity.
    I am not asking for too much :) An I?
    Are there any open source programs that exhibit any of these behavious that I can use as a guide ?
    Hope you can help. Many thanks,
    Aaron - [email protected]

    http://search.java.sun.com/search/java/index.jsp?col=javaforums&qp=&qt=%2Bdnd+%2Bjtree

  • Drag and Drop between two JTrees (urgent)

    Hello,
    I want to drag a node from one JTree and Drop it to another JTree, but it is not working, I am able to Drag from JTree and drop that on Label successfully. I didn't get any tutorial regarding my problem. If anyone of you have made it. Can you please show me your code.
    Thanks in advance.
    jStudent3

    Can you please pass on the code for dragging and dropping node between two JTree? I would be glad if u cud help me. Plz mail the code to [email protected]
    thanks
    adithya

  • Drag and Drop nodes in JTree

    Is there a way to drap and drop JTree nodes without resorting to hacks? http://www.javaworld.com/javatips/jw-javatip97.html outlines a hack to get drag and drop working but it is kinda old. I am wondering whether there is a now a way to do this in Swing. http://weblogs.java.net/blog/shan_man/archive/2006/01/first_class_dra.html outlines a seemingly promising way but when I tried it it still wouldn't let me drag JTree nodes. (btw, if you are going to try it, you must replace TransferHandler.TransferInfo with TransferHandler.TransferSupport. It has apprently been renamed.)

    I have implemented drag and drop of nodes in JTree they same way it is explained in JavaWorld link that you mentioned, I customized it for my application and it worked great.

  • Drag and Drop between JTree and another component

    Hi,
    I have searched the forum for answer to this question but am not sure I found something similar to this. So, please help me out on this.
    I have a JTree and a JPanel, which basically shows images (as thumbnails) for the child nodes of one node in the tree heirarchy.
    I need to be able to drag and drop components from the JPanel to the JTree and vice versa, and of course, when you drop them on the tree, they should go under the correct node.
    I am using Swing 1.4.1, and have successfully implemented DnD in the JTree itself. But I am a little unclear about the DnD between the tree and the panel.
    Would really appreciate if someone could throw some light on this.
    Thanks a lot,
    Sri.

    Hi clairesheridan,
    thanks for your response. Your answer would have helped me if I was using JDK 1.3 but I am try to use the Swing API in jdk1.4.1, in which you have to set a transferhandler etc.
    Please let me know if you have any ideas or solutions.
    Thanks,
    sriharmya.

  • Drag and Drop between JTree and Labels in 2 different panes

    Hi,
    I am using JDK 1.4.1 and am trying to implement Drag n Drop between a JTree and JLabels with ImageIcons, both on different panes.
    I got the DnD working fine on the tree. but i cant get to drag and drop the label from the other pane, on the Jtree as a node. I am getting confused with the DataFlavors, and also wonder if there is something else that i have to do for DnD between 2 panes. Can someone give me any leads on this, please? The Panes I am talking about are splitpanes.
    thanks,
    Sri.

    hey thanks Dennis!! I was hoping you would respond to my question, as I have seen a lot of your replies. yes, the example you gave would be helpful. but i am trying to implement this in 1.4.1, with the new drag and drop in swing. and i am getting confused wiht theh data flavors etc.
    my problem at hand is :
    I have a tree on the left pane. i can drag and drop the nodes on the tree itself. (i already did that...no problem). I have Jlabels with imageicons (actually wrapper classes with labels and imageicons) on the right pane. i have to be able to drag these labels to the tree such that they form a node.
    I have one class the NodeSelection class which extends TransferHandler and implements Transferable. i was able to do DnD for the tree using this. I customized the importData method in this.I thought that i can just use the same class to create the transferhandler and transferable, and just use a different implementation for the importData method if the data being dragged is from the label.
    well, my thoughts and ideas were ok...but i can implement it...so they must be wrong ;-)
    Can u please suggest another way to do this. I have a deadline to meet and am stuck here :-( any suggestions or tips or hints would be very helpful and appreciated!!
    Thanks,
    Sri.

  • Drag and Drop different nodes within a JTree

    I have a JTree that represents a hierarchical object. Within the tree are different nodes representing different objects, each within a container,
    For Example:
    A
    -B container
    -- B NodeObject
    -- B NodeObject
    -C Container
    -- C NodeObject
    -- C NodeObject
    I have got the drag and drop working but as the gesture listener is on the actual JTree object it allows me to drag any object to any other place.
    What i want to be able to do is to force the drag and drop to allow only objects of type C to be put in the C container, etc and to reject any moves
    over other containers.
    As TreeNodes are not Components how do i force this behaviour?
    If i have to i can force the behaviour after the mouse has been released but I would prefer it if Swing would show the correct mouse over icons
    when I put an object over the wrong container.
    Thanks
    Dan Alford

    When you drag get the [x,y] mouse position and use the JTree method:
    getRowForLocation(x, y) for node you at the also for the parent node location of the child node.
    Once the childY is less than childParentY, you stop the drag.
    Hope that helps?

  • Display JTree Node as image  while Drag And Drop

    HI all.
    I have multiple 5 JTrees which involve drag and drop to each other . I would like to display the node(JCompenent) as image/cursor which a DnD operation .So that user could see what he drags .
    I tried out the example about ghost image .
    http://www.javaworld.com/javaworld/javatips/jw-javatip114.html
    This works fine ,but when i apply the same concepts to my application it doesnt work .
    Could any one suggest what could be problem.
    Cheers,Baiju

    I also need to drag my node on my scene during a "drag and drop" operation. But i can't find a solution.
    I've tried to use "startFullDrag()" and catch MouseDragEvent, but nothing ...
    Can anyone help me ?
    Thank !

Maybe you are looking for

  • Reading from a Dual-Layer Disc

    Hey y'all -- I am trying to rip some video files from the VIDEO_TS folder of a dual-layered DVD-Video (I have rights to the material) using OSEX, DVDBackup, Mac the Ripper, MPEG Streamclip, and just drag-and-drop. None of these solutions are allowing

  • How to make a value list depending on appraisal's validity dates

    Hi experts, I would like to know if anyone succeed to define a new (specific) Value Class (definition: HRHAP00_VALUE_TYPE) which make a list which is imported from a referential with dates (in a specific table)... I mean, we would like to conserve ap

  • Multiple table data displayed on 1 form

    Hi, i have search the forum for a solution but cannot find anything relevent. please help. I am trying to display fields from two tables on 1 form. I have currently an interactive report using a query of 2 tables and this works fine. When i click on

  • Can't activate MAXX replacement phone

    My RAZR MAXX was just replaced with a DROID MAXX (due to having no RAZR MAXX to send as a replacement).  The SIM card is a different size so I've tried activating it with both the card pre-installed in the phone as well as another card that was shipp

  • Photoshop cs5 manual

    Hi! Does anybody know, if a manual is available for PS CS5? There is a link under Adobe-support but it does not work (only for CS4 and lower). Thank U