Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 多色网格_Java_Grid - Fatal编程技术网

Java 多色网格

Java 多色网格,java,grid,Java,Grid,我的任务是为3种不同类型的益智游戏制作一个游戏生成器。我只需要完成最后一场比赛,这场比赛非常精彩。我已经使用充满按钮的GridLayout制作了网格 我只需要在所有按钮上应用7种不同的颜色。我以前试过使用这个代码: String[] backgroundColors = {"CYAN","PINK","YELLOW"}; int number = (int)(Math.random() * 3); String c = (backgroundColors[number]); (然后

我的任务是为3种不同类型的益智游戏制作一个游戏生成器。我只需要完成最后一场比赛,这场比赛非常精彩。我已经使用充满按钮的GridLayout制作了网格

我只需要在所有按钮上应用7种不同的颜色。我以前试过使用这个代码:

String[] backgroundColors = {"CYAN","PINK","YELLOW"};  
int number = (int)(Math.random() * 3);  
String c = (backgroundColors[number]);  
(然后在我将按钮添加到窗格后,我添加了以下内容:)

结果失败了。 我想也许我应该使用和数组,但我搜索了一下,不幸的是没有找到任何。 请帮助我使用随机颜色生成器,最好使用数组。

您可以使用

Color[] backgroundColors = {Color.RED,Color.GREEN,Color.BLUE};  
int number = (int)(Math.random() * 3);  
Color c = (backgroundColors[number]); 

.setBackgroundColor()是否使用字符串参数?如果它不起作用,我猜它使用了一个Color类型的参数。你导入颜色库了吗?如果不是,要访问颜色,您必须使用Color类,并使用Color.CYAN访问颜色,例如,您可以这样做

Color[] backgroundColors = {Color.CYAN,Color.PINK,Color.YELLOW};  
int number = (int)(Math.random() * 3);  
Color c = (backgroundColors[number]); 
buttonBejeweled.setBackgroundColor(c);

Java中的按钮没有方法
setBackgroundColor
,而是
。setBackground(Color c)
我建议您在Java中查找有关Color类的文档。+1 setBackgroundColor()用于Android中的视图。Swing组件只有setBackground()方法。谢谢miNde!非常感谢您的帮助这是我使用BlueJ时的错误消息:找不到符号-方法setBackgroundColor(java.awt.Color)我已经导入了必要的包,我只是想知道为什么它不为单个按钮执行背景色。此方法工作得非常好。感谢现在唯一的问题是颜色是随机生成的,而不是单独生成的。意思是如果颜色是黄色,那么它们都是黄色的。你知道如何解决这个问题吗?如果你想让每个按钮都是单独的颜色,我要做的是创建一个你想使用的按钮数组,循环中的每个按钮只需循环使用随机数、颜色分配,“buttonBejewled”将变成“ButtonArray.get(I).setBackgroundColor(c)因此,每次需要新按钮颜色时,您必须为每个按钮指定一种颜色,而不是只执行一次功能。试试看。
Color[] backgroundColors = {Color.CYAN,Color.PINK,Color.YELLOW};  
int number = (int)(Math.random() * 3);  
Color c = (backgroundColors[number]); 
buttonBejeweled.setBackgroundColor(c);