2014-03-07 50 views
0

所以我有這個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")}; 
+1

嘗試'randomValue =圖標[(int)(Math.floor(Math.random()* icons.length))];' – exception1

回答

1

我想通過把我的所有ImageIcons在一個ArrayList,號召ArrayList中java.util.Collections.shuffle(...),然後傳遞出來自洗牌ArrayList中ImageIcons爲了大大簡化這一點。或者如果你的按鈕允許重複的圖標,那麼使用一個java.util.Random變量,稱爲random,並簡單地調用random.nextInt(icons.length)來獲得我的數組的隨機索引。

順便說一句,爲了您自己的利益,請不要使用空白布局和絕對定位。你的JButton網格正在乞求在GridLayout中使用JPanel。乞討。


另外,爲什麼要在同一個項目上發佈問題,但使用不同的名稱?你在你的兩個其他職位已經類似的職位,但不同的用戶名在這裏:

+0

im不使用arraylist的原因是因爲這個程序是par這是一項任務,它要求我們這樣做。此外,我們被告知使用空佈局。那些實際上不是我的帖子順便說一句,我猜其他人也有麻煩的任務了。這實際上是我第一次使用這個網站,我今天剛剛做了我的帳戶。感謝您的提示,但! – user3390522

0

之前設置在JButton的圖標使用該隨機播放功能...

public ImageIcon[] shuffle(ImageIcon[] icons) 
{ 
    int index = 0; 
    ImageIcon temp = 0; 

    for(int i = icons.length -1; i > 0; i--) 
    { 
     index = r.nextInt(i + 1); 
     temp = icons[index]; 
     icons[index] = icons[i]; 
     icons[i] = temp; 
    } 
    return icons; 
}