Search code examples
javaswinglook-and-feeljtoolbar

How to remove/replace the close button from a floating JToolBar


I am learning Java Swing and have a optical issue that i am trying to solve.

When i use the System-Default Look and Feel on Windows 7, i get the huge close button and empty title-bar over the floating JToolBar.

Image of the floating toolbar only (without the application in background):

the floating toolbar

Is there a way to remove the surrounding Borders & Button of a floating toolbar? Or at least adjust their sizes?

Thanks the suggestion from nachokk and the following snipplet found on https://forums.oracle.com/thread/2279762 i may be did a step forward. But still, not working. Now after undocking, the toolbar become invisible.

    tbFile = new JToolBar();
    tbFile.addHierarchyListener(new HierarchyListener() {

        @Override
        public void hierarchyChanged(HierarchyEvent e) {
            if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) == 0) return;
            JToolBar bar = (JToolBar) e.getComponent();
            if (!((BasicToolBarUI) bar.getUI()).isFloating()) return;
            final Window topLevel = SwingUtilities.windowForComponent(bar);
            if (topLevel instanceof JDialog) {
                //((JDialog) topLevel).setVisible(false);
                ((JDialog) topLevel).setUndecorated(true);
                //((JDialog) topLevel).setVisible(true);
            }    
        }
    });

Solution

  • Thanks to comments here and the answer of Yishai on https://stackoverflow.com/a/875317/1107653 , i got what i wanted - undecorated floating ToolBar. In order to use setUndecorated, the frame/dialog should be disposed first.

        tbFile = new JToolBar();
        final HierarchyListener hierarchyListener = new HierarchyListener() {
    
            @Override
            public void hierarchyChanged(HierarchyEvent e) {
    
                if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) == 0) return;
                JToolBar bar = (JToolBar) e.getComponent();
                if (!((BasicToolBarUI) bar.getUI()).isFloating()) return;
    
                Window topLevel = SwingUtilities.windowForComponent(bar);
                if(topLevel == null) return;
    
                topLevel.dispose();
                ((JDialog) topLevel).setUndecorated(true);
                topLevel.setVisible(true);
    
            }
        };
        tbFile.addHierarchyListener(hierarchyListener);