0

I have a JButton in my application to add/remove a JToolBar. When the toolbar is docked, I can remove it using:

toolBar.getParent().remove(toolbar); // toolBar is an instance of JToolBar

If I do this while the toolbar is floating, nothing happens, the floating toolbar remains there.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Aldo Canepa
  • 1,791
  • 2
  • 16
  • 16

1 Answers1

1

Using the BasicToolBarUI object obtained from the JToolBar, we can know if it floating. If the JToolbar is floating, we can dispose its window.

public boolean isFloating(JToolBar toolbar) {
  ToolBarUI ui = toolbar.getUI();
  return ui instanceof BasicToolBarUI && ( (BasicToolBarUI) ui).isFloating();
}

public void removeFromParent(JToolBar toolbar) {
  if (isFloating(toolbar)) {
    // Dock the JToolBar before removing
    BasicToolBarUI basicToolbarUI = (BasicToolBarUI) toolbar.getUI();
    basicToolbarUI.setFloating(false, null);
  }
  // Not floating, docked, remove from parent component
  toolbar.getParent().remove(toolbar);
}
Aldo Canepa
  • 1,791
  • 2
  • 16
  • 16