所以我有這個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