Java: Content Panes

Description

Before Java 2 each top-level container had only one layer. Java 2 top-level containers (JFrame, JApplet, ...) have several layers (panes): root, content, layered, and glass. Programs normally reference only the content pane. There are two programming idioms for using the content pane: (1) using the preassigned pane (recommended), or (2) building your own pane.

Naming convention

It is common to name the content pane content or contentPane.

Idiom 1: Use the existing content pane

Each container has a preconstructed content pane of class Container. You can get this pane and add the components to it. For example,

class MyWindow extends JFrame {
    . . .
    MyWindow() {   // constructor
        Container content = getContentPane();  // Use the default content pane.
        content.add(...);
        content.add(...);
        . . .

All JFrames already have a content pane, so there's no need to create a new one, just get the existing pane. And if you're wondering about the Container type, it's a superclass of JPanel. In fact, if you look at the actual type of the object that's currently returned by getContentPane(), it really is a JPanel, altho you can't count on this in the future, of course.

Sometimes programmers don't bother to copy the content pane reference into a new variable, resulting in code like this. Since there are typically a large number of references to the content pane, this seems awkward.

class MyWindow extends JFrame {
    . . .
    MyWindow() {   // constructor
        getContentPane().add(...);
        getContentPane().add(...);
        . . .

Idiom 2: Create your own content pane

It's common to create a new panel for the content pane and tell the window to use this new panel for it's content pane. For example,

class MyWindow extends JFrame {
    . . .
    MyWindow() {   // constructor
        JPanel content = new JPanel();  // Create a new content pane.
        content.add(...);
        content.add(...);
        . . .
        setContentPane(content);