Taming GridBagLayout & Faking Baseline Align

Jun 7, 03:18 PM

When I was giving some of my dialogs a facelift, I decided I really wanted my label and text boxes aligned to the text’s baseline. It really helps give an app a polished look. I remember seeing a blog about baseline alignment in soon-to-be-release-jre and in matisse. But I need them now. Granted my method is not very accurate on all platforms but it 1) looks better than the default alignment, 2) was quick to implement(don’t have to spend time fiddling with each control in gui builder), and 3) available now.

Example of pseudo-baseline alignment

This method uses GridBagLayout. A lot of people whine about Grid Bag. But frankly, once to figure it out, there is not a compelling replacement. The trick is make methods or classes to build your GridBagContraints otherwise your likely to go nuts.

My little hack does just that. It is a class called BaselineForm (download). Methods on the class build constraint objects for generic controls and special ones for labels. The label constraints can have a different alignment and thicker insets. The fudge factors are hardcoded in this version and I based on the look and feel we use. Feel free to fire up your OS’s magnifier and tweak the code to your needs.

The heart of the code is in the getComponent method….

    public GridBagConstraints getComponent(int x, int y, int w, int h){
        lastX = x;
        lastY = y;
        int useX = x;
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.weighty = 0;
        gbc.gridwidth = w;
        gbc.gridheight = h;

gbc.insets = new Insets(2,2,2,2); gbc.anchor = GridBagConstraints.NORTHWEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = weight; return gbc; }
… and the getLabel method…
    public GridBagConstraints getLabel(int x, int y, int w, int h){
        GridBagConstraints gbc = getComponent(x,y,w,h);
        gbc.insets = new Insets(5,2,2,2);
        gbc.anchor = labelsRightJustistied?GridBagConstraints.NORTHEAST:GridBagConstraints.NORTHWEST;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        return gbc;
    }

So now you can write code like….

JPanel p = new JPanel(new GridBagLayout());
BaselineForm form = new BaselineForm(2); // Two columns
p.add(new JLabel("Username"), form.getLabel());
p.add(new JTextField(), form.getComponent());
p.add(new JLabel("Password"), form.getLabel());
p.add(new JPasswordField(), form.getComponent());

No fuss, no muss.

Commenting is closed for this article.