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?

Similar Messages

  • How to drag and drop tab nodes between tab panes

    I'm working on example from this tutorial( Drag-and-Drop Feature in JavaFX Applications | JavaFX 2 Tutorials and Documentation ). Based on the tutorial I want to drag tabs between two tabs. So far I managed to create this code but I need some help in order to finish the code.
    Source
    tabPane = new TabPane();
    Tab tabA = new Tab();
       Label tabALabel = new Label("Main Component");
    tabPane.setOnDragDetected(new EventHandler<MouseEvent>()
                @Override
                public void handle(MouseEvent event)
                    /* drag was detected, start drag-and-drop gesture*/
                    System.out.println("onDragDetected");
                    /* allow any transfer mode */
                    Dragboard db = tabPane.startDragAndDrop(TransferMode.ANY);
                    /* put a string on dragboard */
                    ClipboardContent content = new ClipboardContent();
                    content.put(DataFormat.PLAIN_TEXT, tabPane);
                    db.setContent(content);
                    event.consume();
    What is the proper way to insert the content of the tab as object? Into the tutorial simple text is transferred. How I must modify this line content.put(DataFormat.PLAIN_TEXT, tabPane);?
    And what is the proper way to insert the tab after I drag the tab:
    Destination
    tabPane.setOnDragDropped(new EventHandler<DragEvent>()
                @Override
                public void handle(DragEvent event)
                    /* data dropped */
                    /* if there is a string data on dragboard, read it and use it */
                    Dragboard db = event.getDragboard();
                    boolean success = false;
                    if (db.hasString())
                        //tabPane.setText(db.getString());
                        Tab tabC = new Tab();
                        tabPane.getTabs().add(tabC);
                        success = true;
                    /* let the source know whether the string was successfully
                     * transferred and used */
                    event.setDropCompleted(success);
                    event.consume();
    I suppose that this transfer can be accomplished?
    Ref javafx 2 - How to drag and drop tab nodes between tab panes - Stack Overflow

    I would use a graphic (instead of text) for the Tabs and call setOnDragDetected on that graphic. That way you know which tab is being dragged. There's no nice way to put the Tab itself into the dragboard as it's not serializable (see https://javafx-jira.kenai.com/browse/RT-29082), so you probably just want to store the tab currently being dragged in a property.
    Here's a quick example; it just adds the tab to the end of the current tabs in the dropped pane. If you wanted to insert it into the nearest location to the actual drop you could probably iterate through the tabs and figure the coordinates of each tab's graphic, or something.
    import java.util.Random;
    import javafx.application.Application;
    import javafx.beans.property.ObjectProperty;
    import javafx.beans.property.SimpleObjectProperty;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.control.Tab;
    import javafx.scene.control.TabPane;
    import javafx.scene.input.ClipboardContent;
    import javafx.scene.input.DragEvent;
    import javafx.scene.input.Dragboard;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.input.TransferMode;
    import javafx.scene.layout.StackPane;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    public class DraggingTabPane extends Application {
      private static final String TAB_DRAG_KEY = "tab" ;
      private ObjectProperty<Tab> draggingTab ;
    @Override
      public void start(Stage primaryStage) {
      draggingTab = new SimpleObjectProperty<>();
      TabPane tabPane1 = createTabPane();
      TabPane tabPane2 = createTabPane();
      VBox root = new VBox(10);
      root.getChildren().addAll(tabPane1, tabPane2);
      final Random rng = new Random();
      for (int i=1; i<=8; i++) {
        final Tab tab = createTab("Tab "+i);
        final StackPane pane = new StackPane();
          int red = rng.nextInt(256);
          int green = rng.nextInt(256);
          int blue = rng.nextInt(256);
        String style = String.format("-fx-background-color: rgb(%d, %d, %d);", red, green, blue);
        pane.setStyle(style);
        final Label label = new Label("This is tab "+i);
        label.setStyle(String.format("-fx-text-fill: rgb(%d, %d, %d);", 256-red, 256-green, 256-blue));
        pane.getChildren().add(label);
        pane.setMinWidth(600);
        pane.setMinHeight(250);
        tab.setContent(pane);
        if (i<=4) {
          tabPane1.getTabs().add(tab);
        } else {
          tabPane2.getTabs().add(tab);
      primaryStage.setScene(new Scene(root, 600, 600));
      primaryStage.show();
      public static void main(String[] args) {
      launch(args);
      private TabPane createTabPane() {
        final TabPane tabPane = new TabPane();
        tabPane.setOnDragOver(new EventHandler<DragEvent>() {
          @Override
          public void handle(DragEvent event) {
            final Dragboard dragboard = event.getDragboard();
            if (dragboard.hasString()
                && TAB_DRAG_KEY.equals(dragboard.getString())
                && draggingTab.get() != null
                && draggingTab.get().getTabPane() != tabPane) {
              event.acceptTransferModes(TransferMode.MOVE);
              event.consume();
        tabPane.setOnDragDropped(new EventHandler<DragEvent>() {
          @Override
          public void handle(DragEvent event) {
            final Dragboard dragboard = event.getDragboard();
            if (dragboard.hasString()
                && TAB_DRAG_KEY.equals(dragboard.getString())
                && draggingTab.get() != null
                && draggingTab.get().getTabPane() != tabPane) {
              final Tab tab = draggingTab.get();
              tab.getTabPane().getTabs().remove(tab);
              tabPane.getTabs().add(tab);
              event.setDropCompleted(true);
              draggingTab.set(null);
              event.consume();
        return tabPane ;
      private Tab createTab(String text) {
        final Tab tab = new Tab();
        final Label label = new Label(text);
        tab.setGraphic(label);
        label.setOnDragDetected(new EventHandler<MouseEvent>() {
          @Override
          public void handle(MouseEvent event) {
            Dragboard dragboard = label.startDragAndDrop(TransferMode.MOVE);
            ClipboardContent clipboardContent = new ClipboardContent();
            clipboardContent.putString(TAB_DRAG_KEY);
            dragboard.setContent(clipboardContent);
            draggingTab.set(tab);
            event.consume();
        return tab ;

  • How drag and drop a node in a TreeView ?

    Hi,
    I want drag and drop a node in a treeview but i don't know how to get this result. I can drag a page item in a treeview or drag a node in a page item but not a node in another.
    Can you help me ?
    Regards,
    Damien Fontaine

    Your implementation of DoAddDragContent() is a little thin looking.
    If you look at the example in the SDK (BscDNDCustomDragSource.cpp) you might need to add at least:
        // we get the data object that represents the drag
        InterfacePtr<IPMDataObject> item(DNDController->AddDragItem(1));
        // no flavor flags
        PMFlavorFlags flavorFlags = 0;
        // we set the type (flavour) in the drag object
        item->PromiseFlavor(customFlavor, flavorFlags);
    Also, check that DoAddDragContent()  is actually being called.

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

  • Drag and drop a node in the line graph

    Hello Flex experts,
      I am using line graph for the monthly data. I want to drag a node , maybe the february node down. How can i achieve it? My code as follows does not work. Will highly appreciate your help as it is urgent requirement.
    <?xml version="1.0"?><!-- charts/BasicLine.mxml --><mx:Application 
    xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script><![CDATA[ 
    import mx.controls.Alert; 
    import mx.collections.ArrayCollection; 
    import mx.core.DragSource; 
    import mx.managers.DragManager; 
    import mx.events.*; 
    import mx.containers.Canvas;
    private  
    function dragExitHandler(event:DragEvent):void {Alert.show(
    " An event exit . ");}
    private  
    function dragOverHandler(event:DragEvent):void {Alert.show(
    " An event drag . ");}
    Bindable] 
    public var expenses:ArrayCollection = new ArrayCollection([{Month:
    "Jan", Profit:2000, Expenses:1500, Amount:450},{Month:
    "Feb", Profit:1000, Expenses:200, Amount:600},{Month:
    "Mar", Profit:1500, Expenses:500, Amount:300}]);
    ]]>
    </mx:Script>
    <mx:Panel title="Line Chart">
    <mx:LineChart id="myChart" dataProvider="
    {expenses}" showDataTips="
    true"dragEnabled="
    true"dragMoveEnabled="
    true"dropEnabled="
    true"dragOver="dragOverHandler(event);"
    dragDrop="dragExitHandler(event);"
    dragExit="dragExitHandler(event);"
    >
    <mx:horizontalAxis>
    <mx:CategoryAxis dataProvider="
    {expenses}" categoryField="
    Month" 
    />
    </mx:horizontalAxis>
    <mx:series>
    <mx:LineSeries yField="
    Profit" displayName="
    Profit" 
    />
    <mx:LineSeries yField="
    Expenses" displayName="
    Expenses" 
    />
    </mx:series>
    </mx:LineChart>
    <mx:Legend dataProvider="{myChart}"/>
    </mx:Panel> 
    Best regards!
    Sandip

    did you ever figure this out? I am trying to figure this out too, and it's not easy.

  • Dragging and dropping an item within horizontalList does not display correctly

    It appears that when I drag an item from a HorizontalList to another location within the same HorizonList, it does not display the images correctly. In my HorizontalList, I have an itemRenderer that shows the thumbnail image of the item.  I have about half a dozen items in the list and when I drag the sixth item and move to the beginning of the list, the display looks as if the first and the sixth element are switched, while in reality the resulting dataProvider array seems to have the right order, meaning the sixth element became the first element and the first element became the second element and so on. Has any one seen such a behavior and how do I rectify this? Thanks in advance. Cheers, Ramesh
    The HorizontalList def is
    <mx:HorizontalList id="myList" width="92%" height="100%" columnWidth="90" rowHeight="105" rollOverColor="#f26722"
                        itemRenderer="com.myListRenderer" labelField="name" dataProvider="{arr}" columnCount="10"
                        click="updateView(event)" dragEnabled="true" dropEnabled="true" dragMoveEnabled="true" >
    </mx:HorizontalList>
    The renderer code is
    <?xml version="1.0" encoding="utf-8"?>
    <mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" horizontalScrollPolicy="off" verticalScrollPolicy="off" horizontalAlign="center"
            verticalAlign="middle" width="90" height="90" verticalGap="0" creationComplete="init()" >
    <mx:Script>
        <![CDATA[
            private function init():void {
                imageFile.source = data.url;
                imageName.text = data.name;
        ]]>
    </mx:Script>
        <mx:Image id="imageFile" scaleContent="true" width="90" height="70" horizontalAlign="center" verticalAlign="middle"/>
        <mx:Label id="imageName" height="18" width="90" textAlign="left"/>
    </mx:VBox>

    Hi Alex,
    In your blogpost on itemRenderers, you discussed something relevant in a brief section on "Background color changes when data changes". However, I could not find any reference for use on dataChange event handler. Can you pelase point me to the right article?
    Implementing dataChange event instead of creationComplete did not solve my issue. I still had the issue. Thanks, Ramesh

  • Macbook drag and drop different that magic trackpad ?

    Dear friends,
    I have been using a Magic Trackpad with my 27" iMac  for a long time and have it configured so that a slight single finger tap then enables the dragging of the current window or selection.
    On my new rMBP I can achieve this only by clicking and keeping pressed and dragging (tiresome if I have to move long distances) or configure the three-finger drag I'm not used to.
    Is there anyway to have the rMBP (10.8.2) behave like the Magic Trackpad ?
    TIA

    I don't usually use tap to click (hate it, personally), but turning it on, I can't find a way to drag a file using just taps and drags.
    However, one thing that took me a while to figure out with the MBP is that you don't have to use the same finger you're dragging with to do the clicking. Despite the fact that the MBP's trackpad is multi-touch sensitive, and ordinarily using multiple fingers triggers a gesture of some kind, it seems to be smart enough that you can click with your thumb (as if there were a separate button) while dragging with your index finger, and this won't trigger a "pinch" gesture.
    Dunno if that will help you or not.

  • Drag and drop the xml schema?

    hi all
    i am creating a GUI. i am using splitpane to split my Frame. and my left split pane contains the XML schema in the form of a JTree. and i need to drag and drop the nodes of a JTree on to right split pane which sub divided in to some regions. i can able to open the xml file in to left split pane as a Jtree. but unable to drag and drop the Nodes in to rightsplit pane.
    any e book or sample code is greatly appriciated.
    thanks in advance.
    karthik

    Hi
    I am new to Oracle but not to VS. I have downloaded and installed the newest tools for Developer, having first tried the install for VS2003.net (which refused to install on my VS 2005.) I got the beta download and installed it, but my oracle explorer shows nothing. Any attempt to add a connection results in an error ORA-12560:TNS:protocol adaptor error. I had the full install of 10g r2 on my notebook, but removed it and opted for the XE version. I removed the Oracle_Home environment variable prior to installing XE. I am trying to connect to the HR database, and the account is unlocked. I saw a reference to the tnsfiles file, and that seems to be the problem, but I don't know what to do about it. Thanks in advance to anyone who can offer help.
    Bruce
    [email protected]

  • Dragging ande dropping into a frame?

    Hi all,
    I am new to Swing Programming and i have a problem in implementing the JTree.
    According my requirement i need to drag a child node of the Jtree and drop into a frame which is adjacent to the JTree pane.
    But i am struck at only dragging and dropping the child node inside the tree itself,
    Please help me by some links or tutorials or any help is greatly appreciated.
    Thanks In advance.....
    Looking forward for your reply.....
    Thanks again,
    karthik.

    now i can able to compile the source code.thanks for that but my actual problem is i am creating a GUI. i am using splitpane to split my Frame. and my left split pane contains the XML schema in the form of a JTree. and i need to drag and drop the nodes of a JTree on to right split pane which sub divided in to some regions. i can able to open the xml file in to left split pane as a Jtree. but unable to drag and drop the Nodes in to rightsplit pane.

  • 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 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 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 problem from wizard inside another drop

    I am using JDK 1.5.0_11 Swing.
    I am facing a Drag and Drop problem which is described below:
    A drag and drop operation invokes a wizard, from which another wizard is invoked. Within one of the panels of this 2nd wizard, I am trying to do a drag and drop from a JTextarea to a JTree node, but am NOT able to. I am not getting any exceptions. I have written a transfer handler for the JTree node to handle the text transfers from a JTextArea. When I try to do a drag and drop from a JTree node to another JTree node I'm getting the 'InvalidDNDOperation: drag and drop in progress' exception.
    When the 2nd wizard is invoked directly, I am able to do the drag and drop from JTextArea to a JTree node and also from a JTree node to another JTree node.
    I tried spawning a new thread for the 2nd wizard, but am still unable to initiate drag and drop.
    Should I be spawning a new thread for the 1st wizard?
    Message was edited by:
    sbandyop

    Please post Swing questions in the Swing forum: http://forum.java.sun.com/forum.jspa?forumID=57

  • Drag and Drop between 2 Panes

    Hi,
    I am using JDK 1.4.1 and am trying to implement Drag n Drop between a JTree and Labels with ImageIcons, both on different panes.
    I got the DnD working just on the tree. but i cant get to drag and drop the label 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?
    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.

Maybe you are looking for

  • Can't Sync Applications After HD Reformat/Reinstall

    A couple of days ago, I experienced some hard drive corruption and had to reformat my hard drive and reinstall the OS, via archive and install. I accidentally started up with a new user folder, but I fixed that by copying my old one over from the bac

  • How to reduce pdf file with out losing image quality

    I have a few ai files that I converted to PDF files and I need to reduce the size of them without losing quality of image.....I selected document then selected reduce size. This gave me a smaller file but my images were low quality.

  • Validity Date of BOM code.

    Hi, I need to know the tables or the functionality which can help to find the validity date of a BOM code. I am a BW consultant and have tried tables like MAST, STAS, STPO but could not find the 'valid to date'. Plz guide, Regards, Saurabh Diwakar

  • Reader 11 install issue

    i am unable to install reader 11.  error msg says portion of ap that needs updated is in use.....not that i am aware of!  i have tried to uninstall the current reader 8.3 without success.  op sys is windows 7 home version.  appreciate any assistance.

  • New Layer Being Created When Timeline Effect Added

    I am working on a Flash file in which I am adding a Timeline Effect (5 frame fade out). Recently, instead of the transition being applied to the layer, in the frame length specified, Flash adds another layer with the standard 30 frames and it deletes