TITLE:JTabbedPaneのタブをドラッグ&ドロップ
#navi(../)
*JTabbedPaneのタブをドラッグ&ドロップ [#ncb175e4]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2004-09-24~
更新日:&lastmod;

#contents

**概要 [#xb4483cd]
JTabbedPaneのタブをDrag&Dropで移動します。

#screenshot

**サンプルコード [#jf8c35ef]
#code{{
 private int getTargetTabIndex(Point pt) {
   for(int i=0;i<this.getTabCount();i++) {
     Rectangle rect = this.getBoundsAt(i);
     rect.setRect(rect.x-rect.width/2, rect.y, rect.width, rect.height);
     if(rect.contains(pt)) {
       return i;
     }
   }
   Rectangle rect = this.getBoundsAt(this.getTabCount()-1);
   rect.setRect(rect.x+rect.width/2, rect.y, rect.width+100, rect.height);
   if(rect.contains(pt)) {
     return this.getTabCount();
   }else{
     return -1;
   }
 }

 private void convertTab(int prev, int next) {
   if(next<0 || prev==next) {
     return;
   }
   Component cmp = this.getComponentAt(prev);
   String str = this.getTitleAt(prev);
   if(next==this.getTabCount()) {
     this.remove(prev);
     this.addTab(str, cmp);
     this.setSelectedIndex(this.getTabCount()-1);
   }else if(prev>next) {
     this.remove(prev);
     this.insertTab(str, null, cmp, null, next);
     this.setSelectedIndex(next);
   }else{
     this.remove(prev);
     this.insertTab(str, null, cmp, null, next-1);
     this.setSelectedIndex(next-1);
   }
 }
}}
-&jnlp;
-&jar;
-&zip;

**解説 [#d37fac64]
上記のサンプルでは、JTabbedPaneのタブをドラッグすると、マウスカーソルが変更されて、ドロップされる位置に青い線を描画します。

ドラッグ中、半透明のタブゴーストを表示するかどうかを切り替えることが出来ます。タブ領域以外にドロップしようとすると、カーソルが変化します。

%%MouseMotionListenerとMouseListenerをimplementsしたJTabbedPaneを作成しています。%% JTabbedPaneのタブが二段以上になる場合の検証はほとんどしていません。

**参考リンク [#za2e1c66]
-[[Java Swing Hacks #63 半透明のドラッグ&ドロップ>http://www.oreilly.co.jp/books/4873112788/toc.html]]

**コメント [#x7903657]
- ドラッグ中のタブゴーストを表示する機能を追加しました。 -- [[terai]] &new{2006-06-23 (金) 15:18:30};
- java.awt.dnd パッケージを使用する方法にソースを変更しました。 -- [[terai]] &new{2006-07-01 (土) 16:22:48};

#comment