How to implement draggable tab using Java Swing?

Question!

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.

EDIT: The Java Tutorials - Drag and Drop and Data Transfer.



Answers

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:

  1. Detect that a drag has occurred
  2. Draw the dragged tab to an offscreen buffer
  3. Track the mouse position whilst dragging occurs
  4. Draw the tab in the buffer on top of the component.

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.

Or maybe I'm just disappointed because I spent time writing this solution when one already existed :p

import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;


public class DraggableTabbedPane extends JTabbedPane {

  private boolean dragging = false;
  private Image tabImage = null;
  private Point currentMouseLocation = null;
  private int draggedTabIndex = 0;

  public DraggableTabbedPane() {
    super();
    addMouseMotionListener(new MouseMotionAdapter() {
      public void mouseDragged(MouseEvent e) {

        if(!dragging) {
          // Gets the tab index based on the mouse position
          int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), e.getY());

          if(tabNumber >= 0) {
            draggedTabIndex = tabNumber;
            Rectangle bounds = getUI().getTabBounds(DraggableTabbedPane.this, tabNumber);


            // Paint the tabbed pane to a buffer
            Image totalImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics totalGraphics = totalImage.getGraphics();
            totalGraphics.setClip(bounds);
            // Don't be double buffered when painting to a static image.
            setDoubleBuffered(false);
            paintComponent(totalGraphics);

            // Paint just the dragged tab to the buffer
            tabImage = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB);
            Graphics graphics = tabImage.getGraphics();
            graphics.drawImage(totalImage, 0, 0, bounds.width, bounds.height, bounds.x, bounds.y, bounds.x + bounds.width, bounds.y+bounds.height, DraggableTabbedPane.this);

            dragging = true;
            repaint();
          }
        } else {
          currentMouseLocation = e.getPoint();

          // Need to repaint
          repaint();
        }

        super.mouseDragged(e);
      }
    });

    addMouseListener(new MouseAdapter() {
      public void mouseReleased(MouseEvent e) {

        if(dragging) {
          int tabNumber = getUI().tabForCoordinate(DraggableTabbedPane.this, e.getX(), 10);

          if(tabNumber >= 0) {
            Component comp = getComponentAt(draggedTabIndex);
            String title = getTitleAt(draggedTabIndex);
            removeTabAt(draggedTabIndex);
            insertTab(title, null, comp, null, tabNumber);
          }
        }

        dragging = false;
        tabImage = null;
      }
    });
  }

  protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Are we dragging?
    if(dragging && currentMouseLocation != null && tabImage != null) {
      // Draw the dragged tab
      g.drawImage(tabImage, currentMouseLocation.x, currentMouseLocation.y, this);
    }
  }

  public static void main(String[] args) {
    JFrame test = new JFrame("Tab test");
    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    test.setSize(400, 400);

    DraggableTabbedPane tabs = new DraggableTabbedPane();
    tabs.addTab("One", new JButton("One"));
    tabs.addTab("Two", new JButton("Two"));
    tabs.addTab("Three", new JButton("Three"));
    tabs.addTab("Four", new JButton("Four"));

    test.add(tabs);
    test.setVisible(true);
  }
}


Add this to isDragAcceptable to avoid Exceptions:

boolean transferDataFlavorFound = false;
for (DataFlavor transferDataFlavor : t.getTransferDataFlavors()) {
    if (FLAVOR.equals(transferDataFlavor)) {
        transferDataFlavorFound = true;
        break;
    }
}
if (transferDataFlavorFound == false) {
    return false;
}
By : Pascal


@Tony: It looks like Euguenes solution just overlooks preserving TabComponents during a swap.

The convertTab method just needs to remember the TabComponent and set it to the new tabs it makes.

Try using this:

    private void convertTab(TabTransferData a_data, int a_targetIndex) {

            DnDTabbedPane source = a_data.getTabbedPane();
            System.out.println("this=source? " + (this == source));
            int sourceIndex = a_data.getTabIndex();
            if (sourceIndex < 0) {
                    return;
            } // if
            //Save the tab's component, title, and TabComponent.
            Component cmp = source.getComponentAt(sourceIndex);
            String str = source.getTitleAt(sourceIndex);
            Component tcmp = source.getTabComponentAt(sourceIndex);

            if (this != source) {
                    source.remove(sourceIndex);

                    if (a_targetIndex == getTabCount()) {
                            addTab(str, cmp);
                            setTabComponentAt(getTabCount()-1, tcmp);
                    } else {
                            if (a_targetIndex < 0) {
                                    a_targetIndex = 0;
                            } // if

                            insertTab(str, null, cmp, null, a_targetIndex);
                            setTabComponentAt(a_targetIndex, tcmp);
                    } // if

                    setSelectedComponent(cmp);
                    return;
            } // if
            if (a_targetIndex < 0 || sourceIndex == a_targetIndex) {
                    return;
            } // if
            if (a_targetIndex == getTabCount()) {    
                    source.remove(sourceIndex);
                    addTab(str, cmp);
                    setTabComponentAt(getTabCount() - 1, tcmp);
                    setSelectedIndex(getTabCount() - 1);
            } else if (sourceIndex > a_targetIndex) {
                    source.remove(sourceIndex);
                    insertTab(str, null, cmp, null, a_targetIndex);
                    setTabComponentAt(a_targetIndex, tcmp);
                    setSelectedIndex(a_targetIndex);
            } else {
                    source.remove(sourceIndex);
                    insertTab(str, null, cmp, null, a_targetIndex - 1);
                    setTabComponentAt(a_targetIndex - 1, tcmp);
                    setSelectedIndex(a_targetIndex - 1);
            }

    }


This video can help you solving your question :)
By: admin