18

In this piece of code:

JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);

I can see it makes a new label and adds it to the JFrame object frame. But I want to understand what does getContentPane() do, and why do I need it?

I read this API but I still didn't understand.

Jacob Raihle
  • 3,720
  • 18
  • 34
Bersan
  • 1,032
  • 1
  • 17
  • 28
  • Nice story: https://weblogs.java.net/blog/hansmuller/archive/2005/11/jframeadd_conte.html – Maroun May 24 '13 at 21:56
  • lool, that geek article xd – Bersan May 24 '13 at 22:08
  • "As a convenience `add` and its variants…have been overridden to forward to the `contentPane` as necessary."—[`JFrame`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html) – trashgod May 24 '13 at 23:17

4 Answers4

31

Every Swing top level container (and JInternalFrame) has what's called a JRootPane. This is responsible for actually managing the overall layout of the window.

enter image description here

The root pane has a number of layers, one of which is the content pane. When you add something to a frame (since Java 5 I think), it is automatically added to the content pane for you, before this, you had to call getContentPane().add(...) yourself

Take a look at How to use RootPanes

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
10

Every JPanel is a container, so either add it to a panel then add it to the container or directly use add(component) or use the getContentPane().add method. Both add the component to the container in Java 7 (I don't know if version 6 has a problem with this or not).

0xCursor
  • 2,242
  • 4
  • 15
  • 33
Caffe Latte
  • 1,693
  • 1
  • 14
  • 32
  • 2
    The [forwarding to the `contentPane`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html) feature appeared in Java 5. – trashgod May 24 '13 at 23:21
5

A container has several layers in it. You can think of a layer as a transparent film that overlays the container. In Java Swing, the layer that is used to hold objects is called the content pane. Objects are added to the content pane layer of the container.

The getContentPane() method retrieves the content pane layer so that you can add an object to it. The content pane is an object created by the Java run time environment. You do not have to know the name of the content pane to use it. When you use getContentPane(), the content pane object then is substituted there so that you can apply a method to it.

Jaimin Patel
  • 4,559
  • 3
  • 32
  • 35
2

A JFrame is the headcomponent which is put together with other subcomponents. With getContentPane() gets the component that represents the contents of a graphical user interface. A JMenuBar for example is placed in another area next to the contentPane of a frame.

Gary Klasen
  • 1,001
  • 1
  • 12
  • 30