Java Reference
In-Depth Information
Display 17.11
Using Panels
(part 2 of 4)
22
public
PanelDemo()
23
{
24
super
("Panel Demonstration");
25
setSize(WIDTH, HEIGHT);
26
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
27
setLayout(
new
BorderLayout());
28
JPanel biggerPanel =
new
JPanel();
29
biggerPanel.setLayout(
new
GridLayout(1, 3));
30
greenPanel =
new
JPanel();
31
greenPanel.setBackground(Color.LIGHT_GRAY);
32
biggerPanel.add(greenPanel);
33
whitePanel =
new
JPanel();
34
whitePanel.setBackground(Color.LIGHT_GRAY);
35
biggerPanel.add(whitePanel);
36
grayPanel =
new
JPanel();
37
grayPanel.setBackground(Color.LIGHT_GRAY);
38
biggerPanel.add(grayPanel);
39
add(biggerPanel, BorderLayout.CENTER);
40
JPanel buttonPanel =
new
JPanel();
41
buttonPanel.setBackground(Color.LIGHT_GRAY);
42
buttonPanel.setLayout(
new
FlowLayout());
43
JButton greenButton =
new
JButton("Green");
44
greenButton.setBackground(Color.GREEN);
An object of the class
PanelDemo
is the action
listener for the buttons in
that object.
45
greenButton.addActionListener(
this
);
46
buttonPanel.add(greenButton);
47
JButton whiteButton =
new
JButton("White");
48
whiteButton.setBackground(Color.WHITE);
49
whiteButton.addActionListener(
this
);
50
buttonPanel.add(whiteButton);
51
JButton grayButton =
new
JButton("Gray");
52
grayButton.setBackground(Color.GRAY);
53
grayButton.addActionListener(
this
);
54
buttonPanel.add(grayButton);
55
add(buttonPanel, BorderLayout.SOUTH);
56
}