Java Reference
In-Depth Information
Display 18.16
paintComponent
Demonstration
(part 1 of 2)
1
import
javax.swing.JFrame;
2
import
javax.swing.JPanel;
3
import
java.awt.GridLayout;
4
import
java.awt.Graphics;
5
import
java.awt.Color;
6
public class
PaintComponentDemo
extends
JFrame
7{
8
public static final int
FRAME_WIDTH = 400;
9
public static final int
FRAME_HEIGHT = 400;
10
private class
FancyPanel
extends
JPanel
11
{
12
public void
paintComponent(Graphics g)
13
{
14
super
.paintComponent(g);
15
setBackground(Color.YELLOW);
16
g.drawOval(FRAME_WIDTH/4, FRAME_HEIGHT/8,
17
FRAME_WIDTH/2, FRAME_HEIGHT/6);
18
}
19
}
20
public static void
main(String[] args)
21
{
22
PaintComponentDemo w =
new
PaintComponentDemo();
23
w.setVisible(
true
);
24
}
25
public
PaintComponentDemo()
26
{
27
setSize(FRAME_WIDTH, FRAME_HEIGHT);
28
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
29
setTitle("The Oval Is in a Panel");
30
setLayout(
new
GridLayout(2, 1));
31
FancyPanel p =
new
FancyPanel();
32
add(p);
33
JPanel whitePanel =
new
JPanel();
34
whitePanel.setBackground(Color.WHITE);
35
add(whitePanel);
36
}
37
}
(continued)