【发布时间】:2014-03-08 15:52:00
【问题描述】:
所以我有这个二维按钮数组和图像数组。我想在按钮上获取图像,但我希望每次程序启动时图像都出现在随机按钮上。像这样:What I want it to look like。现在,当我制作新的 JButton 时,通过更改图标的值,我只能在所有按钮上获得一种颜色。我认为我需要做的是将Math.Random() 设置为一个变量并从图像数组中获取一个随机值,然后当我声明新的JButton 时将变量放入icons[] 但我不知道如果这是正确的并且不知道该怎么做。我做了一些搜索并尝试使用它:
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 = icons[(int)(Math.floor(Math.random() * icons.length))];
标签: java arrays user-interface random