For my Java Swing GUI I have two major components:
One part is a vertical list of a few check boxes, the other is an image.
When the jframe window is resized/maximised the proportions stay the same when I would much rather the absolute size of the check box list stay the same and just the image resize like:
Is this possible using GridBagLayout?
I have been laying everthing out into one JPanel
(ContentPane
) using the following:
CheckBoxes:
for(int i=0; i<5; i++){
GridBagConstraints gbc = new GridBagConstraints();
JCheckBox checkbox = new JCheckBox("CheckBox " + (i+1));
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = i;// Increases by one for each checkbox
gbc.insets = new Insets(0, 10, 5, 5);
gbc.weightx = 1;
gbc.weighty = 1;
contentPane.add(checkbox,gbc);
}
Image: Note I have replaced this with a blank JList
as there is no swing Image component I need the component to work with contentPane.add(...)
.
GridBagConstraints gbc = new GridBagConstraints();
JList list = new JList(new String[]{""});
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 10;
gbc.gridheight = 5;
gbc.gridx = 1;
gbc.gridy = 0;// Increases by one for each checkbox
gbc.insets = new Insets(0, 10, 5, 5);
gbc.weightx = 1;
gbc.weighty = 1;
contentPane.add(list,gbc);
This is most definitely possible.
Where I think you're getting tripped up is that you're using 'gbc.weighty = 1'. This will resize the component vertically at a 1:1 ratio with the component it is in. If you don't want it to resize in this direction, you should change it to gbc.weighty = 0.
If you are having problems getting swing to anchor your check boxes to the top of the panel when it resizes after doing this, I'd try this little trick.
Create a JPanel (I'll call it Panel1) to the left of your image panel. Inside this JPanel, put another JPanel (CheckBoxPanel) that will hold your checkboxes at gridx = 0, gridy = 0. Set it to scale horizontally, but not vertically, so weightx = 1.0, weighty = 0.
Now put an empty JLabel underneath Panel1 at gridx = 0, gridy = 1. Make sure to remove any text that gets set by default to the label. Set it to scale vertically, so the JLabel will have weighty = 1. This will make sure that when you resize, the CheckBoxPanel will get pushed to the top of Panel1 by the expanding JLabel. When you're at 'normal' size, the JLabel will have a height of 0, so you won't see it.
You could use
BoxLayout
instead to avoid complexity!