Java Reference
In-Depth Information
This case study develops the
FigurePanel
class for displaying various figures.
Key
Point
This example develops a useful class for displaying various figures. The class enables the user
to set the figure type and specify whether the figure is filled, and it displays the figure on a
panel. The UML diagram for the class is shown in Figure 13.8. The panel can display lines,
rectangles, round-cornered rectangles, and ovals. Which figure to display is decided by the
type
property. If the
filled
property is
true
, the rectangle, round-cornered rectangle, and
oval are filled in the panel.
VideoNote
The
FigurePanel
class
javax.swing.JPanel
FigurePanel
LINE, RECTANGLE,
ROUND_RECTANGLE,
and
OVAL
are
constants, indicating the figure type.
+LINE = 1
+RECTANGLE = 2
+ROUND_RECTANGLE = 3
+OVAL = 4
-type: int
-filled: boolean
Specifies the figure type (default: 1).
Specifies whether the figure is filled (default: false).
+FigurePanel()
+FigurePanel(type: int)
+FigurePanel(type: int, filled: boolean)
+getType(): int
+setType(type: int): void
+isFilled(): boolean
+setFilled(filled: boolean): void
Creates a default figure panel.
Creates a figure panel with the specified type.
Creates a figure panel with the specified type and filled property.
Returns the figure type.
Sets a new figure type.
Checks whether the figure is filled with a color.
Sets a new filled property.
F
IGURE
13.8
FigurePanel
displays various types of figures on the panel.
The UML diagram serves as the contract for the
FigurePanel
class. The user can use the
class without knowing how the class is implemented. Let us begin by writing a program in
Listing 13.2 that uses the class to display six figure panels, as shown in Figure 13.9.
L
ISTING
13.2
TestFigurePanel.java
1
import
java.awt.*;
2
import
javax.swing.*;
3
4
public class
TestFigurePanel
extends
JFrame {
5
public
TestFigurePanel() {
6 setLayout(
new
GridLayout(
2
,
3
,
5
,
5
));
7 add(
new
FigurePanel(FigurePanel.LINE));
8 add(
new
FigurePanel(FigurePanel.RECTANGLE));
9 add(
new
FigurePanel(FigurePanel.ROUND_RECTANGLE));
10 add(
new
FigurePanel(FigurePanel.OVAL));
11 add(
new
FigurePanel(FigurePanel.RECTANGLE,
true
));
12 add(
new
FigurePanel(FigurePanel.ROUND_RECTANGLE,
true
));
13 }
14
15
public static void
main(String[] args) {
16 TestFigurePanel frame =
new
TestFigurePanel();
17 frame.setSize(
400
,
200
);
18 frame.setTitle(
"TestFigurePanel"
);
create figures