花了一天,发现了一个怪现象,两个及其简单的界面程序一个用了setContentPane(),另一个用了getContentPane().add(),后者能显示,但前者显示不出来:
程序一:
public class MyFrame extends JFrame {
private JPanel myPanel = null; public static void main(String[] args) {
MyFrame myFrame = new MyFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
} public MyFrame() {
super();
initialize();
} private void initialize() {
this.setSize(300, 200);
myPanel = new JPanel();
myPanel.add(new Button());
this.getContentPane().add(myPanel);
this.setTitle("JFrame");
this.getContentPane().removeAll();
this.getContentPane().add(myPanel);
}
}程序二:
public class MyFrame extends JFrame {
private JPanel myPanel = null; public static void main(String[] args) {
MyFrame myFrame = new MyFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
} public MyFrame() {
super();
initialize();
} private void initialize() {
this.setSize(300, 200);
myPanel = new JPanel();
myPanel.add(new Button());
this.setContentPane(myPanel);
this.setTitle("JFrame");
this.getContentPane().removeAll();
this.setContentPane(myPanel);
}
}
觉得很奇怪,为什么会有这样的不同?按理说当我把所有component去掉后再加入都是一样的显示的啊