Google Tag Manager

2022/02/28

Create a new JFrame when the JTabbedPane tab is dropped outside the frame

Code

class TabDragSourceListener implements DragSourceListener {
  @Override public void dragEnter(DragSourceDragEvent e) {
    e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
  }

  @Override public void dragExit(DragSourceEvent e) {
    e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
  }

  @Override public void dragDropEnd(DragSourceDropEvent e) {
    Component c = e.getDragSourceContext().getComponent();
    JRootPane root = ((JComponent) c).getRootPane();
    Class<GhostGlassPane> clz = GhostGlassPane.class;
    Optional.ofNullable(root.getGlassPane())
        .filter(clz::isInstance).map(clz::cast)
        .ifPresent(p -> p.setVisible(false));
    boolean dropSuccess = e.getDropSuccess();
    Window w = SwingUtilities.getWindowAncestor(c);
    boolean outOfFrame = !w.getBounds().contains(e.getLocation());
    if (dropSuccess && outOfFrame && c instanceof DnDTabbedPane) {
      DnDTabbedPane src = (DnDTabbedPane) c;
      int index = src.dragTabIndex;
      final Component cmp = src.getComponentAt(index);
      final Component tab = src.getTabComponentAt(index);
      final String title = src.getTitleAt(index);
      final Icon icon = src.getIconAt(index);
      final String tip = src.getToolTipTextAt(index);
      src.remove(index);
      DnDTabbedPane tabs = new DnDTabbedPane();
      tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
      tabs.addTab(title, icon, cmp, tip);
      tabs.setTabComponentAt(0, tab);
      JFrame frame = new JFrame();
      frame.getContentPane().add(tabs);
      frame.setSize(320, 240);
      frame.setLocation(e.getLocation());
      frame.setVisible(true);
    }
  }

  @Override public void dropActionChanged(DragSourceDragEvent e) {
    /* not needed */
  }

  @Override public void dragOver(DragSourceDragEvent e) {
    /* not needed */
  }
}

References

3 comments:

  1. Hello! Could you help with the task of how to return the moved tab back to the place from where it was moved?

    Thanks a lot!

    ReplyDelete
    Replies
    1. Currently, we do not have a way to move tabs back to the original JTabbedPane. It looks like we need to enable tab moving between JTabbedPanes placed in different JFrames as in Java Swing Tips: Sharing tabs between 2 JFrames

      Delete