[英]How to randomly choose a button from a 2d array of buttons in java?
我已經制作了2個JButton數組
public JButton[][] buttons = new JButton[5][5];
並創建了一個for循環,使這些按鈕25次
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
buttons[i][j] = new JButton();
panel.add(buttons[i][j]);
}
}
}
現在我想做的是從上面創建的按鈕中隨機選擇一個按鈕,並將其文本設置為我定義的內容,我已經嘗試過這種方法,但是它不起作用,只能從3個按鈕中進行選擇,而不能從其余按鈕中進行選擇。
int r = (int) (Math.random());
buttons[r][r].setText(button[random][random].getName());
因此,基本上,我希望從數組中選擇一個隨機按鈕,並將其值更改為其名稱。 另外,當我打印按鈕的名稱時,我該如何打印出字符串中按鈕的名稱。
謝謝。
表達式(int) (Math.random())
始終求值為0,因為Math.random()
返回范圍為[0, 1)
Math.random()
的雙精度數-這樣的雙精度數在轉換為整數時始終會產生0。
而是,創建一個新的Random對象,並使用Random.nextInt(n)
在范圍內選擇適當的值。 例如,
Random r = new Random();
int i = r.nextInt(5); // chooses 0, 1, .. 4
int j = r.nextInt(5);
JButton b = buttons[i][j];
b.setText(b.getName());
(但您可能不希望Component.getName()
..)
您需要選擇一個隨機數組,然后選擇一個隨機索引,以確保您不會超出單個數組中任何一個的范圍。
//create buttons first
Random random = new Random();
JButton[] buttons randomButtonsArray = buttons[random.nextInt(buttons.length)];
JButton randomButton = randomButtonsArray[random.nextInt(randomButtonArray.length)];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.