JAVA:填充框架的方法.add(),setContentPane(),getContentPane()

fro*_*hli 13 java jframe jtoolbar

我找到了三种方法来填充我的JFrame框架= new JFrame("...")createContentPanel返回一个JPanel,createToolBar返回一个ToolBar.

frame.add(this.createToolBar(), BorderLayout.PAGE_START); //this works and puts the ToolBar above and the ContentPanel under it<br>
frame.add(this.createContentPanel(), BorderLayout.CENTER);

frame.setContentPane(this.createContentPanel()); //this lets the JToolBar hover over the ContentPanel
frame.getContentPane().add(this.createToolBar()); 

frame.getContentPane().add(this.createContentPanel()); //this only puts the last one into the JFrame
frame.getContentPane().add(this.createToolBar());
Run Code Online (Sandbox Code Playgroud)

现在我想知道为什么我应该使用getContentPane()/ setContentPane()方法,如果我可以使用一个简单的frame.add(...)来填充我的框架.

Hov*_*els 8

你是对的,因为它们基本上都使用相同的代码,所以你使用哪个(JFrame#add(...)JFrame#getContentPane().add(...))并不重要,但是将来有时候你需要访问contentPane本身,例如你想要更改其边框,设置其背景颜色或确定其尺寸,因此您可能会在某些时候使用getContentPane(),因此了解它并熟悉它会很有帮助.