Fuu
Fuu

Reputation: 3474

Java Swing MigLayout, centering two elements inside a spanned row

I'm working on a MigLayout form with 3 columns and 4 rows, like this:

"wrap 3",
"[15%] 15px [45%] 15px [40%]",
"20 [] 15 [] 15 [grow,fill] 15 []"

Now my goal is to have it look like this:

.------------------------------------.
| 15% |     45%      |     40%       |
|------------------------------------|
|     |              |               |
|------------------------------------|
|     |              |               |
|------------------------------------|
|           button,button            |
`------------------------------------´

I want the buttons on the last row centered, so I assumed that it first requires that I span the 3 columns of the 4th row into one with the "span 3, center" component constraint on the button.

This works nicely with just one button, but I'm having problems figuring out how to add the second button, while keeping both two buttons centered on the same row at the same time. If i add same constraints on the second button it appears perfectly centered below the first button on the next row.

Upvotes: 5

Views: 3519

Answers (3)

kleopatra
kleopatra

Reputation: 51525

The solution is to span and split at the same time: the split defines the number of components that should live in the spanned cell:

panel.add(firstButton, "span, split 2, center");
panel.add(secondButton);

Aside: a span without count defaults to a high number that it effectly means "all"

Upvotes: 6

ungalcrys
ungalcrys

Reputation: 5610

you could try to put two boxes on the right and left sides that will grow or push the buttons in middle like this:

pane.setLayout(new MigLayout("fill"));
pane.add(Box.createHorizontalBox(), "push");
pane.add(new JButton("asdf"));
pane.add(new JButton("zxcv"));
pane.add(Box.createHorizontalBox(), "push,wrap");

Upvotes: 0

colinjwebb
colinjwebb

Reputation: 4378

It's not ideal, but you could add the two buttons to a new JPanel, and then nest that JPanel inside your existing layout with the "span 3, center"

I'm struggling to think of another way.

Upvotes: 2

Related Questions