所以我有这个2d数组按钮,我有一个图像数组。我想获取按钮上的图像,但是我希望每次程序启动时图像都在随机按钮上。像这样:What I want it to look like。现在我只能通过在制作新的JButton时更改图标的值来在所有按钮上获取一种颜色。我认为我需要做的是将Math.Random()
设置为一个变量,并从图像数组中获得一个随机值,然后当我声明新的JButton
时将该变量放在icons[]
中,但我不知道这是否正确,并且不要不知道该怎么做。我做了一些搜索和使用这种尝试:Java GUI - 从数组中获得随机值
var randomValue = icons[Math.floor(Math.random() * icons.length)];
,但我得到一个错误说
possible loss of precision, required int, found double.
帮助将不胜感激。如果你想让我发布整个代码,请告诉我。
// 2D Array of buttons
buttons = new JButton[8][8];
for(int row=0; row<8; row++)
{
for (int col=0; col<8; col++)
{
buttons[row][col] = new JButton(icons[0]);
buttons[row][col].setLocation(6+col*70, 6+row*70);
buttons[row][col].setSize(69,69);
getContentPane().add(buttons[row][col]);
}
}
// Array of images
public static ImageIcon[] icons = {new ImageIcon("RedButton.png"),
new ImageIcon("OrangeButton.png"),
new ImageIcon("YellowButton.png"),
new ImageIcon("GreenButton.png"),
new ImageIcon("BlueButton.png"),
new ImageIcon("LightGrayButton.png"),
new ImageIcon("DarkGrayButton.png")};
尝试'randomValue =图标[(int)(Math.floor(Math.random()* icons.length))];' – exception1