0

你能做一个JFrame随机选择提供的三到四张图片作为背景的吗?因此,当用户打开 时JFrameJFrame将选择任何指定的图片作为背景。

我想要这样的东西:

ImageIcon background = new ImageIcon("First Image.png");
JLabel label = new JLabel(background);
frame.add(label);

第二张图:

ImageIcon background2 = new ImageIcon("Second Image.png");
JLabel label2 = new JLabel(background2);
frame.add(label2);

第三:

ImageIcon background3 = new ImageIcon("Third Image.png");
JLabel label3 = new JLabel(background3);
frame.add(label3);

也许是第四个:

ImageIcon background4 = new ImageIcon("Fourth Image.png");
JLabel label4 = new JLabel(background4);
frame.add(label4);

我想要一些代码,这样 JFrame 就可以使用这些代码中的任何一个。

另外,有没有办法随机更改 JFrame 标题?

就像我想要它一样:

'My Game: It's the best!'

...然后当用户再次打开 JFrame 时,标题将更改为,也许:

'My Game: Try it, it's new!'和/或

'My Game: You can play it easily!'和/或

'My Game: Find all the mysteries...'和/或

'My Game: Money don't go on trees!'和其他有趣的台词。

希望我让你容易理解!

4

2 回答 2

1

还请考虑Collections.shuffle()此处List<JLabel>此处List<Icon>

于 2013-03-11T13:28:19.163 回答
0

您可以使用java.util.Random类来生成随机数。

如果你想选择随机字符串/图像/图像路径,你可以声明一个数组并从中获取一个随机项。这是标题的示例代码:

//class level variable, supply your own lines.
final String[] TITLES = new String[]{"My Game: It's the best!", "My Game: Try it, it's new!"}

//next snippet is random title generation
//it's better to use only one random instance, 
//so you might want to declare this one on class level too
Random random = new Random(); 
int index = random.nextInt(TITLES.length); //get random index for given array.
String randomTitle = TITLES[index];
frame.setTitle(randomTitle);

您可以对图像路径/图像执行相同的操作。声明一个数组类型,通过随机索引获取一个对象:

final String[] IMAGE_PATHS = //initialization goes here

Random random = new Random(); 
String randomImagePath = IMAGE_PATHS[random.nextInt(IMAGE_PATHS.length)];
ImageIcon background = new ImageIcon(randomImagePath);
JLabel label = new JLabel(background);
于 2013-03-11T10:37:43.387 回答