我在 JScrollPane 中有一个带有 GridBagLayout 的 JPanel。我在 JPanel 中还有一个“添加”按钮,单击该按钮将从 JPanel 中删除,将单独组件的新实例添加到 JPanel,然后将自身添加回 JPanel。这种类型的组件列表越来越多,然后是“添加”按钮。
添加新组件可以正常工作,JPanel 会伸展以适应新组件,并且 JScrollPane 的行为与预期一样,允许您滚动 JPanel 的整个长度。
这是添加的工作原理:
jPanel.remove(addButton);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
jPanel.add(new MyComponent(), c);
jPanel.add(addButton, c);
jPanel.validate();
jPanel.repaint();`
通过单击添加的组件本身内部的按钮来进行删除。他们将自己从 JPanel 中删除就好了。然而,JPanel 保持它的扩展大小,重新居中组件列表。
这是删除的工作原理:
Container parent = myComponent.getParent();
parent.remove(myComponent);
parent.validate();
parent.repaint();`
问题是,为什么我的 GridBagLayout JPanel 在添加组件时会调整大小,而在删除组件时却不会?