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