• title: JTabbedPaneのタブをドラッグ&ドロップ tags: [JTabbedPane, DragAndDrop, GlassPane, DragGestureListener] author: aterai pubdate: 2004-09-27 description: JTabbedPaneのタブをDrag&Dropで移動します。 hreflang:
       href: http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html
       lang: en

概要

JTabbedPaneのタブをDrag&Dropで移動します。

サンプルコード

private int getTargetTabIndex(Point glassPt) {
  Point tabPt = SwingUtilities.convertPoint(glassPane, glassPt, DnDTabbedPane.this);
  boolean isTB = getTabPlacement() == JTabbedPane.TOP || getTabPlacement() == JTabbedPane.BOTTOM;
  for (int i = 0; i < getTabCount(); i++) {
    Rectangle r = getBoundsAt(i);
    if (isTB) r.setRect(r.x - r.width / 2, r.y, r.width, r.height);
    else      r.setRect(r.x, r.y-r.height / 2, r.width, r.height);
    if (r.contains(tabPt)) return i;
  }
  Rectangle r = getBoundsAt(getTabCount() - 1);
  if (isTB) r.setRect(r.x + r.width / 2, r.y, r.width, r.height);
  else      r.setRect(r.x, r.y + r.height / 2, r.width, r.height);
  return    r.contains(tabPt) ? getTabCount() : -1;
}

private void convertTab(int prev, int next) {
  if (next < 0 || prev == next) {
    return;
  }
  Component cmp = getComponentAt(prev);
  Component tab = getTabComponentAt(prev);
  String str    = getTitleAt(prev);
  Icon icon     = getIconAt(prev);
  String tip    = getToolTipTextAt(prev);
  boolean flg   = isEnabledAt(prev);
  int tgtindex  = prev > next ? next : next - 1;
  remove(prev);
  insertTab(str, icon, cmp, tip, tgtindex);
  setEnabledAt(tgtindex, flg);

  //When you drag'n'drop a disabled tab, it finishes enabled and selected.
  //pointed out by dlorde
  if (flg) setSelectedIndex(tgtindex);

  // I have a component in all tabs (jlabel with an X to close the tab)
  // and when i move a tab the component disappear.
  // pointed out by Daniel Dario Morales Salas
  setTabComponentAt(tgtindex, tab);
}
View in GitHub: Java, Kotlin

解説

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

ドラッグ中、半透明のタブゴーストを表示するかどうかを切り替えることが出来ます。タブ領域以外にドロップしようとすると、カーソルが変化します。JTabbedPaneのタブが二段以上になる場合の検証はほとんどしていません。

MouseMotionListenerMouseListenerではなく、DragGestureListenerDragSourceListenerDropTargetListenerを使用する方法に変更しました。

参考リンク

コメント