However, it seems to do strange things when all the elements added have odd-numbered widths.
It gets stranger than that. The size of the parent container also affects the layout.
I replaced the f.pack() with:
f.setSize(150, 100);
and it doesn't work. This is basically the scenario you described since this method or the f.pack() will result in the parent container to have an even width and the layout doesn't work.
However, if you use:
f.setSize(151, 100);
the parent container has an odd width and the layout does work properly.
Another strange observation. I tried adding multiple components to the Box. The problem only seems to happen when the last component added has an odd width.
Anyway, I have no idea what the box layout is doing, but it sure seems like a bug to me.
The solution is to use a different layout manager. You can use a GridBagLayout
to display components on different rows. You will need to set the constraint for each component to go to a new row.
Or you could try to use the Relative Layout, which support vertical layout with centered alignment and you don't need any constraints. The only change to your code would be:
//Box b = new Box(BoxLayout.Y_AXIS);
JPanel b = new JPanel( new RelativeLayout(RelativeLayout.Y_AXIS) );