<p>How do I implement a draggable tab using Java Swing? Instead of the static JTabbedPane I would like to drag-and-drop a tab to different position to rearrange the tabs.</p>

<p><strong>EDIT</strong>: <a href="http://java.sun.com/docs/books/tutorial/uiswing/dnd/index.html" rel="noreferrer">The Java Tutorials - Drag and Drop and Data Transfer</a>.</p>

[{'answer_id': 60279, 'author': 'jodonnell', 'author_id': 4223, 'author_profile': 'https://Stackoverflow.com/users/4223', 'pm_score': 3, 'selected': False, 'text': '<p>Found this code out there on the <a href="http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html" rel="noreferrer">tubes</a>:</p>\n\n<pre><code>class DnDTabbedPane extends JTabbedPane {\n  private static final int LINEWIDTH = 3;\n  private static final String NAME = "test";\n  private final GhostGlassPane glassPane = new GhostGlassPane();\n  private final Rectangle2D lineRect   = new Rectangle2D.Double();\n  private final Color     lineColor  = new Color(0, 100, 255);\n  //private final DragSource dragSource  = new DragSource();\n  //private final DropTarget dropTarget;\n  private int dragTabIndex = -1;\n\n  public DnDTabbedPane() {\n    super();\n    final DragSourceListener dsl = new DragSourceListener() {\n      public void dragEnter(DragSourceDragEvent e) {\n        e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);\n      }\n      public void dragExit(DragSourceEvent e) {\n        e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);\n        lineRect.setRect(0,0,0,0);\n        glassPane.setPoint(new Point(-1000,-1000));\n        glassPane.repaint();\n      }\n      public void dragOver(DragSourceDragEvent e) {\n        //e.getLocation()\n        //This method returns a Point indicating the cursor location in screen coordinates at the moment\n        Point tabPt = e.getLocation();\n        SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);\n        Point glassPt = e.getLocation();\n        SwingUtilities.convertPointFromScreen(glassPt, glassPane);\n        int targetIdx = getTargetTabIndex(glassPt);\n        if(getTabAreaBound().contains(tabPt) &amp;&amp; targetIdx&gt;=0 &amp;&amp;\n           targetIdx!=dragTabIndex &amp;&amp; targetIdx!=dragTabIndex+1) {\n          e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);\n        }else{\n          e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);\n        }\n      }\n      public void dragDropEnd(DragSourceDropEvent e) {\n        lineRect.setRect(0,0,0,0);\n        dragTabIndex = -1;\n        if(hasGhost()) {\n          glassPane.setVisible(false);\n          glassPane.setImage(null);\n        }\n      }\n      public void dropActionChanged(DragSourceDragEvent e) {}\n    };\n    final Transferable t = new Transferable() {\n      private final DataFlavor FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType, NAME);\n      public Object getTransferData(DataFlavor flavor) {\n        return DnDTabbedPane.this;\n      }\n      public DataFlavor[] getTransferDataFlavors() {\n        DataFlavor[] f = new DataFlavor[1];\n        f[0] = this.FLAVOR;\n        return f;\n      }\n      public boolean isDataFlavorSupported(DataFlavor flavor) {\n        return flavor.getHumanPresentableName().equals(NAME);\n      }\n    };\n    final DragGestureListener dgl = new DragGestureListener() {\n      public void dragGestureRecognized(DragGestureEvent e) {\n        Point tabPt = e.getDragOrigin();\n        dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);\n        if(dragTabIndex&lt;0) return;\n        initGlassPane(e.getComponent(), e.getDragOrigin());\n        try{\n          e.startDrag(DragSource.DefaultMoveDrop, t, dsl);\n        }catch(InvalidDnDOperationException idoe) {\n          idoe.printStackTrace();\n        }\n      }\n    };\n    //dropTarget =\n    new DropTarget(glassPane, DnDConstants.ACTION_COPY_OR_MOVE, new CDropTargetListener(), true);\n    new DragSource().createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, dgl);\n  }\n\n  class CDropTargetListener implements DropTargetListener{\n    public void dragEnter(DropTargetDragEvent e) {\n      if(isDragAcceptable(e)) e.acceptDrag(e.getDropAction());\n      else e.rejectDrag();\n    }\n    public void dragExit(DropTargetEvent e) {}\n    public void dropActionChanged(DropTargetDragEvent e) {}\n    public void dragOver(final DropTargetDragEvent e) {\n      if(getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM) {\n        initTargetLeftRightLine(getTargetTabIndex(e.getLocation()));\n      }else{\n        initTargetTopBottomLine(getTargetTabIndex(e.getLocation()));\n      }\n      repaint();\n      if(hasGhost()) {\n        glassPane.setPoint(e.getLocation());\n        glassPane.repaint();\n      }\n    }\n\n    public void drop(DropTargetDropEvent e) {\n      if(isDropAcceptable(e)) {\n        convertTab(dragTabIndex, getTargetTabIndex(e.getLocation()));\n        e.dropComplete(true);\n      }else{\n        e.dropComplete(false);\n      }\n      repaint();\n    }\n    public boolean isDragAcceptable(DropTargetDragEvent e) {\n      Transferable t = e.getTransferable();\n      if(t==null) return false;\n      DataFlavor[] f = e.getCurrentDataFlavors();\n      if(t.isDataFlavorSupported(f[0]) &amp;&amp; dragTabIndex&gt;=0) {\n        return true;\n      }\n      return false;\n    }\n    public boolean isDropAcceptable(DropTargetDropEvent e) {\n      Transferable t = e.getTransferable();\n      if(t==null) return false;\n      DataFlavor[] f = t.getTransferDataFlavors();\n      if(t.isDataFlavorSupported(f[0]) &amp;&amp; dragTabIndex&gt;=0) {\n        return true;\n      }\n      return false;\n    }\n  }\n\n  private boolean hasGhost = true;\n  public void setPaintGhost(boolean flag) {\n    hasGhost = flag;\n  }\n  public boolean hasGhost() {\n    return hasGhost;\n  }\n  private int getTargetTabIndex(Point glassPt) {\n    Point tabPt = SwingUtilities.convertPoint(glassPane, glassPt, DnDTabbedPane.this);\n    boolean isTB = getTabPlacement()==JTabbedPane.TOP || getTabPlacement()==JTabbedPane.BOTTOM;\n    for(int i=0;i&lt;getTabCount();i++) {\n      Rectangle r = getBoundsAt(i);\n      if(isTB) r.setRect(r.x-r.width/2, r.y,  r.width, r.height);\n      else   r.setRect(r.x, r.y-r.height/2, r.width, r.height);\n      if(r.contains(tabPt)) return i;\n    }\n    Rectangle r = getBoundsAt(getTabCount()-1);\n    if(isTB) r.setRect(r.x+r.width/2, r.y,  r.width, r.height);\n    else   r.setRect(r.x, r.y+r.height/2, r.width, r.height);\n    return   r.contains(tabPt)?getTabCount():-1;\n  }\n  private void convertTab(int prev, int next) {\n    if(next&lt;0 || prev==next) {\n      //System.out.println("press="+prev+" next="+next);\n      return;\n    }\n    Component cmp = getComponentAt(prev);\n    String str = getTitleAt(prev);\n    if(next==getTabCount()) {\n      //System.out.println("last: press="+prev+" next="+next);\n      remove(prev);\n      addTab(str, cmp);\n      setSelectedIndex(getTabCount()-1);\n    }else if(prev&gt;next) {\n      //System.out.println("   &gt;: press="+prev+" next="+next);\n      remove(prev);\n      insertTab(str, null, cmp, null, next);\n      setSelectedIndex(next);\n    }else{\n      //System.out.println("   &lt;: press="+prev+" next="+next);\n      remove(prev);\n      insertTab(str, null, cmp, null, next-1);\n      setSelectedIndex(next-1);\n    }\n  }\n\n  private void initTargetLeftRightLine(int next) {\n    if(next&lt;0 || dragTabIndex==next || next-dragTabIndex==1) {\n      lineRect.setRect(0,0,0,0);\n    }else if(next==getTabCount()) {\n      Rectangle rect = getBoundsAt(getTabCount()-1);\n      lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);\n    }else if(next==0) {\n      Rectangle rect = getBoundsAt(0);\n      lineRect.setRect(-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);\n    }else{\n      Rectangle rect = getBoundsAt(next-1);\n      lineRect.setRect(rect.x+rect.width-LINEWIDTH/2,rect.y,LINEWIDTH,rect.height);\n    }\n  }\n  private void initTargetTopBottomLine(int next) {\n    if(next&lt;0 || dragTabIndex==next || next-dragTabIndex==1) {\n      lineRect.setRect(0,0,0,0);\n    }else if(next==getTabCount()) {\n      Rectangle rect = getBoundsAt(getTabCount()-1);\n      lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);\n    }else if(next==0) {\n      Rectangle rect = getBoundsAt(0);\n      lineRect.setRect(rect.x,-LINEWIDTH/2,rect.width,LINEWIDTH);\n    }else{\n      Rectangle rect = getBoundsAt(next-1);\n      lineRect.setRect(rect.x,rect.y+rect.height-LINEWIDTH/2,rect.width,LINEWIDTH);\n    }\n  }\n\n  private void initGlassPane(Component c, Point tabPt) {\n    //Point p = (Point) pt.clone();\n    getRootPane().setGlassPane(glassPane);\n    if(hasGhost()) {\n      Rectangle rect = getBoundsAt(dragTabIndex);\n      BufferedImage image = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB);\n      Graphics g = image.getGraphics();\n      c.paint(g);\n      image = image.getSubimage(rect.x,rect.y,rect.width,rect.height);\n      glassPane.setImage(image);\n    }\n    Point glassPt = SwingUtilities.convertPoint(c, tabPt, glassPane);\n    glassPane.setPoint(glassPt);\n    glassPane.setVisible(true);\n  }\n\n  private Rectangle getTabAreaBound() {\n    Rectangle lastTab  = getUI().getTabBounds(this, getTabCount()-1);\n    return new Rectangle(0,0,getWidth(),lastTab.y+lastTab.height);\n  }\n\n  public void paintComponent(Graphics g) {\n    super.paintComponent(g);\n    if(dragTabIndex&gt;=0) {\n      Graphics2D g2 = (Graphics2D)g;\n      g2.setPaint(lineColor);\n      g2.fill(lineRect);\n    }\n  }\n}\n\nclass GhostGlassPane extends JPanel {\n  private final AlphaComposite composite;\n  private Point location = new Point(0, 0);\n  private BufferedImage draggingGhost = null;\n  public GhostGlassPane() {\n    setOpaque(false);\n    composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);\n  }\n  public void setImage(BufferedImage draggingGhost) {\n    this.draggingGhost = draggingGhost;\n  }\n  public void setPoint(Point location) {\n    this.location = location;\n  }\n  public void paintComponent(Graphics g) {\n    if(draggingGhost == null) return;\n    Graphics2D g2 = (Graphics2D) g;\n    g2.setComposite(composite);\n    double xx = location.getX() - (draggingGhost.getWidth(this) /2d);\n    double yy = location.getY() - (draggingGhost.getHeight(this)/2d);\n    g2.drawImage(draggingGhost, (int)xx, (int)yy , null);\n  }\n}\n</code></pre>\n'}, {'answer_id': 60306, 'author': 'Tom Martin', 'author_id': 5303, 'author_profile': 'https://Stackoverflow.com/users/5303', 'pm_score': 5, 'selected': False, 'text': '<p>Curses! Beaten to the punch by a Google search.  Unfortunately it\'s true there is no easy way to create draggable tab panes (or any other components) in Swing.  So whilst the example above is complete this one I\'ve just written is a bit simpler. So it will hopefully demonstrate the more advanced techniques involved a bit clearer.  The steps are:</p>\n\n<ol>\n<li>Detect that a drag has occurred</li>\n<li>Draw the dragged tab to an offscreen buffer</li>\n<li>Track the mouse position whilst dragging occurs</li>\n<li>Draw the tab in the buffer on top of the component.</li>\n</ol>\n\n<p>The above example will give you what you want but if you want to really understand the techniques applied here it might be a better exercise to round off the edges of this example and add the extra features demonstrated above to it.</p>\n\n<p>Or maybe I\'m just disappointed because I spent time writing this solution when one already existed :p</p>\n\n<pre class="lang-java prettyprint-override"><code>import java.awt.Component;\nimport java.awt.Graphics;\nimport java.awt.Image;\nimport java.awt.Point;\nimport java.awt.Rectangle;\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.MouseMotionAdapter;\nimport java.awt.image.BufferedImage;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JTabbedPane;\n\n\npublic class DraggableTabbedPane extends JTabbedPane {\n\n  private boolean dragging = false;\n  private Image tabImage = null;\n  private Point currentMouseLocation = null;\n  private int draggedTabIndex = 0;\n\n  public DraggableTabbedPane() {\n    super();\n    addMouseMotionListener(new MouseMotionAdapter() {\n      public void mouseDragged(MouseEvent e) {\n\n        if(!dragging) {\n          // Gets the tab index based on the mouse position\n          int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), e.getY());\n\n          if(tabNumber &gt;= 0) {\n            draggedTabIndex = tabNumber;\n            Rectangle bounds = getUI().getTabBounds(DraggableTabbedPane.this, tabNumber);\n\n\n            // Paint the tabbed pane to a buffer\n            Image totalImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);\n            Graphics totalGraphics = totalImage.getGraphics();\n            totalGraphics.setClip(bounds);\n            // Don\'t be double buffered when painting to a static image.\n            setDoubleBuffered(false);\n            paintComponent(totalGraphics);\n\n            // Paint just the dragged tab to the buffer\n            tabImage = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB);\n            Graphics graphics = tabImage.getGraphics();\n            graphics.drawImage(totalImage, 0, 0, bounds.width, bounds.height, bounds.x, bounds.y, bounds.x + bounds.width, bounds.y+bounds.height, DraggableTabbedPane.this);\n\n            dragging = true;\n            repaint();\n          }\n        } else {\n          currentMouseLocation = e.getPoint();\n\n          // Need to repaint\n          repaint();\n        }\n\n        super.mouseDragged(e);\n      }\n    });\n\n    addMouseListener(new MouseAdapter() {\n      public void mouseReleased(MouseEvent e) {\n\n        if(dragging) {\n          int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), 10);\n\n          if(tabNumber &gt;= 0) {\n            Component comp = getComponentAt(draggedTabIndex);\n            String title = getTitleAt(draggedTabIndex);\n            removeTabAt(draggedTabIndex);\n            insertTab(title, null, comp, null, tabNumber);\n          }\n        }\n\n        dragging = false;\n        tabImage = null;\n      }\n    });\n  }\n\n  protected void paintComponent(Graphics g) {\n    super.paintComponent(g);\n\n    // Are we dragging?\n    if(dragging &amp;&amp; currentMouseLocation != null &amp;&amp; tabImage != null) {\n      // Draw the dragged tab\n      g.drawImage(tabImage, currentMouseLocation.x, currentMouseLocation.y, this);\n    }\n  }\n\n  public static void main(String[] args) {\n    JFrame test = new JFrame("Tab test");\n    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n    test.setSize(400, 400);\n\n    DraggableTabbedPane tabs = new DraggableTabbedPane();\n    tabs.addTab("One", new JButton("One"));\n    tabs.addTab("Two", new JButton("Two"));\n    tabs.addTab("Three", new JButton("Three"));\n    tabs.addTab("Four", new JButton("Four"));\n\n    test.add(tabs);\n    test.setVisible(true);\n  }\n}\n</code></pre>\n'}, {'answer_id': 61982, 'author': 'Eugene Yokota', 'author_id': 3827, 'author_profile': 'https://Stackoverflow.com/users/3827', 'pm_score': 5, 'selected': True, 'text': '<p>I liked <a href="http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html" rel="nofollow noreferrer">Terai Atsuhiro san\'s DnDTabbedPane</a>, but I wanted more from it. The original Terai implementation transfered tabs within the TabbedPane, but it would be nicer if I could drag from one TabbedPane to another.</p>\n\n<p>Inspired by @<a href="https://stackoverflow.com/questions/60269/how-to-implement-draggable-tab-using-java-swing#60306">Tom</a>\'s effort, I decided to modify the code myself.\nThere are some details I added. For example, the ghost tab now slides along the tabbed pane instead of moving together with the mouse.</p>\n\n<p><code>setAcceptor(TabAcceptor a_acceptor)</code> should let the consumer code decide whether to let one tab transfer from one tabbed pane to another. The default acceptor always returns <code>true</code>.</p>\n\n<pre><code>/** Modified DnDTabbedPane.java\n * http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html\n * originally written by Terai Atsuhiro.\n * so that tabs can be transfered from one pane to another.\n * eed3si9n.\n */\n\nimport java.awt.*;\nimport java.awt.datatransfer.*;\nimport java.awt.dnd.*;\nimport java.awt.geom.*;\nimport java.awt.image.*;\nimport javax.swing.*;\n\npublic class DnDTabbedPane extends JTabbedPane {\n    public static final long serialVersionUID = 1L;\n    private static final int LINEWIDTH = 3;\n    private static final String NAME = "TabTransferData";\n    private final DataFlavor FLAVOR = new DataFlavor(\n            DataFlavor.javaJVMLocalObjectMimeType, NAME);\n    private static GhostGlassPane s_glassPane = new GhostGlassPane();\n\n    private boolean m_isDrawRect = false;\n    private final Rectangle2D m_lineRect = new Rectangle2D.Double();\n\n    private final Color m_lineColor = new Color(0, 100, 255);\n    private TabAcceptor m_acceptor = null;\n\n    public DnDTabbedPane() {\n        super();\n        final DragSourceListener dsl = new DragSourceListener() {\n            public void dragEnter(DragSourceDragEvent e) {\n                e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);\n            }\n\n            public void dragExit(DragSourceEvent e) {\n                e.getDragSourceContext()\n                        .setCursor(DragSource.DefaultMoveNoDrop);\n                m_lineRect.setRect(0, 0, 0, 0);\n                m_isDrawRect = false;\n                s_glassPane.setPoint(new Point(-1000, -1000));\n                s_glassPane.repaint();\n            }\n\n            public void dragOver(DragSourceDragEvent e) {\n                //e.getLocation()\n                //This method returns a Point indicating the cursor location in screen coordinates at the moment\n\n                TabTransferData data = getTabTransferData(e);\n                if (data == null) {\n                    e.getDragSourceContext().setCursor(\n                            DragSource.DefaultMoveNoDrop);\n                    return;\n                } // if\n\n                /*\n                Point tabPt = e.getLocation();\n                SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);\n                if (DnDTabbedPane.this.contains(tabPt)) {\n                    int targetIdx = getTargetTabIndex(tabPt);\n                    int sourceIndex = data.getTabIndex();\n                    if (getTabAreaBound().contains(tabPt)\n                            &amp;&amp; (targetIdx &gt;= 0)\n                            &amp;&amp; (targetIdx != sourceIndex)\n                            &amp;&amp; (targetIdx != sourceIndex + 1)) {\n                        e.getDragSourceContext().setCursor(\n                                DragSource.DefaultMoveDrop);\n\n                        return;\n                    } // if\n\n                    e.getDragSourceContext().setCursor(\n                            DragSource.DefaultMoveNoDrop);\n                    return;\n                } // if\n                */\n\n                e.getDragSourceContext().setCursor(\n                        DragSource.DefaultMoveDrop);\n            }\n\n            public void dragDropEnd(DragSourceDropEvent e) {\n                m_isDrawRect = false;\n                m_lineRect.setRect(0, 0, 0, 0);\n                // m_dragTabIndex = -1;\n\n                if (hasGhost()) {\n                    s_glassPane.setVisible(false);\n                    s_glassPane.setImage(null);\n                }\n            }\n\n            public void dropActionChanged(DragSourceDragEvent e) {\n            }\n        };\n\n        final DragGestureListener dgl = new DragGestureListener() {\n            public void dragGestureRecognized(DragGestureEvent e) {\n                // System.out.println("dragGestureRecognized");\n\n                Point tabPt = e.getDragOrigin();\n                int dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);\n                if (dragTabIndex &lt; 0) {\n                    return;\n                } // if\n\n                initGlassPane(e.getComponent(), e.getDragOrigin(), dragTabIndex);\n                try {\n                    e.startDrag(DragSource.DefaultMoveDrop, \n                            new TabTransferable(DnDTabbedPane.this, dragTabIndex), dsl);\n                } catch (InvalidDnDOperationException idoe) {\n                    idoe.printStackTrace();\n                }\n            }\n        };\n\n        //dropTarget =\n        new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE,\n                new CDropTargetListener(), true);\n        new DragSource().createDefaultDragGestureRecognizer(this,\n                DnDConstants.ACTION_COPY_OR_MOVE, dgl);\n        m_acceptor = new TabAcceptor() {\n            public boolean isDropAcceptable(DnDTabbedPane a_component, int a_index) {\n                return true;\n            }\n        };\n    }\n\n    public TabAcceptor getAcceptor() {\n        return m_acceptor;\n    }\n\n    public void setAcceptor(TabAcceptor a_value) {\n        m_acceptor = a_value;\n    }\n\n    private TabTransferData getTabTransferData(DropTargetDropEvent a_event) {       \n        try {\n            TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR);             \n            return data;\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n\n        return null;\n    }\n\n    private TabTransferData getTabTransferData(DropTargetDragEvent a_event) {\n        try {\n            TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR);             \n            return data;\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n\n        return null;\n    }\n\n    private TabTransferData getTabTransferData(DragSourceDragEvent a_event) {\n        try {\n            TabTransferData data = (TabTransferData) a_event.getDragSourceContext()\n                .getTransferable().getTransferData(FLAVOR);             \n            return data;\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n\n        return null;        \n    }\n\n    class TabTransferable implements Transferable {\n        private TabTransferData m_data = null;\n\n        public TabTransferable(DnDTabbedPane a_tabbedPane, int a_tabIndex) {\n            m_data = new TabTransferData(DnDTabbedPane.this, a_tabIndex);\n        }\n\n        public Object getTransferData(DataFlavor flavor) {\n            return m_data;\n            // return DnDTabbedPane.this;\n        }\n\n        public DataFlavor[] getTransferDataFlavors() {\n            DataFlavor[] f = new DataFlavor[1];\n            f[0] = FLAVOR;\n            return f;\n        }\n\n        public boolean isDataFlavorSupported(DataFlavor flavor) {\n            return flavor.getHumanPresentableName().equals(NAME);\n        }       \n    }\n\n    class TabTransferData {\n        private DnDTabbedPane m_tabbedPane = null;\n        private int m_tabIndex = -1;\n\n        public TabTransferData() {\n        }\n\n        public TabTransferData(DnDTabbedPane a_tabbedPane, int a_tabIndex) {\n            m_tabbedPane = a_tabbedPane;\n            m_tabIndex = a_tabIndex;\n        }\n\n        public DnDTabbedPane getTabbedPane() {\n            return m_tabbedPane;\n        }\n\n        public void setTabbedPane(DnDTabbedPane pane) {\n            m_tabbedPane = pane;\n        }\n\n        public int getTabIndex() {\n            return m_tabIndex;\n        }\n\n        public void setTabIndex(int index) {\n            m_tabIndex = index;\n        }\n    }\n\n    private Point buildGhostLocation(Point a_location) {\n        Point retval = new Point(a_location);\n\n        switch (getTabPlacement()) {\n            case JTabbedPane.TOP: {\n                retval.y = 1;\n                retval.x -= s_glassPane.getGhostWidth() / 2;\n            } break;\n\n            case JTabbedPane.BOTTOM: {\n                retval.y = getHeight() - 1 - s_glassPane.getGhostHeight();\n                retval.x -= s_glassPane.getGhostWidth() / 2;\n            } break;\n\n            case JTabbedPane.LEFT: {\n                retval.x = 1;\n                retval.y -= s_glassPane.getGhostHeight() / 2;\n            } break;\n\n            case JTabbedPane.RIGHT: {\n                retval.x = getWidth() - 1 - s_glassPane.getGhostWidth();\n                retval.y -= s_glassPane.getGhostHeight() / 2;\n            } break;\n        } // switch\n\n        retval = SwingUtilities.convertPoint(DnDTabbedPane.this,\n                retval, s_glassPane);\n        return retval;\n    }\n\n    class CDropTargetListener implements DropTargetListener {\n        public void dragEnter(DropTargetDragEvent e) {\n            // System.out.println("DropTarget.dragEnter: " + DnDTabbedPane.this);\n\n            if (isDragAcceptable(e)) {\n                e.acceptDrag(e.getDropAction());\n            } else {\n                e.rejectDrag();\n            } // if\n        }\n\n        public void dragExit(DropTargetEvent e) {\n            // System.out.println("DropTarget.dragExit: " + DnDTabbedPane.this);\n            m_isDrawRect = false;\n        }\n\n        public void dropActionChanged(DropTargetDragEvent e) {\n        }\n\n        public void dragOver(final DropTargetDragEvent e) {\n            TabTransferData data = getTabTransferData(e);\n\n            if (getTabPlacement() == JTabbedPane.TOP\n                    || getTabPlacement() == JTabbedPane.BOTTOM) {\n                initTargetLeftRightLine(getTargetTabIndex(e.getLocation()), data);\n            } else {\n                initTargetTopBottomLine(getTargetTabIndex(e.getLocation()), data);\n            } // if-else\n\n            repaint();\n            if (hasGhost()) {\n                s_glassPane.setPoint(buildGhostLocation(e.getLocation()));\n                s_glassPane.repaint();\n            }\n        }\n\n        public void drop(DropTargetDropEvent a_event) {\n            // System.out.println("DropTarget.drop: " + DnDTabbedPane.this);\n\n            if (isDropAcceptable(a_event)) {\n                convertTab(getTabTransferData(a_event),\n                    getTargetTabIndex(a_event.getLocation()));\n                a_event.dropComplete(true);\n            } else {\n                a_event.dropComplete(false);\n            } // if-else\n\n            m_isDrawRect = false;\n            repaint();\n        }\n\n        public boolean isDragAcceptable(DropTargetDragEvent e) {\n            Transferable t = e.getTransferable();\n            if (t == null) {\n                return false;\n            } // if\n\n            DataFlavor[] flavor = e.getCurrentDataFlavors();\n            if (!t.isDataFlavorSupported(flavor[0])) {\n                return false;\n            } // if\n\n            TabTransferData data = getTabTransferData(e);\n\n            if (DnDTabbedPane.this == data.getTabbedPane()\n                    &amp;&amp; data.getTabIndex() &gt;= 0) {\n                return true;\n            } // if\n\n            if (DnDTabbedPane.this != data.getTabbedPane()) {\n                if (m_acceptor != null) {\n                    return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());\n                } // if\n            } // if\n\n            return false;\n        }\n\n        public boolean isDropAcceptable(DropTargetDropEvent e) {\n            Transferable t = e.getTransferable();\n            if (t == null) {\n                return false;\n            } // if\n\n            DataFlavor[] flavor = e.getCurrentDataFlavors();\n            if (!t.isDataFlavorSupported(flavor[0])) {\n                return false;\n            } // if\n\n            TabTransferData data = getTabTransferData(e);\n\n            if (DnDTabbedPane.this == data.getTabbedPane()\n                    &amp;&amp; data.getTabIndex() &gt;= 0) {\n                return true;\n            } // if\n\n            if (DnDTabbedPane.this != data.getTabbedPane()) {\n                if (m_acceptor != null) {\n                    return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());\n                } // if\n            } // if\n\n            return false;\n        }\n    }\n\n    private boolean m_hasGhost = true;\n\n    public void setPaintGhost(boolean flag) {\n        m_hasGhost = flag;\n    }\n\n    public boolean hasGhost() {\n        return m_hasGhost;\n    }\n\n    /**\n     * returns potential index for drop.\n     * @param a_point point given in the drop site component\'s coordinate\n     * @return returns potential index for drop.\n     */\n    private int getTargetTabIndex(Point a_point) {\n        boolean isTopOrBottom = getTabPlacement() == JTabbedPane.TOP\n                || getTabPlacement() == JTabbedPane.BOTTOM;\n\n        // if the pane is empty, the target index is always zero.\n        if (getTabCount() == 0) {\n            return 0;\n        } // if\n\n        for (int i = 0; i &lt; getTabCount(); i++) {\n            Rectangle r = getBoundsAt(i);\n            if (isTopOrBottom) {\n                r.setRect(r.x - r.width / 2, r.y, r.width, r.height);\n            } else {\n                r.setRect(r.x, r.y - r.height / 2, r.width, r.height);\n            } // if-else\n\n            if (r.contains(a_point)) {\n                return i;\n            } // if\n        } // for\n\n        Rectangle r = getBoundsAt(getTabCount() - 1);\n        if (isTopOrBottom) {\n            int x = r.x + r.width / 2;\n            r.setRect(x, r.y, getWidth() - x, r.height);\n        } else {\n            int y = r.y + r.height / 2;\n            r.setRect(r.x, y, r.width, getHeight() - y);\n        } // if-else\n\n        return r.contains(a_point) ? getTabCount() : -1;\n    }\n\n    private void convertTab(TabTransferData a_data, int a_targetIndex) {\n        DnDTabbedPane source = a_data.getTabbedPane();\n        int sourceIndex = a_data.getTabIndex();\n        if (sourceIndex &lt; 0) {\n            return;\n        } // if\n\n        Component cmp = source.getComponentAt(sourceIndex);\n        String str = source.getTitleAt(sourceIndex);\n        if (this != source) {\n            source.remove(sourceIndex);\n\n            if (a_targetIndex == getTabCount()) {\n                addTab(str, cmp);\n            } else {\n                if (a_targetIndex &lt; 0) {\n                    a_targetIndex = 0;\n                } // if\n\n                insertTab(str, null, cmp, null, a_targetIndex);\n\n            } // if\n\n            setSelectedComponent(cmp);\n            // System.out.println("press="+sourceIndex+" next="+a_targetIndex);\n            return;\n        } // if\n\n        if (a_targetIndex &lt; 0 || sourceIndex == a_targetIndex) {\n            //System.out.println("press="+prev+" next="+next);\n            return;\n        } // if\n\n        if (a_targetIndex == getTabCount()) {\n            //System.out.println("last: press="+prev+" next="+next);\n            source.remove(sourceIndex);\n            addTab(str, cmp);\n            setSelectedIndex(getTabCount() - 1);\n        } else if (sourceIndex &gt; a_targetIndex) {\n            //System.out.println("   &gt;: press="+prev+" next="+next);\n            source.remove(sourceIndex);\n            insertTab(str, null, cmp, null, a_targetIndex);\n            setSelectedIndex(a_targetIndex);\n        } else {\n            //System.out.println("   &lt;: press="+prev+" next="+next);\n            source.remove(sourceIndex);\n            insertTab(str, null, cmp, null, a_targetIndex - 1);\n            setSelectedIndex(a_targetIndex - 1);\n        }\n    }\n\n    private void initTargetLeftRightLine(int next, TabTransferData a_data) {        \n        if (next &lt; 0) {\n            m_lineRect.setRect(0, 0, 0, 0);\n            m_isDrawRect = false;\n            return;\n        } // if\n\n        if ((a_data.getTabbedPane() == this)\n                &amp;&amp; (a_data.getTabIndex() == next\n                || next - a_data.getTabIndex() == 1)) {\n            m_lineRect.setRect(0, 0, 0, 0);\n            m_isDrawRect = false;\n        } else if (getTabCount() == 0) {\n            m_lineRect.setRect(0, 0, 0, 0);\n            m_isDrawRect = false;\n            return;\n        } else if (next == 0) {\n            Rectangle rect = getBoundsAt(0);\n            m_lineRect.setRect(-LINEWIDTH / 2, rect.y, LINEWIDTH, rect.height);\n            m_isDrawRect = true;\n        } else if (next == getTabCount()) {\n            Rectangle rect = getBoundsAt(getTabCount() - 1);\n            m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,\n                    LINEWIDTH, rect.height);\n            m_isDrawRect = true;\n        } else {\n            Rectangle rect = getBoundsAt(next - 1);\n            m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,\n                    LINEWIDTH, rect.height);\n            m_isDrawRect = true;\n        }\n    }\n\n    private void initTargetTopBottomLine(int next, TabTransferData a_data) {\n        if (next &lt; 0) {\n            m_lineRect.setRect(0, 0, 0, 0);\n            m_isDrawRect = false;\n            return;\n        } // if\n\n        if ((a_data.getTabbedPane() == this)\n                &amp;&amp; (a_data.getTabIndex() == next\n                || next - a_data.getTabIndex() == 1)) {\n            m_lineRect.setRect(0, 0, 0, 0);\n            m_isDrawRect = false;\n        } else if (getTabCount() == 0) {\n            m_lineRect.setRect(0, 0, 0, 0);\n            m_isDrawRect = false;\n            return;\n        } else if (next == getTabCount()) {\n            Rectangle rect = getBoundsAt(getTabCount() - 1);\n            m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,\n                    rect.width, LINEWIDTH);\n            m_isDrawRect = true;\n        } else if (next == 0) {\n            Rectangle rect = getBoundsAt(0);\n            m_lineRect.setRect(rect.x, -LINEWIDTH / 2, rect.width, LINEWIDTH);\n            m_isDrawRect = true;\n        } else {\n            Rectangle rect = getBoundsAt(next - 1);\n            m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,\n                    rect.width, LINEWIDTH);\n            m_isDrawRect = true;\n        }\n    }\n\n    private void initGlassPane(Component c, Point tabPt, int a_tabIndex) {\n        //Point p = (Point) pt.clone();\n        getRootPane().setGlassPane(s_glassPane);\n        if (hasGhost()) {\n            Rectangle rect = getBoundsAt(a_tabIndex);\n            BufferedImage image = new BufferedImage(c.getWidth(),\n                    c.getHeight(), BufferedImage.TYPE_INT_ARGB);\n            Graphics g = image.getGraphics();\n            c.paint(g);\n            image = image.getSubimage(rect.x, rect.y, rect.width, rect.height);\n            s_glassPane.setImage(image);            \n        } // if\n\n        s_glassPane.setPoint(buildGhostLocation(tabPt));\n        s_glassPane.setVisible(true);\n    }\n\n    private Rectangle getTabAreaBound() {\n        Rectangle lastTab = getUI().getTabBounds(this, getTabCount() - 1);\n        return new Rectangle(0, 0, getWidth(), lastTab.y + lastTab.height);\n    }\n\n    public void paintComponent(Graphics g) {\n        super.paintComponent(g);\n\n        if (m_isDrawRect) {\n            Graphics2D g2 = (Graphics2D) g;\n            g2.setPaint(m_lineColor);\n            g2.fill(m_lineRect);\n        } // if\n    }\n\n    public interface TabAcceptor {\n        boolean isDropAcceptable(DnDTabbedPane a_component, int a_index);\n    }\n}\n\nclass GhostGlassPane extends JPanel {\n    public static final long serialVersionUID = 1L;\n    private final AlphaComposite m_composite;\n\n    private Point m_location = new Point(0, 0);\n\n    private BufferedImage m_draggingGhost = null;\n\n    public GhostGlassPane() {\n        setOpaque(false);\n        m_composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f);\n    }\n\n    public void setImage(BufferedImage draggingGhost) {\n        m_draggingGhost = draggingGhost;\n    }\n\n    public void setPoint(Point a_location) {\n        m_location.x = a_location.x;\n        m_location.y = a_location.y;\n    }\n\n    public int getGhostWidth() {\n        if (m_draggingGhost == null) {\n            return 0;\n        } // if\n\n        return m_draggingGhost.getWidth(this);\n    }\n\n    public int getGhostHeight() {\n        if (m_draggingGhost == null) {\n            return 0;\n        } // if\n\n        return m_draggingGhost.getHeight(this);\n    }\n\n    public void paintComponent(Graphics g) {\n        if (m_draggingGhost == null) {\n            return;\n        } // if \n\n        Graphics2D g2 = (Graphics2D) g;\n        g2.setComposite(m_composite);\n\n        g2.drawImage(m_draggingGhost, (int) m_location.getX(), (int) m_location.getY(), null);\n    }\n}\n</code></pre>\n'}, {'answer_id': 8610017, 'author': 'Jay Warrick', 'author_id': 1112480, 'author_profile': 'https://Stackoverflow.com/users/1112480', 'pm_score': 3, 'selected': False, 'text': '<p>@Tony: It looks like <a href="https://stackoverflow.com/a/61982/1112480">Euguenes solution</a> just overlooks preserving TabComponents during a swap.</p>\n\n<p>The convertTab method just needs to remember the TabComponent and set it to the new tabs it makes.</p>\n\n<p>Try using this:</p>\n\n<pre><code>    private void convertTab(TabTransferData a_data, int a_targetIndex) {\n\n            DnDTabbedPane source = a_data.getTabbedPane();\n            System.out.println("this=source? " + (this == source));\n            int sourceIndex = a_data.getTabIndex();\n            if (sourceIndex &lt; 0) {\n                    return;\n            } // if\n            //Save the tab\'s component, title, and TabComponent.\n            Component cmp = source.getComponentAt(sourceIndex);\n            String str = source.getTitleAt(sourceIndex);\n            Component tcmp = source.getTabComponentAt(sourceIndex);\n\n            if (this != source) {\n                    source.remove(sourceIndex);\n\n                    if (a_targetIndex == getTabCount()) {\n                            addTab(str, cmp);\n                            setTabComponentAt(getTabCount()-1, tcmp);\n                    } else {\n                            if (a_targetIndex &lt; 0) {\n                                    a_targetIndex = 0;\n                            } // if\n\n                            insertTab(str, null, cmp, null, a_targetIndex);\n                            setTabComponentAt(a_targetIndex, tcmp);\n                    } // if\n\n                    setSelectedComponent(cmp);\n                    return;\n            } // if\n            if (a_targetIndex &lt; 0 || sourceIndex == a_targetIndex) {\n                    return;\n            } // if\n            if (a_targetIndex == getTabCount()) {    \n                    source.remove(sourceIndex);\n                    addTab(str, cmp);\n                    setTabComponentAt(getTabCount() - 1, tcmp);\n                    setSelectedIndex(getTabCount() - 1);\n            } else if (sourceIndex &gt; a_targetIndex) {\n                    source.remove(sourceIndex);\n                    insertTab(str, null, cmp, null, a_targetIndex);\n                    setTabComponentAt(a_targetIndex, tcmp);\n                    setSelectedIndex(a_targetIndex);\n            } else {\n                    source.remove(sourceIndex);\n                    insertTab(str, null, cmp, null, a_targetIndex - 1);\n                    setTabComponentAt(a_targetIndex - 1, tcmp);\n                    setSelectedIndex(a_targetIndex - 1);\n            }\n\n    }\n</code></pre>\n'}, {'answer_id': 20433634, 'author': 'Pascal', 'author_id': 3076046, 'author_profile': 'https://Stackoverflow.com/users/3076046', 'pm_score': 2, 'selected': False, 'text': '<p>Add this to isDragAcceptable to avoid Exceptions:</p>\n\n<pre><code>boolean transferDataFlavorFound = false;\nfor (DataFlavor transferDataFlavor : t.getTransferDataFlavors()) {\n    if (FLAVOR.equals(transferDataFlavor)) {\n        transferDataFlavorFound = true;\n        break;\n    }\n}\nif (transferDataFlavorFound == false) {\n    return false;\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/60269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3827/']