Reputation: 385
I'm making a simple game where a user clicks to remove buttons, but I'm having some trouble with my GridBagLayout resizing when the buttons are removed.
The default window looks like this:
When one button is clicked, it is removed:
However, when every button in a row / column is removed, the gridbag resizes and the buttons get bigger:
Is there a way I can prevent this behavior from happening? I.e. adding padding to the gridbag to keep all the columns / rows distributed as they were originally with whitespace in the unfilled areas?
Additionally, here is some of my code:
public void actionPerformed(ActionEvent e)
{
// if we're not selecting multiple buttons and we're not clicking
// the "select multiple" checkbox
if ( !multiSelectState && e.getActionCommand() != "Select Multiple" )
{
JButton button = (JButton)e.getSource();
p.remove(button);
p.revalidate();
p.repaint();
}
}
Upvotes: 0
Views: 390
Reputation: 324128
Is there a way I can prevent this behavior from happening?
You could use a GridLayout
. Then you can just use:
button.setVisible( false );
and the space will be reserved in the grid.
Otherwise you would need to reserve the space in the grid by adding a dummy component to the grid (the GridBagLayout does not include invisible components in the layout).
One option would be to replace the button with an empty panel, so the code might be something like:
JPanel panel = new JPanel();
panel.setPreferredSize( button.getPreferredSize() );
GridBagLayout layout = (GridBagLayout)p.getLayout();
GridBagConstraints gbc = layout.getConstraints( button );
p.remove(button);
p.add(panel, gbc);
p.revalidate();
p.repaint();
Another way would be to use a panel with a CardLayout. Then this panel would contain your JButton and an empty JPanel.
Then instead of removing the JButton from the layout, you just swap the button and display the empty panel. Read the section from the Swing tutorial on How to Use CardLayout for more information.
Upvotes: 3