JAVA: Ways to fill a Frame. add(), setContentPane(), getContentPane()

froehli picture froehli · Jun 26, 2011 · Viewed 27.4k times · Source

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());

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.

Answer

Hovercraft Full Of Eels picture Hovercraft Full Of Eels · Jun 26, 2011

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.