MigLayout is a powerfull Swing layout manager.
However, when you are used to the standard J2SE layout managers, it can take a while to understand how to do something using MigLayout.
For example, I needed to create this UI:

As you can see, the idea is to leave the OK button at the button of the dialog, even when the dialog is resized.
My initial attempt was to use a fake panel as the third row:
public class TestResize extends JDialog {
protected JPanel contentPane;
public TestResize() {
super((Dialog) null, "Test resize", true);
setupUI();
setContentPane(contentPane);
}
private void setupUI() {
contentPane = new JPanel(new MigLayout());
// first row
contentPane.add(new JLabel("Enter size"), "");
contentPane.add(new JTextField(""), "grow, pushx, wrap");
// second row
contentPane.add(new JLabel("Enter weight"), "");
contentPane.add(new JTextField(""), "grow, pushx, wrap");
// third row = fake panel that is allowed to grow
contentPane.add(new JPanel(), "span 2, grow, pushy, wrap");
// fourth row = panel with centered button
JPanel buttonPanel = new JPanel(new MigLayout("", "[center, grow]"));
buttonPanel.add(new JButton("Ok"), "");
contentPane.add(buttonPanel, "dock south");
}
public static void main(String[] args) {
TestResize dialog = new TestResize();
dialog.pack();
dialog.setVisible(true);
}
}
This works… but it’s not the correct way to do it using MigLayout: you need to use the “push” constraint.
public class TestResize extends JDialog {
protected JPanel contentPane;
public TestResize() {
super((Dialog) null, "Test resize", true);
setupUI();
setContentPane(contentPane);
}
private void setupUI() {
// Layout is constructed with "push" constraint
contentPane = new JPanel(new MigLayout("", "", "[][]push[]"));
// first row
contentPane.add(new JLabel("Enter size:"), "");
contentPane.add(new JTextField(""), "grow, pushx, wrap");
// second row
contentPane.add(new JLabel("Enter weight"), "");
contentPane.add(new JTextField(""), "grow, pushx, wrap");
// third row = panel with centered button
JPanel buttonPanel = new JPanel(new MigLayout("", "[center, grow]"));
buttonPanel.add(new JButton("Ok"), "");
contentPane.add(buttonPanel, "dock south");
}
public static void main(String[] args) {
TestResize dialog = new TestResize();
dialog.pack();
dialog.setVisible(true);
}
}
That’s it: no more crappy fake panel ! 🙂
Laurent KUBASKI