2012-03-21 95 views
4

我已經在JTree中實現了拖放功能,並且工作正常,但是我覺得這有點令人困惑。在圖中,我將展示item4item5之間的放置位置可能會因您所在節點之間的距離而異。我猜這是因爲item4item5的行邊界在它們之間的中間相遇,並且取決於你在哪一邊,你實際上在不同的行中。JTree節點間的索引刪除

從用戶的角度來看,我認爲這並不自然。我會認爲,如果我跌到節點之上,就會在其上面出現下降。如果我跌到節點下面,則會在其下面出現下降。有沒有辦法配置這種行爲?

enter image description here

編輯:添加代碼來顯示如何獲得放置位置

DropLocation dropLoc = support.getDropLocation(); 
    Point dropPoint = dropLoc.getDropPoint(); 
    tree.getTree().getPathForLocation(dropPoint.x, dropPoint.y); 

注意supportTransferSupport對象

編輯2:我似乎通過檢查已經解決了這個問題如果下降點高於或低於節點的中點。然後我可以判斷這個下降是高於還是低於哪個節點。

+0

您能告訴我們選擇在哪裏放置節點的代碼嗎? – 2012-03-21 20:28:22

+0

我已經添加了該代碼。 – 2012-03-22 00:10:33

+0

爲了更好的幫助,請儘快發佈[SSCCE](http://sscce.org/) – 2012-03-22 04:21:45

回答

2

您已經理清了答案,但是由於我已經整理了代碼,所以仍然值得將它發佈。

 public void dragOver(DropTargetDragEvent dtde) 
     { 
      Point dropPoint = dtde.getLocation(); 
      TreePath path = tree.getPathForLocation(dropPoint.x, dropPoint.y); 
      Rectangle pathBounds = tree.getPathBounds(path); 
      Rectangle topHalf = new Rectangle(pathBounds.x, pathBounds.y, pathBounds.width, pathBounds.height/2); 
      if (topHalf.contains(dropPoint)) 
      { 
       System.out.println("top half"); 
      } 
      else 
      { 
       System.out.println("bottom half"); 
      } 
     }