当该addComponents()
方法运行一次时,我得到了所需的 JPanel 布局。但是,当里面的代码addComponents()
被多次执行时,JPanel 的布局就完全错误了。有什么我似乎做错了吗?
public class DeleteStudent extends JPanel {
public SearchPanel search = new SearchPanel();
private final JButton deleteButton = new JButton("Delete from database");
private GridBagConstraints cons = new GridBagConstraints();
private final GridBagLayout gridBag = new GridBagLayout();
public DeleteStudent() {
super();
setLayout(gridBag);
setPreferredSize(new Dimension(400, 300));
addComponents();
addComponents(); //Method fails when run more than once!
}
public void addComponents() {
cons.gridy = 1;
cons.insets = new Insets(50, 0, 0, 0);
gridBag.setConstraints(deleteButton, cons);
removeAll();
add(search);
add(deleteButton);
update();
}
private void update() {
revalidate();
repaint();
}
截图:
1次方法调用后的JPanel:http: //img402.imageshack.us/img402/6409/oncer.png
2 次方法调用后的 JPanel:http: //imageshack.us/scaled/landing/254/twiced.png