Google Tag Manager

2008/04/07

Drag and Drop the Tabs in JTabbedPane

Code

protected int getTargetTabIndex(Point glassPt) {
  int count = getTabCount();
  if (count == 0) {
    return -1;
  }

  Point tabPt = SwingUtilities.convertPoint(glassPane, glassPt, this);
  boolean isHorizontal = isTopBottomTabPlacement(getTabPlacement());
  for (int i = 0; i < count; ++i) {
    Rectangle r = getBoundsAt(i);

    // First half.
    if (isHorizontal) {
      r.width = r.width / 2 + 1;
    } else {
      r.height = r.height / 2 + 1;
    }
    if (r.contains(tabPt)) {
      return i;
    }

    // Second half.
    if (isHorizontal) {
      r.x += r.width;
    } else {
      r.y += r.height;
    }
    if (r.contains(tabPt)) {
      return i + 1;
    }
  }
  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);
}

References