Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are good ways to keep GridBagConstraints under control?

Tags:

java

swing

I'm somewhat new to Swing programming, and I find that as much as I love the power of GridBagLayout, if you've got a lot of components, there are lots of lines of code just setting up the constraints for the layout. What are some good ways to keep this under control, besides using a visual editor?

like image 657
decitrig Avatar asked Jan 29 '26 14:01

decitrig


2 Answers

Remember that when you add GridBagConstraints to a GridBagLayout the data is copied (actually cloned). Therefore, you don't need to start from scratch for each component you add.

You may find the double-brace idiom useful.

I recommend using a better builder than GridBagConstraints public fields. My original answer had a link to a now defunct blog entry on the subject for an example. IIRC, a class extending GridBagConstraints with method returning this. I forget all the extras, but there were methods that set multiple fields (say, gridx and gridy), increments and more exotics things.

like image 178
Tom Hawtin - tackline Avatar answered Jan 31 '26 04:01

Tom Hawtin - tackline


I feel your pain. I feel it so much, that I have recently abandoned GridBagLayout entirely, in favor of another tool - JGoodies Forms. Its layout code is more concise, reads at a higher level, and is in general much more satisfying to use than GridBagLayout.

It defines a mini-language to define layouts. It's cryptic at first glance, but don't let that discourage you.

If you are able to use it in your environment, I would highly recommend it.

like image 33
John Avatar answered Jan 31 '26 05:01

John