替换GridBagLayout中的Component

Jul*_*ale 2 java swing awt jpanel layout-manager

我创建了一个从JPanel扩展的类,其布局属性是GridBagLayout.我基本上需要显示一个JLabel(网格)数组,但是一旦创建了组件我就无法替换它.我试图删除我想要更改的组件,然后放置新组件,但结果很奇怪.例如,我创建了一个10x10 JLabel的数组,并想用这段代码替换position [0] [0]和position [9] [9]:

//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();
Run Code Online (Sandbox Code Playgroud)

但只有位置[0] [0]看起来很好.我该怎么做才能更换一个组件?

在此输入图像描述

Mad*_*mer 6

GridBagLayout,每个组件都与之相关联GridBagConstraints.简单地移除组件并将其替换为位于相同位置的组件将不起作用,因为新组件将接收新组件GridBagConstraints

但是,您可以做的是获取与给定组件关联的约束.

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

这将使用与要删除的组件所使用的约束相同的约束来添加组件.

这当然都假定您正在分配gridx/ gridy约束......