JScrollPane 中的 GridBagLayout 无法正确调整大小
我有一个 JPanel,其中 JScrollPane 内有一个 GridBagLayout。我在 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 在添加组件时会调整大小,但在删除组件时不会调整大小?
I have a JPanel with a GridBagLayout inside of a JScrollPane. I also have an 'add' button within the JPanel which, when clicked, will be removed from the JPanel, adds a new instance of a separate component to the JPanel, then adds itself back to the JPanel. This sort of makes a growing list of components, followed by the 'add' button.
Adding new components works fine, the JPanel stretches to accommodate the new components, and the JScrollPane behaves as expected, allowing you to scroll through the entire length of the JPanel.
This is how the add works:
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();`
Removal works by clicking a button inside the added components themselves. They remove themselves from the JPanel just fine. However, the JPanel keeps it's stretched-out size, re-centering the list of components.
This is how removal works:
Container parent = myComponent.getParent();
parent.remove(myComponent);
parent.validate();
parent.repaint();`
The question is, why does my GridBagLayout JPanel resize when adding components, but not when removing components?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须重新验证并重新绘制 JScrollPane,这是一个示例:
You have to revalidate and repaint the JScrollPane, here is an example: