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.
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);
}