JToolbar Insert Left and Right

Brandon picture Brandon · Apr 26, 2013 · Viewed 7.5k times · Source

I created a JToolbar component and added it to a Frame. The toolbar uses the BorderLayout.

I add three buttons to the toolbar and they show just fine except I want them to be added to the right side of the toolbar. Right align.

Then whenever I add other buttons to the toolbar, I want them to add to the left side.

How can I do this?

I did the following but what happens is that the buttons appear on top of eachother :S The three to the right are all on eachother and the two to the left are all on eachother..

public class Toolbar extends JToolBar {

    private JToggleButton Screenshot = null;
    private JToggleButton UserKeyInput = null;
    private JToggleButton UserMouseInput = null;
    private CardPanel cardPanel = null;

    public Toolbar() {
        setFloatable(false);
        setRollover(true);
        setLayout(new BorderLayout());

        //I want to add these three to the right side of my toolbar.. Right align them :l
        Screenshot = new JToggleButton(new ImageIcon());
        UserKeyInput = new JToggleButton(new ImageIcon());
        UserMouseInput = new JToggleButton(new ImageIcon());
        cardPanel = new CardPanel();

        add(Screenshot, BorderLayout.EAST);
        add(UserKeyInput, BorderLayout.EAST);
        add(UserMouseInput, BorderLayout.EAST);
        addListeners();
    }

    public void addButtonLeft() {        
        JButton Tab = new JButton("Game");
        Tab.setFocusable(false);
        Tab.setSize(50, 25);

        Tab.setActionCommand(String.valueOf(Global.getApplet().getCanvas().getClass().hashCode()));
        Tab.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardPanel.jumpTo(Integer.valueOf(e.getActionCommand()));
            }
        });

        add(Tab, BorderLayout.WEST);
    }
}

Answer

drew moore picture drew moore · Apr 26, 2013

They're on top of eachother because you're putting them all in the same two places - namely BorderLayout.EAST and BorderLayout.WEST.

You can achieve your desired effect without using a BorderLayout but instead using JToolBar's default layout.

 add(tab);
 // add other elements you want on the left side 

 add(Box.createHorizontalGlue());

 add(Screenshot);
 add(UserKeyInput);
 add(UserMouseInput);
 //everything added after you place the HorizontalGlue will appear on the right side

EDIT (based on your comment):

Create a new JPanel and add it to the toolbar before the glue:

 JPanel leftPanel = new JPanel();
 add(leftPanel);

 add(Box.createHorizontalGlue());

 add(Screenshot);
 add(UserKeyInput);
 add(UserMouseInput);

Then have your addButtonLeft() method add new buttons to the panel, rather than directly to the toolbar.