Reputation: 368
I'm trying to center the content of a JPanel with BoxLayout vertically. The BoxLayout is aligned to the Y-axis, so items inside are aligned horizontally.
For example, what I have now:
-----------------------------
| ------ |
| ---------- |
| ---- |
| -------------- |
| |
| |
| |
| |
| |
| |
-----------------------------
What I want:
-----------------------------
| |
| |
| |
| ------ |
| ---------- |
| ---- |
| -------------- |
| |
| |
| |
-----------------------------
At the moment, I'm centering the column of elements using setAlignmentX(Component.CENTER_ALIGNMENT):
JPanel box = new JPanel();
box.setLayout(new BoxLayout(box, BoxLayout.Y_AXIS));
JLabel one = new JLabel("First element");
one.setAlignmentX(JLabel.CENTER_ALIGNMENT);
box.add(one);
JLabel two = new JLabel("Second element");
two.setAlignmentX(JLabel.CENTER_ALIGNMENT);
box.add(two);
...
How could I change this to also be vertically centered?
Upvotes: 1
Views: 1393
Reputation: 324108
The BoxLayout
layout allows components to grow (up to their maximum size) when extra space is available.
You need to add components that are allowed to grow. The basic code would be:
box.add( Box.createVerticalGlue() );
box.add(...);
box.add( Box.createVerticalGlue() );
The two "glue" components on the top/bottom will grow to fill available space.
Upvotes: 2