Java Reference
In-Depth Information
populate the frame. But some less-educated folk, and those in a hurry, often added compon-
ents 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 back-
ground and sits over the top of the
ContentPane
; its primary use is in temporarily painting
something over the top of the main
ContentPane
. Because of this, you need to use the
JFrame
's
getContentPane()
method:
public
public class
class
ContentPane
ContentPane
extends
extends
JFrame
{
public
public
ContentPane
() {
Container cp
=
getContentPane
();
// now add Components to "cp"...
cp
.
add
(
new
new
JLabel
(
"A Really Simple Demo"
,
JLabel
.
CENTER
));
}
}
You can add any number of components (including containers) into this existing container,
using the
ContentPane add()
method:
public
public class
class
JFrameDemo
JFrameDemo
extends
extends
JFrame
{
private
private static
static final
final
long
long
serialVersionUID
= -
3089466980388235513L
;
JButton quitButton
;
/** Construct the object including its GUI */
public
public
JFrameDemo
() {
super
super
(
"JFrameDemo"
);
Container cp
=
getContentPane
();
cp
.
setLayout
(
new
new
FlowLayout
());
cp
.
add
(
quitButton
=
new
new
JButton
(
"Exit"
));
// Set up so that "Close" will exit the program,
// not just close the JFrame.
setDefaultCloseOperation
(
JFrame
.
EXIT_ON_CLOSE
);
// This "action handler" will be explained later in the chapter.
quitButton
.
addActionListener
(
new
new
ActionListener
() {
public
public
void
void
actionPerformed
(
ActionEvent e
) {
setVisible
(
false
false
);
dispose
();
System
.
exit
(
0
);