Java Reference
In-Depth Information
Self-Test Exercises
12. How would you modify the class definition in Display 17.6 so that the window
produced by the no-argument constructor is magenta instead of pink?
13. Rewrite the following two lines from Display 17.6 so that the label does not
have the name
aLabel
or any other name.
Hint
: Use an anonymous object.
JLabel aLabel =
new
JLabel("Close-window button works.");
add(aLabel);
Display 17.6
A
JFrame
with Color
(part 1 of 2)
1
import
javax.swing.JFrame;
2
import
javax.swing.JLabel;
3
import
java.awt.Color;
4
public class
ColoredWindow
extends
JFrame
5 {
6
public static final int
WIDTH = 300;
7
public static final int
HEIGHT = 200;
8
public
ColoredWindow(Color theColor)
9 {
10
super
("No Charge for Color");
11 setSize(WIDTH, HEIGHT);
12 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13 getContentPane().setBackground(theColor);
14 JLabel aLabel =
new
JLabel("Close-window button works.");
15 add(aLabel);
16 }
17
public
ColoredWindow()
18 {
19
This is an invocation of the
other constructor.
this
(Color.BLUE);
20 }
21 }
This is the file
ColoredWindow
java
.
1
import
java.awt.Color;
This is the file
ColoredWindow
java
.
2
public class
DemoColoredWindow
3 {
4
public static void
main(String[] args)
5 {
6 ColoredWindow w1 =
new
ColoredWindow();
7 w1.setVisible(
true
);
8 ColoredWindow w2 =
new
ColoredWindow(Color.GRAY);
9 w2.setVisible(
true
);
10 }
11 }
(continued)