TITLE:JTreeのノードをドラッグ&ドロップ
#navi(../)
*JTreeのノードをドラッグ&ドロップ [#uec75d42]
Posted by [[terai]] at 2007-02-26

#contents

**概要 [#gec25d47]
JTreeのノードをドラッグ&ドロップで移動します。[[Java Swing Hacks #26: DnD JTree>http://www.oreilly.co.jp/books/4873112788/]]のソースコードをベースにしています。

-&jnlp;
-&jar;
-&zip;

#screenshot

**サンプルコード [#le4b53da]
#code{{
public void dragOver(DropTargetDragEvent dtde) {
  DataFlavor[] f = dtde.getCurrentDataFlavors();
  boolean isDataFlavorSupported = f[0].getHumanPresentableName().equals(NAME);
  if(!isDataFlavorSupported) {
    //サポートされていないDataFlavorである(例えばデスクトップからファイルなど)
    rejectDrag(dtde);
    return;
  }
  // figure out which cell it's over, no drag to self
  Point pt = dtde.getLocation();
  TreePath path = getPathForLocation(pt.x, pt.y);
  if(path==null) {
    //ノード以外の場所である(例えばJTreeの余白など)
    rejectDrag(dtde);
    return;
  }
  Object droppedObject;
  try {
    droppedObject = dtde.getTransferable().getTransferData(localObjectFlavor);
  }catch(Exception ex) {
    rejectDrag(dtde);
    return;
  }
  MutableTreeNode droppedNode
    = (MutableTreeNode) droppedObject;
  DefaultMutableTreeNode targetNode
    = (DefaultMutableTreeNode) path.getLastPathComponent();
  DefaultMutableTreeNode parentNode
    = (DefaultMutableTreeNode) targetNode.getParent();
  while(parentNode!=null) {
    if(droppedNode.equals(parentNode)) {
      //親ノードを子ノードにドロップしようとしている
      rejectDrag(dtde);
      return;
    }
    parentNode = (DefaultMutableTreeNode)parentNode.getParent();
  }
  //dropTargetNode は、描画用(Rectangle2D、Line)のflag
  dropTargetNode = targetNode;
  dtde.acceptDrag(dtde.getDropAction());
  repaint();
}
private void rejectDrag(DropTargetDragEvent dtde) {
  dtde.rejectDrag();
  dropTargetNode = null; // dropTargetNode(flag)をnullにして
  repaint();             // Rectangle2D、Lineを消すためJTreeを再描画
}
}}

**解説 [#lc4f6171]
[[HACK #26: DnD JTree>http://www.oreilly.co.jp/books/4873112788/]]から以下の動作を変更しています。

- ルートノードのドラッグを禁止
- 自ノードから自ノードへのドラッグ&ドロップを禁止
-- ノードを自分と一つ上のノードとの間にドロップするとノードが消える
- 親ノードを子ノードにドロップすることを禁止
-- フォルダノードを自分自身にドロップするとフォルダノードが消えてしまう
- サポートされていないDataFlavorのドロップを禁止
-- エクスプローラなどからファイルをドロップすると、描画が乱れる

----
制限事項:兄弟ノードの末尾に直接ドラッグ&ドロップすることは出来ません。それらの親ノードにドロップすると兄弟ノードの一番最後に追加されます。

**参考リンク [#c25ab43d]
- [[HACK #26: DnD JTree>http://www.oreilly.co.jp/books/4873112788/]]
- [[Java Tip 114: Add ghosted drag images to your JTrees - Java World>http://www.javaworld.com/javaworld/javatips/jw-javatip114.html]]
- [[DnD (drag and drop)JTree code : Tree : Swing JFC : Java examples (example source code) Organized by topic>http://www.java2s.com/Code/Java/Swing-JFC/DnDdraganddropJTreecode.htm]]

**コメント [#of354fb4]
#comment