用户界面如何在JavaGUI中为按钮创建各种颜色?
我用这段代码在JavaGUI中创建了一系列按钮,正好是20个按钮,有20种不同的颜色。然而,不知何故,我不能,如果我使用这段代码,我会把所有20个按钮都涂成一种相同的颜色。如何在每个按钮中使用不同的颜色为它们着色?先谢谢你。注意,在代码中,我没有使用列出的数组
setTitle("My Frame");
setSize(500, 200);
setLayout(new GridLayout(0, 5));
int R = (int) (Math.random()*256);
int G = (int) (Math.random()*256);
int B = (int) (Math.random()*256);
Color color = new Color(R, G, B);
for (int i = 0; i < 20; i++)
{
JButton button = new JButton(Integer.toString(i));
setBackground(color);
add(button);
}
setVisible(true);
# 1 楼答案
变量
R
、G
、B
和随后的color
在循环for
开始之前被分配一个随机值。然后,在整个循环中,它们保留相同的值,因此所有按钮的颜色都相同尝试在循环的每个迭代中创建一个新的
Color
值:现在循环的每个迭代都会为
R
、G
、B
(和color
)获得自己不同的随机值# 2 楼答案