Java GUI - 从数组中获取随机值

时间:2014-03-07 00:45:03

标签: java arrays user-interface random

所以我有这个2D数组按钮,我有一个图像数组。我想在按钮上获取图像,但我希望每次程序启动时图像都在随机按钮上。像这样:What I want it to look like。现在,当我制作新的JButton时,通过更改图标的值,我只能在所有按钮上获得一种颜色。我认为我需要做的是将Math.Random()设置为变量并从图像数组中获取随机值,然后在我声明新icons[]时将变量放在JButton中但我不知道这是否正确,不知道该怎么做。我做了一些搜索并尝试使用它:

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")};

2 个答案:

答案 0 :(得分:1)

通过将所有ImageIcons放在ArrayList中,在ArrayList上调用java.util.Collections.shuffle(...),然后按顺序从洗牌后的ArrayList中传出ImageIcons,我会大大简化这个。或者,如果您的按钮允许重复图标,则使用java.util.Random变量,例如调用random并简单地调用random.nextInt(icons.length)以获取我的数组的随机索引。

顺便说一句,请为自己的利益,不要使用空布局和绝对定位。您的JButtons网格要求使用JPanel保存在GridLayout中。乞。


顺便说一句,为什么你在同一个项目上发布问题但使用不同的名字?您在此处的其他帖子中都有类似的帖子,但用户名不同:

答案 1 :(得分:0)

在JButton上设置图标之前,请使用此shuffle函数...

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;
}