Alan Yu
Alan Yu

Reputation: 33

Java GridBayLayout replacing components

I am trying to delete multiple components in a JPanel using a GridBagLayout

javax.swing.SwingUtilities.invokeLater(new Runnable(){
    public void run(){
        createAndShowGUI();

        GamePanel gamePanel = new GamePanel(frame.getContentPane());
        gamePanel.delBlock(0, 0);
        gamePanel.delBlock(0, 1);

        frame.setContentPane(gamePanel);

    }
}); 

This is is the method for deleting a block

public void delBlock(int x, int y){

    int location = x * row + y;
    this.remove(location);

    this.revalidate();
    this.repaint();

}

As you can see the 2 blocks should be next to one another but this is what i get as a result.

enter image description here

Upvotes: 0

Views: 48

Answers (1)

camickr
camickr

Reputation: 324137

    gamePanel.delBlock(0, 0);
    gamePanel.delBlock(0, 1);

First you remove component at location 0. Then all the components shift 1 position in the Container.

Then you remove component at location 1. However, this the component that was at location 2, before you removed the first component.

Try:

    gamePanel.delBlock(0, 1);
    gamePanel.delBlock(0, 0);

to reverse the order in which you remove the components.

That is always remove components from the end of the container first.

As you can see the 2 blocks should be next to one another

I can't tell if you mean "next to" one another in a vertical sense or horizontal sense.

Given that the two components have been removed from the first column, it appears that you are building your grid in column order. That is you add all the components for column 1 and then column 2 and then column 3 etc.

If you want your components to be "beside" one another (in a horizontal sense) then you need to add the components in row order.

Upvotes: 2

Related Questions