MigLayout: sizegroup based on smallest cell

54 Views Asked by At

I would like to use the sizegroup keyword in miglayout to have 2 cells of the grid have the same width. The problem is that sizegroup stretches the shortest cell to reach the width of the longer, whereas i would want the opposite behaviour.

What i am trying to achieve is to have aTextField.width = btextField.width + bButton.width

import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;


public class SizeGroupExample extends JFrame {
    
    private final MigLayout migLayout = new MigLayout("debug", "", "");
    private final JLabel aLabel = new JLabel("Label A");
    private final JTextField aTextField = new JTextField();
    private final JLabel bLabel = new JLabel("Label B");
    private final JTextField bTextField = new JTextField();
    private final JButton bButton = new JButton("Press");
    
    public SizeGroupExample() {
        Container container = getContentPane();
        container.setLayout(migLayout);
        add(aLabel, "");
        add(aTextField, "w 250!, sg 2, wrap");
        add(bLabel, "");
        add(bTextField, "split 2, sg 2");
        add(bButton, "wrap");
        setResizable(true);
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);
    }
    
    public static void main(String[] args) {
        new SizeGroupExample();
    }
}
1

There are 1 best solutions below

0
Emmanuel Bourg On

sizegroups are always aligned on the biggest component, so this won't work. But in the specific case described, you can get the expected result by growing the first field:

getContentPane().setLayout(new MigLayout("debug"));
add(new JLabel("Label A"), "");
add(new JTextField(), "growx, wrap");
add(new JLabel("Label B"), "");
add(new JTextField(), "width 200!, split 2, ");
add(new JButton("Press"), "wrap");
setResizable(true);
pack();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);

This gives:

enter image description here

The total width is set by the second field and the button, and the first field expands to the width available.