• category: swing folder: DnDTabbedPane title: JTabbedPaneのタブをドラッグ&ドロップ tags: [JTabbedPane, DragAndDrop, GlassPane, DragGestureListener] author: aterai pubdate: 2004-09-27T11:54:33+09:00 description: JTabbedPaneのタブをDrag&Dropで移動します。 image: https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTLjYzYe0I/AAAAAAAAAXw/nr90t9LvfMI/s800/DnDTabbedPane.png hreflang:
       href: https://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html
       lang: en

概要

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

サンプルコード

protected int getTargetTabIndex(Point glassPt) {
  Point tabPt = SwingUtilities.convertPoint(glassPane, glassPt, this);
  boolean isTB = getTabPlacement() == JTabbedPane.TOP || getTabPlacement() == JTabbedPane.BOTTOM;
  Point d = isTB ? new Point(1, 0) : new Point(0, 1);
  for (int i = 0; i < getTabCount(); i++) {
    Rectangle r = getBoundsAt(i);
    r.translate(-r.width * d.x / 2, -r.height * d.y / 2);
    if (r.contains(tabPt)) {
      return i;
    }
  }
  Rectangle r = getBoundsAt(getTabCount() - 1);
  r.translate(r.width * d.x / 2, r.height * d.y / 2);
  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を使用する方法に変更しました。

参考リンク

コメント