Search code examples
javaswingjtoolbar

Setting a specific location for a floating JToolBar


I want to set a specific location to a JToolBar when I launch the Application. Is there any way to set the floating location of a JToolBar on a specific Point on the screen?

I have this code as example which will create a Toolbar and tries to set it floating at Point(300,200), but instead it displays it (floating) at location (0,0).

public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JToolBar toolbar = new JToolBar();
    toolbar.add(new JButton("button 1"));
    toolbar.add(new JButton("button 2"));

    Container contentPane = frame.getContentPane();
    contentPane.add(toolbar, BorderLayout.NORTH);

    ((BasicToolBarUI) toolbar.getUI()).setFloating(true, new Point(300, 200));

    frame.setSize(350, 150);
    frame.setVisible(true);
}

Thank you


Solution

  • From the source code of setFloating(boolean, Point), the Point parameter is only used in case of a false first parameter, and is used to find the location to dock the toolbar to its original Container.

    Basically, floating being the boolean parameter, it goes like :

    if(floating), undock the toolbar and put it in a Window, which location corresponds to the internal floatingXand floatingY variables of BasicToolBarUI (the Point parameter is not used at all)

    else , dock it back to the Container, using the Point parameter to find where to dock it (North, East...).

    Fortunately, a method exists to modify the values of floatingX and floatingY : setFloatingLocation(int x, int y).

    So just call this method before calling setFloating (to which you may pass a null Point parameter, since it won't be used anyway).

    ((BasicToolBarUI) toolbar.getUI()).setFloatingLocation(300, 200);
    ((BasicToolBarUI) toolbar.getUI()).setFloating(true, null);