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?
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;
}
As far as I can rely on what you wrote, this should work. So, I would suggest to start looking for other bugs in your code.
Are you setting the LayoutManager correctly in both examples?
Update: Try to get rid of the reset call in the constructor. The super class constructor will do the job correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With