1

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

Joshua Goldberg
  • 5,059
  • 2
  • 34
  • 39
Joe Balin
  • 177
  • 2
  • 17

2 Answers2

1

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Hmm, thanks for the response, but that still doesn't answer my question (perhaps I worded it weird?). I want to move the buttons to look like this (as in, the buttons align to the left of the toolbar and stack vertically when docked to the left): http://puu.sh/seMS7/4e3347c203.png – Joe Balin Nov 11 '16 at 17:07
  • @JoeBalin, Did you download the demo code from the tutorial and test it? – camickr Nov 11 '16 at 17:11
  • I went back and copy-pasted the example code. Basically, I had initialized the ButtonGroup earlier in the program, so I only had to loop through the button group and add each button to the toolbar. However, by defining a new ButtonGroup and then adding the buttons back to, it magically fixed it, and they align properly. Weird. – Joe Balin Nov 11 '16 at 17:40
0

A FlowLayout can only lay out components in horizontal rows, wrapping around like the way text "flows" on a page.

You could change to a vertical BoxLayout: toolbar.setLayout(new BoxLayout(toolbar, BoxLayout.PAGE_AXIS)); or get the same effect (since JToolBar uses a BoxLayout by default) by calling the constructor new JToolBar(SwingConstants.VERTICAL)

To left align, though, I believe you will need to call setAlignmentX(FlowLayout.LEFT) for each Component you add, not the toolbar itself or its layout. See, for example, the BoxLayout tutorial.

Joshua Goldberg
  • 5,059
  • 2
  • 34
  • 39