O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required