Java Reference
In-Depth Information
The Swing version of panel is
JPanel
. You can use
new JPanel()
to create a panel with
a default
FlowLayout
manager or
new JPanel(LayoutManager)
to create a panel with
the specified layout manager. Use the
add(Component)
method to add a component to the
panel. For example, the following code creates a panel and adds a button to it:
JPanel p =
new
JPanel();
p.add(
new
JButton(
"OK"
));
Panels can be placed inside a frame or inside another panel. The following statement places
panel
p
in frame
f
:
f.add(p);
Listing 12.6 gives an example that demonstrates using panels as subcontainers. The program
creates a user interface for a microwave oven, as shown in Figure 12.10.
Frame
Content panel
Button
Panel
p2
Panel
p1
F
IGURE
12.10
The program uses panels to organize components.
L
ISTING
12.6
TestPanels.java
1
import
java.awt.*;
2
import
javax.swing.*;
3
4
public class
TestPanels
extends
JFrame {
5
public
TestPanels() {
6
// Create panel p1 for the buttons and set GridLayout
7
8
9
10
// Add buttons to the panel
11
for
(
int
i =
1
; i <=
9
; i++) {
12
JPanel p1 =
new
JPanel();
panel p1
p1.setLayout(
new
GridLayout(
4
,
3
));
p1.add
(
new
JButton(
""
+ i));
13 }
14
15 p1.add(
new
JButton(
""
+
0
));
16 p1.add(
new
JButton(
"Start"
));
17 p1.add(
new
JButton(
"Stop"
));
18
19
// Create panel p2 to hold a text field and p1
20
21 (
new
JTextField(
"Time to be displayed here"
),
22 BorderLayout.NORTH);
23
JPanel p2 =
new
JPanel(
new
BorderLayout());
panel p2
p2.add
p2.add
(p1, BorderLayout.CENTER);
24
25
// Add contents to the frame
26 add(p2, BorderLayout.EAST);
27 add(
new
JButton(
"Food to be placed here"
),
28 BorderLayout.CENTER);
29 }
30
add p2 to frame