Dragging within a JTree

Hi,
     I have a JTree and I want to enable the possibility of dragging from one node to another, but I do not want the ability to drag and drop anything external.
I think my problem would be easier to explain in the context of a JTree showing the contents and sub-contents of a directory. I need this JTree to have the ability to drag a file from one sub-directory to another. I also need the ability to drag a certain Sub-Directory and all the files underneath to another location in the JTree. I however do not want dragging anything external like files or text from outside the JTree to in the JTree as they do not make sense in my case.
     What is the easiest way to do this? I was looking at [Default DnD Support|http://java.sun.com/docs/books/tutorial/uiswing/dnd/defaultsupport.html] and it seems to say that some support is in place, but I need to write some of the code? I did not understand what I needed to do. I have setDragEnabled(true) to true for the JTree.
I’d be grateful to someone who would guide me.
Thanks,
O.O.

Thanks fun_with_me for the links. (I had got the last link, but the first two are new to me.)
     While they provide good examples of what needs to be done, I am trying to understand what is the basic amount of code needed to get this to work. The examples out there seem to be from Java 1.3 or 1.4. I am wondering if there are better ways to do this in Java 5 or 6?
     As far as the Tutorial in [Default DnD Suppor|http://java.sun.com/docs/books/tutorial/uiswing/dnd/defaultsupport.html] I could not understand the last two paragraphs where they say that the JTree needs some custom code, and that code is fairly minimal.
I hope someone has some ideas
O.O.

Similar Messages

  • Can't click drag within widgets in Dashboard

    Not sure what caused it, but suddenly I can't click-drag WITHIN a dashboard widget. For example, if I click and hold the pulldown menu in the Dictionary to change to thesaurus, the pull-down menu won't activate. It only activates if I click and release to bring it up. And I can't select text within a text field. If I click and drag over a word to select it, the whole widget will move.
    Same issue as this unresolved thread-- http://discussions.apple.com/thread.jspa?messageID=11847234&#11847234
    It occurs even if I log out/in as a different user. Sure, there are workarounds, but I'd like to fix this behavior. Anyone got any ideas?

    I'm in the same boat - is there a solution to this?

  • Copy drag within a layer

    To copy an object you can use Alt + the move tool and drag.  This creates a new layer. I want to copy objects by dragging within a layer but can't remember the shortcut!  Anyone know?
    I know if you hit Alt + Shift + Arrow an object will copy within a layer....but you can't manipulate its position as fast as you can if you were using the move tool.
    L

    Select first, then Control-Alt and drag.
    -Noel

  • Container that can be dragged within a container? is it possible?

    hello guys,
    I'm wondering if there is a possibility to have a big container that contains smaller containers which can be dragged within that big container.
    if yes, plz give me an example

    [Internal Frame|http://java.sun.com/docs/books/tutorial/uiswing/components/internalframe.html]

  • 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?

  • 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

  • Perform drag&drop in Jtree without even selecting a node once?

    Hi All,
    Is it possible to perform drag and Drop action on tree nodes even when the Jtree is not active.
    That is, say a jtree is not active and i directly want to drag a node inside it without even selecting it once?
    Thanks alot in Advance.

    You should google for "jtree drag and drop". I remember seeing a very nice tutorial on codeproject.
    If your run into any specific issue let me know.

  • Enable drag support at JTree jdk1.4.1

    Hi,
    I have problems to activate the drag support with own TransferHandler at JTree. When I only activate with setDragEnabled(true) it works fine, but drags only the text from node. I'll drag my own class. So I create an TransferHandler myself. But when I activate this with setTransferHandler(new MyTransferhandler()) and MosueAdapter exportAsDrag() it doesn't work. The exportAsDrag doesn't invoke any drag behavior.
    A simple example like this below doesn't work too. But why ?
    TIA
    Dirk
    treecomponentType.setTransferHandler(new TransferHandler("text"));
    MouseListener ml = new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    JComponent c = (JComponent)e.getSource();
    TransferHandler th = c.getTransferHandler();
    th.exportAsDrag(c, e, TransferHandler.COPY);
    treecomponentType.addMouseListener(ml);

    I think the problem is the !GraphicsEnvironment.isHeadless() request in exportAsDrag. Ihis will cause the skip of dragging. But how to correct the problem ?

  • Dragged node in jTree

    hi all,
    I have a jTree which use class dnd, based in this link... http://forums.sun.com/thread.jspa?forumID=57&threadID=296255
    Well, I have one method sortJtree, and when node is dragged for other node I want call sortJtree. If anyone knows how do this.
    Thanks

    in this link I found solution...
    http://coding.derkeiler.com/Archive/Java/comp.lang.java.gui/2008-02/msg00086.html
    thanks Rogan Dawes

  • Drag & Drop from JTree (String) to JTextArea (Graphics2D)

    Hi everyone,
    I want to create a Drag & Drop from a JTree node to any location in a JTextArea. Upon dropping the node onto the JTextArea, I would want to draw a rectangle and the node name.
    I've created a custom transfer handler which allows the transferring of text from the tree node to the JTextArea.
    Any general ideas on how I can do that are wlecomed.

    I've managed to get hold of the JPanel via TransferHandler.TransferSupport.getComponent()
    the source seems a bit more tricky. I've tried this
    Transferable tr = support.getTransferable();
                   DataFlavor f = new DataFlavor();
                   f = new DataFlavor(MyTreeNode.class,"MyTreeNode");
                   try {
                        Object o = tr.getTransferData(f);...
    but the source does not provide a MyTreeNode instance, but something else (a String, I guess)
    how can I change this?

  • Restricting Drag Within An Area

    I would like place an small image within an area (canvas?)
    and restrict dragging to within that area.
    It is a user control to allow them to visually position an
    image on the display at an exact location.
    Then I would save the x and y position of where they dragged
    the item to
    I have been searching the forums for drag, but most of the
    posts are in reference to the data grid.
    Can any give me any tips or close examples that I might be
    able to search for?
    Thanks
    Mathias

    Hi Mathias,
    From what I understand,
    - Allow dragging in a Canvas and
    - If the user drags an image in that Canvas,
    - Another image cannot be dragged to the same place where
    the previous image exists and so on...
    If my above understanding is correct and assuming that you
    know how to allow dragging in a component:
    In the drag handlers of 'DragEvent.DRAG_ENTER' and
    'DragEvent.DRAG_OVER', you should check if the position of the drag
    overlaps with previously inserted image and if so call
    'DragManager.acceptDragDrop(null);' else use 'acceptDragDrop'
    Hope this helps.
    ~Chakree.

  • Suddenly can't click and drag within my playlists

    I can drag songs or podcasts to my playlist, but cannot organize them once they are in there. Also, previously I could drag them in a particular order, and achieve the desired result but that is no longer the case. Thanks for your consideration.

    Well, I don't see any mention of an updated Lion drivers on Wacom's site, but heres a link to the driver download page and a link to their online community.
    Drivers | Wacom Americas
    Wacom Community
    WTH.

  • JTree Drag & Drop question.  DragSourceDragEvent vs DropTargetDragEvent

    I'm implementing Drag and Drop within a JTree.
    I need to get the TreeNode as the user drags over it. This method works for a DropTargetDragEvent:
    private TreeNode getNodeForEvent(DropTargetDragEvent dtde)
                  Point p = dtde.getLocation();
                  DropTargetContext dsc = dtde.getDropTargetContext();
                  JTree tree = (JTree)dsc.getComponent();
                  TreePath path = tree.getClosestPathForLocation(p.x, p.y);
                  System.out.println("DropTargetDragEvent: Closet path for tree locaiton is " + path);
                  return (TreeNode)path.getLastPathComponent();
            } But this method for DragSourceDragEvent returns a node much farther down on the JTree than where the user is dragging.
    private TreeNode getNodeForEvent(DragSourceDragEvent dsde)
             Point p = dsde.getLocation();
             DragSourceContext dsc = dsde.getDragSourceContext();
             JTree tree = (JTree)dsc.getComponent();
             TreePath path = tree.getClosestPathForLocation(p.x, p.y);
             System.out.println("DragSourceDragEvent: Closet path for tree locaiton is " + path);
             return (TreeNode)path.getLastPathComponent();
       } Am I missing something? The first method I found on this site. The 2nd method I modified since I need the node based on a DragSourceDragEvent because that's where I can set a custom cursor based on the node type.
    Has anyone run into this before?
    Thanks

    I've figured out why this is happening but am not sure how to fix it.
    For DropTargetDragEvent getLocation() returns the cursors position within the component.
    For DragSouceDragEvent getLocation returns the cursors position on the screen.
    Sortof makes sense but I don't know how to get a position over a component from the position on the screen.

  • 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 move operation

    I have a piece of code which is doing a drag and drop on a JTRee.This code also needs to handle move and copy operations.THe move method does not work the way expected.When I do a drag operation the node gets dragged but is not removed from the parent although pls note that when all the node are removed under a parent and I click on the parent node the plus sign next to the parent disappears and also the nodes disappear. I am not sure what the problem is ..has anyone ever faced such a situation.
    If anybody had any idea as to how to get a move operation on a JTree then your guidance for the same will be highly appreciated.
    Thanks for your help

    Thanks for the reply.I am removing the node from the model.
    I am doing the drag and drop between 2 trees and that is when I have the above mentioned problem.
    But when I drag within the same tree everything works fine.
    Let me explain one thing here that I am using 2 different instance of the same class for the 2 trees is it something like only one of the tree is getting refrehsed and other one is not.If so then how do I ensure that both instance of the tree gets refreshed.Any clues ????

Maybe you are looking for

  • Creation of an ERP Sales Order or ERP Quotation from CRM Opportunity

    Hello Experts, The scenario is as follows: I have done the cross-system copy control of transaction types and item categories to enable ERP Quotation and ERP Sales Order creation from CRM Opportunity.  However, after saving the CRM Opportunity, when

  • CS5 posts "Error 6"

    In deleting a bunch of useless apps, I messed up CS5, which will not open. I get an "Error 6" prompt. What do I do"

  • Image in html signature doesn't appear

    I've tried this tutorial to put together an html signature including images. http://allforces.com/2006/04/14/css-signatures/ As you can see at Step 6, the image shows when the signature is selected. When I compose an email however, I always get a 'bl

  • 10g Forms can't run on windows 7

    Have developed forms in oracle 10g. And tried to running it on windows 7 64 bits. Using all browsers available to me. but yet the result is blank page. Any help please

  • Use WiFi cable

    I've read that there is the wall charge for Ipod nano USB and WiFi type. When i've bought my ipod, in the box, there was only USB cable, without Power adapter!!!!! On aplle store the WiFi power adpater can be used for ipod nano too! I try to connect