Align Swing Components across Panels
I recommend to favor flat layouts over nested ones. In a single layout alignment is easy. Avoid TitledBorders and replace them with titled separators, separators, or just white space. That helps for the vast majority of editors and forms.
But if you want to align across multiple editors or forms, the above technique fails. The JGoodies FormLayout provides two levels to address this problems, and more generally to improve layout consistency: 1) lower bounds for sizes, 2) layout variables.
With 1) you can describe layouts that ensure a minimum width across forms. For example, if you want to say that all label columns have at least a width of 100px, you can say "[100px, pref]" for the label column.
2) goes beyond approach 1). And the motivation is to extract the 100px from your many forms. In FormLayout you can setup layout variables, for example $label that you configure as "[100px, pref]" or "right:[75dlu, pref]", etc. If you use the layout variable in all your editors, these will be consistent and you have a single place where you can configure all label columns for all editors.
There's no simple way to do that which I'm aware of. Your options:
- Write your own layout manager (or extend an existing one) with that capability
- Fixed column widths
- Decide that panels that are visually separated by borders don't need to have their contents aligned after all
Just because the JPanel
s have borders, doesn't mean that they actually need to contain their apparent contents. Set the panels to transparent. Add the panels and the components to the enclosing panel. Add spacer components to mimic the insets of the panels in the layout. You will also need to switch off "optimised drawing", or some such, for overlapping components.