Drag n Drop in JTree

Hi,
I am working on a prototype that requires drag and drop operation on a JTree. My applet requires to drag a item from the list into a JTree. I could achive this in the Frame and appletviewer, but when it comes to browser the drag and drop does not take place. I would appreciate if anyone could give a solution to this.
Thanks,

Does anyone of you able to work with drag n drop in Applet.
I am not able to achieve that,if someone has done that do help me.
Moreover we need to specify some security privileges if we need to run the drag n drop in an applet isnt it??
how to do that. in browser specialy. How to use the policy file?
thanking in advance

Similar Messages

  • 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 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 n Drop in JTree - missing the visual effect

    Hi,
    I already implemented the D&D on Jtree (from a JList)
    I've implemented DropTargetListener and it works
    I've the visual effect of the Dragged object on the mouse
    I have an extended DefaultTreeCellRenderer witch I use for other things.
    My problem is how do I get the visual effect of the active tree nodes when I drag it over them ?
    thanks,
    Allen

    Drag and drop is not something you can just turn on and off im afraid. You have 2 choices:
    1. if the dragging and dropping only occurs over a single component such as your tree, you could probably make a simplified on with mouse [motion?] listeners. On a mouse drag it could check which node was under the drag point and keep that in a variable. On a mouse release it could look to see if theres a node there and if so make it a child of that node.
    2. Implement full drag and drop, subclassing the JTree and having both a DragSource and DropTarget assigned to it. Theres a load of interfaces to implement but its not too difficult. Youll also need to make a DataFlavor class to contain the node values. Its the more involved solution but would probably be better in the long run.
    DS

  • Autoscrolling during drag n drop in jtree

    i have jTree where in the dragtarget n droptarget are both the same tree
    Tree contains large amount of data .... it is in a scrollpane
    when i drag a node to a drop target which is down under...i need the autoscrolling there
    any guesses

    1) make your class implement the java.awt.dnd.Autoscroll interface
    2) implement the methods required by Autoscroll:    /**
        *    Autoscroll Interface requires following 2 methods to be implemented:
        public static final Insets defaultScrollInsets = new Insets( 8, 8, 8, 8 );
        protected Insets scrollInsets = defaultScrollInsets;
        // Autoscrolling support
        public void setScrollInsets( Insets insets )
            this.scrollInsets = insets;
        public Insets getScrollInsets( )
            return scrollInsets;
        // Implementation of Autoscroll interface
        public Insets getAutoscrollInsets( )
            Rectangle r = getVisibleRect( );
            Dimension size = getSize( );
            Insets i = new Insets( r.y + scrollInsets.top, r.x + scrollInsets.left,
                size.height - r.y - r.height + scrollInsets.bottom,
                size.width - r.x - r.width + scrollInsets.right );
            return i;
        public void autoscroll( Point location )
            JScrollPane scroller =
                (JScrollPane)SwingUtilities.getAncestorOfClass( JScrollPane.class, this );
            if ( scroller != null )
                JScrollBar hBar = scroller.getHorizontalScrollBar( );
                JScrollBar vBar = scroller.getVerticalScrollBar( );
                Rectangle r = getVisibleRect( );
                if ( location.x <= r.x + scrollInsets.left )
                    // Need to scroll left
                    hBar.setValue( hBar.getValue( ) - hBar.getUnitIncrement( -1 ) );
                if ( location.y <= r.y + scrollInsets.top )
                    // Need to scroll up
                    vBar.setValue( vBar.getValue( ) - vBar.getUnitIncrement( -1 ) );
                if ( location.x >= r.x + r.width - scrollInsets.right )
                    // Need to scroll right
                    hBar.setValue( hBar.getValue( ) + hBar.getUnitIncrement( 1 ) );
                if ( location.y >= r.y + r.height - scrollInsets.bottom )
                    // Need to scroll down
                    vBar.setValue( vBar.getValue( ) + vBar.getUnitIncrement( 1 ) );
        }

  • Drag and Drop in JTree / Show line between Nodes as DropTarget

    Hello folks,
    I am using the posted DnDTree.
    My problem is to show a line between two nodes when I am drgging another node over them.
    The idea is to have the posibility to sort nodes in the same level.
    Has anybody an idea how to solve that?
    Thanks and best reards,
    Florian

    "My problem is to show a line between two nodes when I am drgging another node over them."
    Try this dragOver method:
    public void dragOver(DropTargetDragEvent dtde) {
    Point p = dtde.getLocation();
    int closestRow = getClosestRowForLocation(p.x, p.y);
    Graphics g = getGraphics();
    try {
    if (closestRow != -1) {
    DnDNode node =(DnDNode)getPathForRow(closestRow).getLastPathComponent();
    Rectangle r = getRowBounds(closestRow);
    g.setXORMode(getBackground());     
    if (p.y >= r.y && p.y <= r.y + r.height) {
    dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
    drawNewLine = false;
    drawNewRectangle = false;
    if (!node.getAllowsChildren() && ((r.x != x1 || r.y + r.height != y1) || rectangleDrawn)) {
    drawNewLine = true;
    parentNode = (DnDNode) node.getParent();
    index = parentNode.getIndex(node) + 1;                    
    } else if (node.getAllowsChildren()) {
    if ((isCollapsed(closestRow) || (isExpanded(closestRow) && node.getChildCount() == 0)) && (rectangleDrawn || (!lineDrawn && !rectangleDrawn)) && p.y > r.y + r.height - 5) {
    drawNewLine = true;
    parentNode = (DnDNode) node.getParent();
    index = parentNode.getIndex(node) + 1;
    } else if ((lineDrawn && p.y <= r.y + r.height - 5) || ((rectangleDrawn || (!lineDrawn && !rectangleDrawn)) && (r.x != x || r.y != y))) {
    drawNewRectangle = true;
    parentNode = node;
    index = 0;
    // Marks where the drop will occur
    if (drawNewLine || drawNewRectangle) {
    if (lineDrawn) {
    g.drawLine(x1, y1, x2, y2);
    lineDrawn = false;
    if (rectangleDrawn) {
    g.drawRect(x, y, w, h);
    rectangleDrawn = false;
    if (drawNewLine) {
    x1 = r.x;
    y1 = r.y + r.height;
    x2 = getWidth() - 5;
    y2 = r.y + r.height;
    g.drawLine(x1, y1, x2, y2);
    lineDrawn = true;
    if (drawNewRectangle) {
    x = r.x;
    y = r.y;
    w = getWidth() - r.x - 5;
    h = r.height - 1;     
    g.drawRect(x, y, w, h);
    rectangleDrawn = true;
    } else {
    dtde.rejectDrag();
    index = -1;
    if (lineDrawn) {
    g.drawLine(x1, y1, x2, y2);
    x1 = -1;
    y1 = -1;
    lineDrawn = false;
    if (rectangleDrawn) {
    g.drawRect(x, y, w, h);
    x = -1;
    y = -1;
    rectangleDrawn = false;
    } finally {
    g.dispose();
    Hope this works for you...
    Good luck
    /Tomas

  • Drag N Drop Icons

    I would like the users to hold the mouse on a component such as a label with an icon. Then i would like him to be able to drag the actual label around on the screen and register where he drops it and what label it is?
    A tutorial would be best if posible. It seems all the tuts here are about draging and dropping text, what about icons/ components.
    Thanks

    I suppose you saw this one already, then?
    http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html
    Or here's another set; dragging and dropping in JTree sounds like it's not text-oriented:
    http://www.javaolympus.com/J2SE/JFC/DragDrop/DragDrop.jsp
    These are just the first ones I found when I searched Google for the keywords "java drag and drop tutorial".

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

  • 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

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

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

Maybe you are looking for