2014-03-07 113 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; 
}