I’m using GroupLayout to manage components in some dynamically generated data input forms. The layout is more or less like so:
*-----------------------------------------------*
| label A | field A |
| label B | field B |
| label C | field C |
*-----------------------------------------------*
I’m using 2 parallel groups for the horizontal layout, and a single sequential group for the vertical layout. For the most part, everything is working just fine.
I want to limit the maximum width of the labels (which are just instances of JLabel) to 1/3 of the width of the parent JFrame. If the JFrame was a fixed size this would be trivial, but I have to deal with it being resized.
I’m picking up ComponentListener.componentResized() events from the JFrame but I’m a bit stuck on what to do once I receive such an event.
I’ve tried this approach without any luck:
public void componentResized(ComponentEvent e) {
int maxW = parentFrame.getWidth() / 3;
for (JLabel l : labels) {
l.setMaximumSize( // have also tried setSize() and setPreferredSize()
new Dimension(
Math.min(l.getSize().width, maxW),
l.getMaximumSize().height));
}
groupLayout.invalidateLayout(getContentSpace());
}
Can anyone suggest a way to limit the width of the labels which will work?
I could probably rebuild the layout from scratch every time, but I feel like there ought to be a simpler way.
In this example,
GroupLayoutcan simply rely on the preferred size of the label, without having to resort to anysetXXXSize()method. In this approach,The use of
GroupLayout.Alignment.TRAILINGto right justify the labels is a personal preference, and I’ve added a second panel to show how it works nested in another layout.