javaswingjtoolbarjtogglebutton

JToolbar: JToggleButton Alignment


I am attempting to align JToggleButtons in a JToolBar. I want the buttons to be aligned vertically and to the left. My code is as follows:

JToolBar toolbar = new JToolBar();
toolbar.setLayout(new FlowLayout());
toolbar.setAlignmentX(FlowLayout.LEFT);
toolbar.add(new JToggleButton("Test"));
toolbar.add(new JToggleButton("Test2"));
toolbar.add(new JToggleButton("Test3"));
toolbar.add(new JToggleButton("Test with a long name"));

This is what the result looks like. my JToolBar

Also, when docked to the left, it looks like this. Ideally, I want the buttons to stack on each other vertically (and still remain aligned to the left). Any tips?

JToolBar docked to the left

The ideal results should look like this: Ideal results - left aligned buttons, and stacked when the toolbar is docked to the left


Solution

  • I want the buttons to align to the left

    This is the default behaviour for a JToolBar. There is no need to play with the layout manager.

    I want the buttons to stack on each other vertically

    Again, this is the default behaviour when used with the default layout manager.

    Read the section from the Swing tutorial on How to Use Tool Bars for more information and working examples.