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

2022-01-24 00:00:00 java jframe jtoolbar

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

I found three ways to fill my JFrame frame = new JFrame("...") createContentPanel returns a JPanel and createToolBar returns a 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());

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

And now I am wondering why should i use the getContentPane()/setContentPane() method if i could just use a simple frame.add(...) to fill my frame.

推荐答案

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

You are right that it doesn't matter which you use (JFrame#add(...) vs. JFrame#getContentPane().add(...)) since they both essentially call the same code, however there will be times in the future when you'll need access to the contentPane itself, such as if you want to change its border, set its background color or determine its dimensions, and so you'll likely use getContentPane() at some point, and thus getting to know it and be familiar with it would be helpful.

相关文章