【问题标题】:Java GUI - Getting random value from arrayJava GUI - 从数组中获取随机值
【发布时间】:2014-03-08 15:52:00
【问题描述】:

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

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 = icons[(int)(Math.floor(Math.random() * icons.length))];

标签: java arrays user-interface random


【解决方案1】:

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

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


顺便说一句,您为什么要针对同一个项目发布问题但使用不同的名称?您在此处的其他两个帖子中都有相似的帖子,但用户名不同:

【讨论】:

  • 我不使用数组列表的原因是因为这个程序是分配的一部分,它要求我们这样做。此外,我们被告知使用空布局。顺便说一句,这些实际上不是我的帖子,我猜其他人也遇到了问题。这实际上是我第一次使用这个网站,我今天刚刚注册了我的帐户。不过感谢您的提示!
【解决方案2】:

在您设置 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-09
    • 2018-06-19
    • 1970-01-01
    • 2022-10-08
    • 2010-12-11
    相关资源
    最近更新 更多