Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Displaying GUI Components

Problem

You want to create some GUI components and have them appear in a window.

Solution

Create a JFrame and add the components to its ContentPane.

Discussion

The older Abstract Windowing Toolkit (AWT) had a simple frame component that allowed you to add components directly to it. “Good” programs always created a panel to fit inside the frame, and populated that. But some less-educated heathens often added components directly to the frame. The Swing JFrame is more complex; it comes with not one but two containers already constructed inside it. The ContentPane is the main container; you should normally use it as your JFrame’s main container. The GlassPane has a clear background and sits over the top of the ContentPane; its primary use is in temporarily painting something over top of the main ContentPane. Because of this, you need to use the JFrame’s getContentPane( ) method:

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

public class ContentPane extends JFrame {
    public ContentPane(  ) {
        Container cp = getContentPane(  );
        // now add Components to "cp"...
    }
}

Then you can add any number of components (including containers) into this existing container, using the Container’s add( ) method:

import java.awt.*; import java.awt.event.*; import javax.swing.*; /** Just a Frame */ public class JFrameDemo extends JFrame { boolean unsavedChanges = false; JButton quitButton; /** Construct the object including its GUI */ public JFrameDemo( ) { super("JFrameDemo"); getContentPane( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata