Replace Component in GridBagLayout

I created a Class that extends from JPanel which layout property is GridBagLayout. I basically need to display an array of JLabels (grid) but i'm not able to replace a component once it's created. I've tried to remove the component that I want to change, and then place the new one but the result is weird. For example i've created an array of 10x10 JLabels and want to replace position[0][0] and position[9][9] with this code:

//At first i have the jpanel layout completely filled

this.remove(0);
this.add((JLabel) start, 0);  //This was created with GridBagLayout.gridx = 0 and GridBagLayout.gridy = 0 and it's fine

this.remove(99);
this.add((JLabel) end, 99); //This was created with GridBagLayout.gridx = 9 and GridBagLayout.gridy = 9 and it's out of grid
this.revalidate();

But only position[0][0] looks fine. What should i do to replace a component?

enter image description here

Upvotes: 2

Views: 4441

Answers (2)

I solve my problem by using:

this.setComponentZOrder(newItem, 0);

So, I actually didn't remove the object on Jpanel but I placed the new one over the old object.

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347314

In GridBagLayout, each component is associated with GridBagConstraints. Simple removing a component and replacing it with a component at the same position won't work, as the new component will receive a new GridBagConstraints

What you can do, however, is get the constraints associated with a give component.

Component toRemove = getComponent(0);
GridBagLayout layout = (GridBagLayout)getLayout();
GridBagConstraints gbc = layout.getConstraints();
remove(toRemove);
add(new JLabel("Happy"), gbc, 0);

This will add the component using the same constraints as those used by the component you are removing.

This of course all assumes that you are assigning the gridx/gridy constraints...

Upvotes: 6

Related Questions