Java Reference
In-Depth Information
You can construct a
JPanel
object with no parameters, or you can specify the lay-
out manager to use. Once you've constructed the panel, you can add components to it
using its
add
method:
// creates a JPanel container with a FlowLayout
JPanel panel = new JPanel(new FlowLayout());
panel.add(new JButton("button 1"));
panel.add(new JButton("button 2"));
A common strategy is to use a
BorderLayout
for the frame, then add panels to
some or all of its five regions. For example, the following code produces a window
that looks like a telephone keypad, using a panel with a
GridLayout
in the center
region of the frame and a second panel with a
FlowLayout
in the south region of
the frame:
1 // A GUI that resembles a telephone keypad.
2
3
import
java.awt.*;
4
import
javax.swing.*;
5
6
public class
Telephone {
7
public static void
main(String[] args) {
8 JFrame frame =
new
JFrame();
9 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
10 frame.setSize(
new
Dimension(250, 200));
11 frame.setTitle("Telephone");
12
13 frame.setLayout(
new
BorderLayout());
14
15 // main phone buttons
16 JPanel centerPanel =
new
JPanel(
new
GridLayout(4, 3));
17
for
(
int
i = 1; i <= 9; i++) {
18 centerPanel.add(
new
JButton("" + i));
19 }
20 centerPanel.add(
new
JButton("*"));
21 centerPanel.add(
new
JButton("0"));
22 centerPanel.add(
new
JButton("#"));
23 frame.add(centerPanel, BorderLayout.CENTER);
24
25 // south status panel
26 JPanel southPanel =
new
JPanel(
new
FlowLayout());
27 southPanel.add(
new
JLabel("Number to dial: "));
28 southPanel.add(
new
JTextField(10));
29 frame.add(southPanel, BorderLayout.SOUTH);
Search WWH ::
Custom Search