Re: GridBagLayout - A simple test program
Knute Johnson wrote:
With all the questions that show up about how to get GridBagLayout to
work I thought I would write a little test program to use as a training
device. Any feedback would be appreciated. The program has most of the
constraints but not the ones I rarely use, all the Baseline relative and
Orientation relative values. I could put those in but I thought I would
put it out there for comments before I generated all that code. The
other feature that might be good to add is the ability to set the
preferred size of the components as that does have an effect on layout.
Anyway, please try it out and let me know what you think. Click on a
button to set the constraints for that button.
Thanks,
http://rabbitbrush.frazmtn.com/gridbagtester.html
I definitely think there's a need for tools that help with GridBagLayout.
About the only time I use GridBagLayout is as follows
String[] label = { "Apples", "Pears", "Bananas" };
JTextField[] field = new JTextField[label.length];
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
GridBagConstraints labelConstraints = new GridBagConstraints();
labelConstraints.anchor = GridBagConstraints.EAST; // right align
labelConstraints.gridwidth = GridBagConstraints.RELATIVE; // position
GridBagConstraints fieldConstraints = new GridBagConstraints();
fieldConstraints.gridwidth = GridBagConstraints.REMAINDER; // end row
fieldConstraints.fill = GridBagConstraints.HORIZONTAL; // fill
fieldConstraints.weightx = 1.0; // uses horizontal space
for (int i = 0; i < label.length; i++) {
p.add(new JLabel(label[i] + ": "), labelConstraints);
field[i] = new JTextField(Integer.toString(i));
p.add(field[i], fieldConstraints);
}
I find the above to be a useful idiom but I don't think your Applet
would help anyone learn it.
Your applet looks at layouts from GridBagLayout's point of view, would
it be possible to make an applet with menus that say things like
"move this box to the start of new line",
"make this box grow as the container grows",
"this box is part of a group of similar boxes",
"make all members of this group right aligned"
In other words, look at the layout problem from a beginners perspective
and display some generated source code they can then use.
As a sidenote, here's an equivalent MigLayout:
String[] label = { "Apples", "Pears", "Bananas" };
JTextField[] field = new JTextField[label.length];
JPanel p = new JPanel();
p.setLayout(new MigLayout("wrap", "[align right][fill,grow]",""));
for (int i = 0; i < label.length; i++) {
p.add(new JLabel(label[i] + ": "));
field[i] = new JTextField(Integer.toString(i));
p.add(field[i]);
}
I find MigLayout always to be more concise *and* easier to understand.
Anything which helps us GridBagLayoutPhobics is a good thing and should
be encouraged.