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

Similar Messages

  • 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

  • How can I allow a learner to review a created Drag and Drop Quiz to show the learner their incorrect/correct answers?

    Captivate 8: I have created an assessment with two multiple choice question slides and eight drag and drop question slides. After the learner views their score, I would like them to be able to review all of their answers to see where errors were made. Currently, the review quiz only shows their answers and the correct answers for Multiple choice question slides. Ideally, I would like a review of the drag and drop question slides where the incorrect choices are outlined in red or something to this effect. I appreciate any insight and suggestions!

    Sorry, D&D is not a normal question slide and I can only recommend logging a feature request. I would really like to be able to choose whether an interaction is reset or not, because this problem doesn't exist only for D&D but for all learning interactions as well.

  • 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 feature in start menu between right side and left side

    Hello , I think it is a good idea to allow the user to drag items and apps from the left side of start menu and drop them in the right side, and vice versa. Such feature make life easier than clicking right button and choose unpin or pin to start.

    If you want your idea/opinion heard, please use the Feedback app.
    Posting at the forums won't get their attention, I don't think.

  • I cannot drag and drop to the time line!!! This worked before.

    Hello All,
    The last time I used iMovie was about a month ago. I have successfully imported and edited many projects in the past year. I just imported footage from a Mini DV camcorder as I always have in the past. When I click on video to drag to the time line, as soon as I move the mouse pointer, the video thumbnail becomes ghosted and I do not see the thumbnail or green + symbol when dragging. I even moved the mouse pointer to the timeline anyway and released the mouse click and nothing happened. I even tried dragging image files and MOV files from the Finder to the iMovie interface and that would not work either.
    What is preventing me from dragging?
    Ralph Ocampo

    Also, after the video thumbnail is ghosted, if I click on the ghosted thumbnail the thumbnail image does not appear in the preview window. Instead, the preview window turns black.
    Also, if I double click the ghosted thumbnail I do not get the Clip info dialog. It's as if the clip no longer exists, but I can see it's ghosted thumbnail.
    Also, I showed my wife the problem and she just told me she was using iMovie 2 days ago with no problem.
    Ralph Ocampo

  • How do I drag and drop files in iTunes 12?  I don't see my other computers in the side bar only playlist?

    I upgraded to Itunes 12 and now cannot drag and drop my movies & music files between my shared computers?  The side bar option, which only appears under the Playlist tab does not show my other shared devices where I used to simply drag files over and drop them on them to transfer.  I have 2 IMACs and a macbook pro that i like to keep hard copies of my music and video libraries on.  Anyone know how I can get my shared computer to show up on the side bar so I can drag and drop like I've been doing for the last 5 years?

    Thank you Peter.  Mine is more about creating playlist on my iMac and then wanting to drop it it on to my macbook pro for tailgating and family events, instead of recreating.  That doesn't seem like something that should bother apple as I already have the music and I am not going to go purchase it again off iTunes if this is what they are thinking.  I think this is about limiting our ability to share music and movies.   

  • Can't Drag and Drop in Home Sharing

    I just enabled home sharing between my desktop mac and my macbook pro. Can see all music (from the desktop) and playlists, but cannot drag and drop individual songs or playlists between the two. Any advice on this?
    Also, if I import music library will it bring playlists too, or just songs?

    Have a look at the Home Sharing Section in this Link:
    iTunes: How to move your music to a new computer
    Also, See Here
    HOME SHARING
    Understanding
    http://support.apple.com/kb/HT3819
    How to
    http://support.apple.com/kb/HT2688
    Troubleshooting
    http://support.apple.com/kb/TS2972

  • Reordering photos in folders by drag and drop

    Hi, When reordering photos by attempting to drag and drop a stack of photos between two other stacks, instead of inserting the selected stack between the 2 stacks, my v2.3 insists on adding the stack to one of the existing stacks. If I drag and drop a single picture between stacks, things are fine. Also, dragging and dropping a stack between two single photos is okay. But not trying to reorder stacks. Any ideas? Thanks!

    Since in iPhoto folders do not hold photos but hold other folders or albums there is a good chance of confusion here - are you speaking of albums or events?
    In general you select photos  by clicking on one and depressing the command key and clicking on additional photos --  or probably easier selecting oen photo and creating an album and then dragging additional photos to that album - once you have what you want to send collected open the album and select all and e-mail them
    LN

  • Drag and Drop Attachment from Outlook to LABVIEW

    Hi,
    I try to write a very simple program, which manages files. With the path control of LABVIEW we fortunately can Drag and Drop files from e.g. explorer, whose path I can use after dropping. The problem is, that I would like to do this directly with files from an Outlook mail attachment. Drag the attachment and drop it onto my LABVIEW window and be able to handle this file (copy elsewhere and rename it, for example)... That is what I dream of.
    I searched the internet for a long time, but I didn't find a solution.
    Thanks a lot for your help,
    yours,
    Daniel

    Probably not as easily. Drag & Drop in Windows is a complicated thing with the Server and Client negotiating a format to transfer. The server can offer many formats and the client then selects the one it can handle. The LabVIEW path control only can handle physical paths. So if the server application offers a path as one of the formats and then when the application selects that format makes sure that the file is copied somewhere in the filesystem (temporary path) and sends that path to the client, the LabVIEW path control will work fine. If the server application insists into memory stream only formats, the LabVIEW path control can not deal with them in any way. Outlook being a Microsoft product most likely insists in OLE formats and then you get into trouble.
    You basically need to interface to the Win32 or OLE Drag and Drop API to get this working. And no it's not trivial at all, because Drag and Drop not only varies greatly between platforms but also between OS versions.
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

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

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

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

Maybe you are looking for

  • How do I contact apple with unknown charges to my account

    My account was charged almost $30.00 for apps that I did not purchase! How do I contact apple about these charges?

  • My iphone 4 is calling random numbers

    My iPhone 4 is dialling random numbers on its own. I looked down at my phone when i thought it was locked + it was dialling this random number and then stopped. The number appeared in my recent calls list and it is a completely random number; not fro

  • How can I figure out if I have a virus?

    I'm afraid that I may have caught a virus on my Macbook, because when I'm into safari things keep popping up. How can I determine whether or not i have a virus? Or is that even possible?

  • Vacation message breaks sieve filter

    Hi, Sun Java(tm) System Messaging Server 6.2-4.03 (built Sep 22 2005) libimta.so 6.2-4.03 (built 04:37:42, Sep 22 2005) SunOS mta1 5.10 Generic_118822-11 sun4u sparc SUNW,Sun-Fire-V240 User have created several sieve filters via UWC and they work ok.

  • How to create a stroked line that randomize each stroke color?

    Hi all, I am strating out designing in illustrator and I need help on how to created a stroked line, -----------, with each stroke (  -  )  a different colour, like, each stroke having a different randomized color which differs from the next one. Als