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");
   ...
contentPane.add(stopButton);

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:

buttonPanel.add(stopButton);

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();
    guiWithPanel.setVisible(true);
  }

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

    buttonPanel.setLayout(new FlowLayout());

    JButton stopButton = new JButton("Red");
    stopButton.setBackground(Color.red); 
    stopButton.addActionListener(this);
    buttonPanel.add(stopButton);

    JButton goButton = new JButton("Green");
    goButton.setBackground(Color.green);
    goButton.addActionListener(this); 
    buttonPanel.add(goButton);

    contentPane.add(buttonPanel, BorderLayout.SOUTH);
  }

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

    if (e.getActionCommand().equals("Red"))
      contentPane.setBackground(Color.red);
    else if (e.getActionCommand().equals("Green"))
      contentPane.setBackground(Color.green);
    else
      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:

 stopButton.addActionListener(this);

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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020