0
votes

I've tried all combinations and looked at all the documentation but I can't figure out how to use GridBagLayout.

I've got 3 components in a JPanel with GridBagLayout being the LayoutManager of the JPanel and using GridBagConstraints on the 3 components.

With the current code (as shown below) the 3 elements appear on the panel properly. The issue is that the first component is a JLabel which sometimes is quite long, if this is the case then it will expand and make the other 2 components smaller.

My objective is to have a JPanel with a GridBagLayout of 1 row and 4 columns, where the first element takes up the first 2 columns, and the other 2 elements take up the remaining 2, and that these elements to do not expand out of their columns.

private static void setConstraints(GridBagConstraints constraints, int gridx, int gridy, int weightx, Insets insets) {
    constraints.gridx = gridx;
    constraints.weightx = weightx;
    constraints.insets = insets;
}

gridBagLayout = new GridBagLayout();
constraints = new GridBagConstraints();
centerPanel = new JPanel(gridBagLayout);

constraints.fill = GridBagConstraints.HORIZONTAL;
fileNameLabel = new JLabel("Resolving: '" + EngineHelpers.trimStringToFitPanel(urlTextField.getText(), 70) + "'");
setConstraints(constraints, 0, 0, 2, new Insets(0, 5, 5, 0));
gridBagLayout.setConstraints(fileNameLabel, constraints);
progressBar = new JProgressBar();
progressBar.setStringPainted(true);
setConstraints(constraints, 1, 0, 1, new Insets(0, 5, 5, 0));
gridBagLayout.setConstraints(progressBar, constraints);
cancelDownloadButton = new JButton("Cancel");
setConstraints(constraints, 2, 0, 1, new Insets(0, 0, 0, 0));
gridBagLayout.setConstraints(cancelDownloadButton, constraints);

centerPanel.add(fileNameLabel);
centerPanel.add(progressBar);
centerPanel.add(cancelDownloadButton);

Thanks in advance everyone, sorry for the stupid question!

1

1 Answers

2
votes

You probably want weightx set to 0 for both the button and progress bar. For the label, set the weight to 1. This will keep the button and progress bar from expanding at all and let the progress bar take all the extra space.

Also set gridwidth on the progress bar constraints to 2 so it actually uses 2 columns.

Finally, depending on where centerPanel is placed, it may not actual expand to fill the container. If centerPanel is being placed in a parent with a BorderLayout, it should expand. To make sure, you can add a border with centerPanel.setBorder(BorderFactory.createLineBorder(Color.RED)) for debugging. This can also be useful on the button, label and progress bars too.