Java getContentPane()

Sheeraz Gul Apr 01, 2022
Java getContentPane()

In Java Swing, a container has multiple layers in it, and the layer used to hold the objects is called the content pane. This content pane is implemented through getContentPane() method.

The objects are added to the content pane layer of a particular container. This tutorial demonstrates how to use getContentPane() in Java.

Demonstrate the Use of the GetContentPane() in Java

The content pane layer is retrieved by the getContentPane() method, where we can add objects. The content pane itself is an object created by the Java run time environment.

We do not need to know the name of any content pane to use it. The content pane object is substituted in the container when we use the getContentPane() method; after this substitution, we can apply any method to it.

Let’s see some examples:

package delftstack;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Get_Content_Pane {
    public static void main(String[] args) {
        JFrame demo_frame = new JFrame("GetContentPane");
        final JLabel demo_label = new JLabel("Hello! This is delftstack..");
        // Use getContentPane()


The code above shows the simple use of getContentPane, which creates a JFrame with a JLabel.



Let’s try another example:

package delftstack;

import java.awt.Container;
import javax.swing.*;

public class Get_Content_Pane {
	public static void main(String[] args) {
	    JFrame Demo_Frame = new JFrame("GetContentPane");
	    Container Demo_Content_Pane = Demo_Frame.getContentPane();

	    JButton button1 = new JButton("Button1");
	    JButton button2 = new JButton("Button2");

	    button1.setBounds(10, 10, 200, 30);
	    button2.setBounds(250, 10, 150, 40);

	    Demo_Frame.setBounds(0, 0, 500, 150);

The code above creates a JFrame with two buttons of different sizes using getContentPane.


GetContentPane 2

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - Java Swing