tags:

views:

296

answers:

2
+3  Q: 

MigLayout Question

I need to layout a panel on the top of my Dialog so that it has two buttons (Save and Cancel).

I want the save to be on the left and Cancel to be on the right side.

I've created a JPanel using the MigLayout and docked it to the north of the content pane, and can't for the life of me figure out how to add the two buttons to it so that they appear as I want them. Docking them within the panel seems to get rid of all padding in the dialog (which looks terrible).

Any help would be greatly appreciated.

+2  A: 

Doh, always happens as soon as you ask a question, the answer pops out:

JPanel buttonPanel = new JPanel(new MigLayout("fill","[50][50]",""));
buttonPanel.add(saveChangesButton);
buttonPanel.add(cancelButton, "align right");
getContentPane().add(buttonPanel, "dock north");

Note that the content pane is using the MigLayout too.

Allain Lalonde
You should have accepted the other guy's answer, he's right. You should be using the tags.
I82Much
Done. Thanks for bringing my attention to this.
Allain Lalonde
+8  A: 

As an aside, you should probably not be dictating which button is on the left or right. That's one of the way cool things about MiGLayout (platform independence, even on things such as where the cancel button should go).

p.add(cancelButton, "tag cancel");
p.add(okButton, "tag ok");

Now the buttons will appear in the correct order, based on platform.

Here's an article with code doing what you are going for. I strongly recommend avoiding trying to force the size of components like buttons (these really should come from the platform look and feel). Also, docking is fine if it makes sense to do so, but I rarely find it to be necessary. Instead of building a totally separate panel for your buttons, just span the row that contains the buttons - much cleaner, and you don't wind up with all of the nested panels.

It's hard to break from the border layout technique of nested panels, but once you get the hang of it, MigLayout is a dream. BTW - I understand that there are times where you might want to build up the button panel in a library - if that's the case, then separate panels may make sense (although you could also have the library add a button row to an existing panel, instead of returning a panel that you then add to the layout).

Kevin Day