如何在JavaGUI中为按钮创建各种颜色?
我用这段代码在JavaGUI中创建了一系列按钮,正好是20个按钮,有20种不同的颜色。然而,不知何故,我不能,如果我使用这段代码,我会把所有20个按钮都涂成一种相同的颜色。如何在每个按钮中使用不同的颜色为它们着色?先谢谢你。注意,在代码中,我没有使用列出的数组如何在JavaGUI中为按钮创建各种颜色?,java,user-interface,Java,User Interface,我用这段代码在JavaGUI中创建了一系列按钮,正好是20个按钮,有20种不同的颜色。然而,不知何故,我不能,如果我使用这段代码,我会把所有20个按钮都涂成一种相同的颜色。如何在每个按钮中使用不同的颜色为它们着色?先谢谢你。注意,在代码中,我没有使用列出的数组 setTitle("My Frame"); setSize(500, 200); setLayout(new GridLayout(0, 5)); int R = (int
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);
setTitle(“我的框架”);
设置大小(500200);
setLayout(新的GridLayout(0,5));
int R=(int)(Math.random()*256);
int G=(int)(Math.random()*256);
intb=(int)(Math.random()*256);
颜色=新颜色(R、G、B);
对于(int i=0;i<20;i++)
{
JButton button=新JButton(Integer.toString(i));
挫折背景(颜色);
添加(按钮);
}
setVisible(真);
变量R
、G
、B
,以及随后的color
,在的循环开始之前,被分配一个随机值。然后,在整个循环中,它们保留相同的值,因此所有按钮的颜色都相同
尝试在循环的每次迭代中创建一个新的颜色值:
for (int i = 0; i < 20; i++)
{
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);
JButton button = new JButton(Integer.toString(i));
setBackground(color);
add(button);
}
for(int i=0;i<20;i++)
{
int R=(int)(Math.random()*256);
int G=(int)(Math.random()*256);
intb=(int)(Math.random()*256);
颜色=新颜色(R、G、B);
JButton button=新JButton(Integer.toString(i));
挫折背景(颜色);
添加(按钮);
}
现在循环的每次迭代都会为R
、G
、B
(和color
)获得自己不同的随机值;
设置大小(500200);
setLayout(新的GridLayout(0,5));
对于(int i=0;i<20;i++)
{
int R=(int)(Math.random()*256);
int G=(int)(Math.random()*256);
intb=(int)(Math.random()*256);
颜色=新颜色(R、G、B);
JButton button=新JButton(Integer.toString(i));
挫折背景(颜色);
添加(按钮);
}
setVisible(真);
谢谢,它马上就起作用了!我现在觉得自己很笨,犯了一个像这样的新手错误。。。
setTitle("My Frame");
setSize(500, 200);
setLayout(new GridLayout(0, 5));
for (int i = 0; i < 20; i++)
{
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);
JButton button = new JButton(Integer.toString(i));
setBackground(color);
add(button);
}
setVisible(true);