Search code examples
javaswinginline-code

Why does creating an inline version of GridBagConstraints not work?


In attempting to make some Swing code more readable, I have made an InlineGridBagConstraints class which looks like this:

public class InlineGridBagConstraints extends GridBagConstraints {

public InlineGridBagConstraints gridx(int x) {
    gridx = x;
    return this;
}

public InlineGridBagConstraints gridy(int y) {
    gridy = y;
    return this;
}

public InlineGridBagConstraints gridheight(int h) {
    gridheight = h;
    return this;
}

public InlineGridBagConstraints gridwidth(int w) {
    gridwidth = w;
    return this;
}

    // .... and so on, for all fields.

}

The intention is to change this kind of code:

GridBagConstraints c = new GridBagConstraints();
c.gridx = 2;
c.gridy = 1;
c.gridwidth = 3;
myJPanel.add(myJButton, c);

c.gridx = 3;
c.gridwidth = 2;
myJPanel.add(myOtherJButton, c);

c.gridx = 1;
c.gridy = 5;
c.gridheight = 4;
myJPanel.add(yetAnotherJButton, c);

...with something much easier to understand and read, like this:

InlineGridBagConstraints c = new InlineGridBagConstraints();
myJPanel.add(myJButton, c.gridx(2).gridy(1).gridwidth(3));
myJPanel.add(myOtherJButton, c.gridx(3).gridy(1).gridwidth(2);
myJPanel.add(yetAnotherJButton, c.gridx(1).gridy(5).gridheight(4);

However, the above code isn't working. When I attempt it, all of the components occupy the same area in the center of the JPanel and overlap one another. They are not spaced out in the GridBagLayout. If I use the uglier version with the regular GridBagConstraints, however, it works perfectly as intended.

I have tried typecasting the InlineGridBagConstraints into GridBagConstraints, thinking that perhaps that was an issue (even though it shouldn't be), but that didn't help at all.

I've run out of ideas. Does anyone know why this is occurring or what the key difference between the first (standard) and the second (inline) implementations is?


Solution

  • I really have no idea what your GUIConstants defines, as we don't see it, but changing the reset() method in InlineGridBagConstraints to the one below, makes your UI look as you probably expected:

      public InlineGridBagConstraints reset() {
        gridx = 0;
        gridy = 0;
        gridheight = 1;
        gridwidth = 1;
        insets = new Insets(5, 5, 5, 5);
        fill = GridBagConstraints.BOTH;
        anchor = GridBagConstraints.CENTER;
        return this;
      }