我在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在添加组件时会调整大小,但在删除组件时却没有?
答案 0 :(得分:1)
您必须重新验证并重新绘制JScrollPane,这是一个示例:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingTest {
public static void main(String[] args) {
final JPanel panel = new JPanel(new GridBagLayout());
for (int i = 0; i < 25; i++) {
JTextField field = new JTextField("Field " + i, 20);
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridy = i;
panel.add(field, constraints);
}
final JScrollPane scrollPane = new JScrollPane(panel);
JButton removeButton = new JButton("Remove Field");
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (panel.getComponentCount() >= 1) {
panel.remove(panel.getComponentCount() - 1);
scrollPane.revalidate();
scrollPane.repaint();
}
}
});
JFrame frame = new JFrame("Swing Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(640, 480);
frame.setLocation(200, 200);
frame.getContentPane().add(scrollPane);
frame.getContentPane().add(removeButton, BorderLayout.SOUTH);
frame.setVisible(true);
}
}