Java 语言规范的第 6.8 节包含包、方法、字段和常量等项的命名约定。关于常量名的子节(6.8.5)声明常量不应使用小写字母,但从一开始, Color 类中的全部颜色常量如 red 、 green 和 blue 就是以全小写指定的。Merlin 也直接开了个先例,现在以全大写提供相同的常量。现在尚不反对使用旧名称,但在您的 1.4 程序中您可以使用较新的名称。
我们将为测试程序创建一个颜色常量数组和一个对这些颜色常量进行循环的计数程序,然后提供一个 changeBackground() 方法,该方法按两个方向的其中一个方向对这些颜色常量进行循环(请参阅“清单 3”)。
清单 3. 更改背景色
1 private static final Color colors[] = {
2 Color.BLACK,
3 Color.BLUE,
4 Color.CYAN,
5 Color.DARK_GRAY,
6 Color.GRAY,
7 Color.GREEN,
8 Color.LIGHT_GRAY,
9 Color.MAGENTA,
10 Color.ORANGE,
11 Color.PINK,
12 Color.RED,
13 Color.WHITE,
14 Color.YELLOW
15 };
16 static int colorCounter;
17
18 private static final int UP = 1;
19 private static final int DOWN = 2;
20 private static void changeBackground(JFrame frame, int direction) {
21 // See bug 4475240
22 // w/o bug, change background of getContentPane()
23 button.setBackground(colors[colorCounter]);
24 // Update counter based on direction
25 if (direction == UP) {
26 colorCounter++;
27 } else {
28 --colorCounter;
29 }
30 // Wrap colors
31 if (colorCounter == colors.length) {
32 colorCounter = 0;
33 } else if (colorCounter < 0) {
34 colorCounter = colors.length-1;
35 }
36 }
37
2 Color.BLACK,
3 Color.BLUE,
4 Color.CYAN,
5 Color.DARK_GRAY,
6 Color.GRAY,
7 Color.GREEN,
8 Color.LIGHT_GRAY,
9 Color.MAGENTA,
10 Color.ORANGE,
11 Color.PINK,
12 Color.RED,
13 Color.WHITE,
14 Color.YELLOW
15 };
16 static int colorCounter;
17
18 private static final int UP = 1;
19 private static final int DOWN = 2;
20 private static void changeBackground(JFrame frame, int direction) {
21 // See bug 4475240
22 // w/o bug, change background of getContentPane()
23 button.setBackground(colors[colorCounter]);
24 // Update counter based on direction
25 if (direction == UP) {
26 colorCounter++;
27 } else {
28 --colorCounter;
29 }
30 // Wrap colors
31 if (colorCounter == colors.length) {
32 colorCounter = 0;
33 } else if (colorCounter < 0) {
34 colorCounter = colors.length-1;
35 }
36 }
37
向您的 main() 例程添加对 changeBackground() 方法的调用。
在其它类如 GridBagLayout 中也对命名约定进行了更新, GridBagLayout 类包括几个 protected 方法如 AdjustForGravity() ,这些 protected 方法现在已被修改为以小写字母开头。