How to make BoxLayout vertical but children flow top-aligned?

Posted by user291701 on Stack Overflow See other posts from Stack Overflow or by user291701
Published on 2012-06-21T13:28:04Z Indexed on 2012/06/21 15:16 UTC
Read the original article Hit count: 208

Filed under:

I'm trying to get get a vertical, top-aligned layout to work. This is what I have:

JPanel pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));

MyImagePanel panelImage = new MyImagePanel();
panelImage.setSize(400, 400);

pane.add(new JComboBox());
pane.add(panelImage);
pane.add(new JButton("1"));
pane.add(new JButton("2"));
pane.add(new JButton("3"));

JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.add(pane);
frame.pack();
frame.setVisible(true);

All the controls appear, but it looks like padding is being applied at run time between their tops and bottoms so they're somewhat vertically centered. This is what I'm going for:

-----------------------------------------------------
| ComboBox |                                        |
------------                                        |
|          |                                        |
| Image    |                                        |
|          |                                        |
------------                                        |
| Button 1 | Any additional space fills the right   |
------------                                        |
| Button 2 |                                        |
------------                                        |
| Button 3 |                                        |
------------                                        |
|                                                   |
|  Any additional space fills the bottom            |
|                                                   |
-----------------------------------------------------

How do I get BoxLayout to do that?

Thanks

------------------------- Update -------------------------

Was able to use this:

Box vertical = Box.createVerticalBox();
frame.add(vertical, BorderLayout.NORTH);
vertical.add(new JComboBox());
vertical.add(new JButton("1"));  
...

to get what I wanted.

© Stack Overflow or respective owner

Related posts about swing