Marius Manastireanu
Marius Manastireanu

Reputation: 2576

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

Upvotes: 3

Views: 1018

Answers (2)

Arnaud
Arnaud

Reputation: 17524

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

Upvotes: 2

bradnorman5490
bradnorman5490

Reputation: 33

To give the toolbar an absolute layout first you have to set the layout to null like this: frame.setLayout(null); Then instead of ((BasicToolBarUI) toolbar.getUI()).setFloating(true, new Point(300, 200)); you can just use toolBar.setBounds(x,y, width, height);

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setLayout(null);
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);

toolBar.setBounds(100,100,50,50);

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

}

Upvotes: 0

Related Questions