Changing the Grid Size in a GridBagLayout
-
27-10-2019 - |
Question
I am just trying to add 3 centered vertical buttons to a GridBagLayout in java swing. Right now I believe the default grid size is 3x3. I wanted to know if I can change that and add more columns and rows. I simply want to make 3 centered equally spaced butons in a pane.
pane.setLayout(new GridLayout(10,1));
// Insert a space before the first button
for (int i = 1; i < 6; i++ ){
pane.add(new JLabel(""));
}
pane.add(new Button("1"));
pane.add(new Button("2"));
pane.add(new Button("3"));
// Insert a space after the last button
pane.add(new JLabel(""));
That was the final solution Thanks everyone!
Solution
I agree with @Chris a GridLayout
would be easier:
myPanel.setLayout(new GridLayout(5,1));
// Insert a space before the first button
add(new JLabel(""));
add(new Button("1"));
add(new Button("2"));
add(new Button("3"));
// Insert a space after the last button
add(new JLabel(""));
OTHER TIPS
Simply add more values to the weights attributes. This tells it how to lay out the gridbag - 0 means use only the space needed, then the rest of the space is split up according to the weights given.
GridBagLayout gbl = new GridBagLayout();
...
gbl.columnWeights = new double[] {1.0, 1.0, 1.0, 1.0, Double.MIN_VALUE};
gbl.rowWeights = new double[] {1.0, 1.0, 1.0, 1.0, Double.MIN_VALUE};
...
contentPane.setLayout(gbl_contentPane);
And then give your items GridBagConstraints
with gridx
and gridy
set appropriately (from 0) for the new columns/rows:
GridBagConstraints gbc = new GridBagConstraints();
...
gbc.gridx = 3;
gbc.gridy = 3;
...
contentPane.add(textFieldName, gbc_textFieldName);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow