Bersan
Bersan

Reputation: 3477

Java GUI: about getContentPane( ) method and content

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.

Upvotes: 18

Views: 96656

Answers (4)

Caffe Latte
Caffe Latte

Reputation: 1743

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).

Upvotes: 10

Jaimin Patel
Jaimin Patel

Reputation: 4637

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.

Upvotes: 5

MadProgrammer
MadProgrammer

Reputation: 347314

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

Upvotes: 31

Gary Klasen
Gary Klasen

Reputation: 1070

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.

Upvotes: 2

Related Questions