Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Container Classes

Fill all the glasses there, for why Should every creature drink but I, Why, man of mortals, tell me why?
Abraham Cowley, Anacreon

When you use Swing to make a GUI such as the windows we have been defining, you build new classes for the GUI out of already existing classes. There are two principal ways to build new GUI classes out of old classes. You can use inheritance. For example, to build a window interface, you normally use the Swing class JFrame and make your window a derived class of JFrame. The second way to make new classes out of old classes is to use one of the Swing classes as a container and to place components in the container. (Technically speaking, adding components to a container class does not necessarily make it a new class. However, the way that we advocate adding components is in the class constructor; so for all practical purposes it will produce a new class. In any event, this is a technical detail that need not concern you when first learning about Swing. For our purposes, we will think of adding components as producing a new class.)

For example, in the class ButtonDemo (Display 12) we added a button to the window as follows:

JButton stopButton = new JButton("Red");

You do not choose between these two ways of building a GUI. In almost all cases, you use both of these techniques when you define a GUI class.

In this section, we will look at the class Jpanel, which is often used to define subparts of a window. We then go on to discuss the general properties of container classes such as JPanel and the content pane of JFrame.

The JPanel Class

A GUI is often organized in a hierarchical fashion, with window-like containers inside of other window-like containers. In this section, we introduce a new class that facilitates this organization: The class JPanel is a very simple container class that does little more than group objects. It is one of the simplest of container classes, but one you will use frequently. A JPanel object is little more than an area of the screen into which you put other objects, such as buttons and labels. The JPanel object may then be put in the content pane of a JFrame. Thus, one of the main functions of JPanel objects is to subdivide a JFrame into different areas. These JPanel objects are usually simply called panels when we want a shorter, less-formal term. The judicious use of panels can affect the arrangement of components in a window as much as the choice of a layout manager. For example, suppose you use a BorderLayout manager; then you can place components in each of the five locations: BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.EAST, BorderLayout.WEST, and BorderLayout.CENTER. But what if you want to put two components at the bottom of the screen, in the BorderLayout.SOUTH position? To get two components in the BorderLayout.SOUTH position, you put the two components in a panel and then place the panel in the BorderLayout.SOUTH position.

Display 13 contains a slight variation of the program in Display 12. In Display 13, we have placed the buttons in a panel called buttonPanel, so that the portion of the window with the buttons does not change color when the rest of the window changes color. As was true for the program in Display 12, when you click the "Red" button in the GUI in Display 13, the window's color changes to red, and, similarly, the color changes to green when you click the "Green" button. But in Display 13, the buttons are in a separate panel that is white and that does not change color. As you can see, you use a layout manager and the method add with a JPanel object in exactly the same way that you do for the content pane of a JFrame. The buttons are placed in the panel with add, as in the following example:


and then the JPanel is placed in the JFrame with add as follows:

contentPane.add(buttonPanel, BorderLayout.SOUTH);

Note that the content pane (contentPane) and the panel (buttonPanel) each have their own layout manager.

Display 13—Putting the Buttons in a Panel

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

 *Simple demonstration of putting buttons in a panel.
public class PanelDemo extends JFrame implements ActionListener
  public static final int WIDTH = 300;
  public static final int HEIGHT = 200;

  public static void main(String[] args)
    PanelDemo guiWithPanel = new PanelDemo();

  public PanelDemo()
    setSize(WIDTH, HEIGHT);
    addWindowListener(new WindowDestroyer()); 
    setTitle("Panel Demonstration"); 
    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    JPanel buttonPanel = new JPanel();

    buttonPanel.setLayout(new FlowLayout());

    JButton stopButton = new JButton("Red");

    JButton goButton = new JButton("Green");

    contentPane.add(buttonPanel, BorderLayout.SOUTH);

  public void actionPerformed(ActionEvent e) 
    Container contentPane = getContentPane();

    if (e.getActionCommand().equals("Red"))
    else if (e.getActionCommand().equals("Green"))
      System.out.println("Error in button interface.");

Be sure to notice that you add things to a JFrame and JPanel in slightly different ways. With a JFrame, you first get the content pane with getContentPane and then use the method add with the content pane. With a JPanel, you use the method add directly with the JPanel object. There is no content pane to worry about with a JPanel.

Notice how the action listeners are set up. Each button registers the this parameter as a listener, as in the following line:


Because the line appears inside of the constructor for the class PanelDemo, the this parameter refers to PanelDemo, which is the entire window interface. Thus, the entire window container is the listener, not the JPanel. (Remember that PanelDemo is the window with the JPanel. It is not itself the JPanel.) So, when you click the button labeled "Red", it is the background of the bigger window that turns red. The panel with the buttons always stays white.

Note that because it is the PanelDemo class that is the listener for button-clicking events, it is PanelDemo that implements ActionListener and has the method actionPerformed.

There is also one other small but new technique, introduced in Display 13. In that class, we gave each button a color, as well as giving colors to the panel and the content pane. This was done with the method setBackground in basically the same way that we did in previous examples. The only new thing to note is that you can give a button or almost any other item a color using setBackground.

You can add one JPanel to another JPanel using the method add, and each JPanel can have a different layout manager. With a hierarchy of panels to build it this way, you can create almost any sort of arrangement of components inside of a GUI.

The Container Class

There is a predefined class called Container. Any descendent class of the class Container can have components added to it (or, more precisely, can have components added to objects of the class). The class JFrame is a descendent class of the class Container, so any descendent class of the class JFrame can serve as a container to hold labels, buttons, panels, or other components.

Similarly, the class JPanel is a descendent of the class Container; any object of the class JPanel can serve as a container to hold labels, buttons, other panels, or other components. The Container class is in the AWT library and not in the Swing library. This is not a major issue, but does mean that you need to import the awt package when using the Container class. So any class definition that contains a reference to the class Container must contain the following import statement:

import java.awt.*;

A container class is any descendent class of the class Container. Any descendent class of the class JComponent is called a JComponent, or sometimes more simply a component. You can add any JComponent object to any container class object.

The class JComponent is derived from the class Container, and so you can add a JComponent to another JComponent. Sometimes, this will turn out to be a good idea, and sometimes it is something to avoid. We will discuss the different cases as we go along. The classes Component, Frame, and Window are AWT classes that some readers may have heard of. We include them for reference value, but we will have no need for these classes.

There are two ways that you can add a JComponent to a container. One way is the way we added components to a JFrame: You first obtain the content pane of the JFrame using the method getContentPane. Then, you add components to the content pane using the method add. Another way is the way we add items to a JPanel: With a JPanel, you directly use the method add with the JPanel. With a JPanel, there is no content pane to worry about. How do you decide which of these two approaches (with or without getContentPane) you need to use? For each container class, you must either memorize which approach to use or look it up. (Some who are more familiar with Swing might contend that there is an "easier" way to determine whether or not you use getContentPane with container classes. They would say that you use getContentPane with a container, whenever the container class implements the RootPaneContainer interface. That is correct as far as it goes, but to find out if the class implements the RootPaneContainer class, you must either memorize that fact or look it up.)

If you only use the classes discussed in this article, then it is easy to decide. With objects of the class JFrame (including objects of any derived class of JFrame), you use getContentPane. None of the other container classes discussed in this article use getContentPane.

When you are dealing with a Swing container class, you have three kinds of objects to deal with: The container class itself (probably some sort of window-like object), the components you add to the container (such as labels, buttons, and panels), and a layout manager, which is an object that positions the components inside the container. We have seen examples of these three kinds of objects in almost every JFrame class we have defined. Almost every complete GUI interface you build, and many subparts of the GUIs you build, will be made up of these three kinds of objects.

Java Tip: Guide for Creating Simple Window Interfaces

Most simple windowing GUIs follow a pattern that is easy to learn and that will get you started with Swing. Here is an outline of some of the main points we've seen so far:

  1. A typical GUI consists of some windowing object that is derived from the class JFrame and that contains a number of components, such as labels and buttons.

  2. When the user clicks the close-window button, the window should close, but this will not happen correctly unless your program registers a window listener to close the window. One way to accomplish this is to add the following to the GUI class definition within a constructor definition:

    addWindowListener(new WindowDestroyer());

    You can use the definition of WindowDestroyer given in Display 2.

  3. You can group components together by placing the components in a JPanel and adding the JPanel to the GUI.

  4. The GUI (that is, the JFrame) and each JPanel in the GUI should be given a layout manager using the method setLayout.

  5. If any of the components, such as a button, generate action events, then you need to make the GUI (or some other class) an action listener. Every component that generates an action event should have an action listener registered with it. You register an action listener with the method addActionListener.

  6. In order to make your windowing GUI (or other class) into an action listener, you need to add the following to the beginning of the class definition:

    implements ActionListener
  7. You also need to add a definition of the method actionPerformed to the class.

This is not the only way to create a GUI window class, but it shows a simple and common way to do it, and it is basically the only way we know of so far.

  • + Share This
  • 🔖 Save To Your Account