繁体   English   中英

如何从Java中的二维按钮数组中随机选择一个按钮?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM