你可以制作JFrame
只是随机选择提供的三到四张图片作为背景。因此,当用户打开JFrame
时,JFrame
会选择任何所声明的图片作为背景。
我想要这样的事情:
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!'
和其他有趣的行。
希望我能让你轻松理解!
答案 0 :(得分:1)
另请考虑Collections.shuffle()
,List<JLabel>
为here,List<Icon>
为here。
答案 1 :(得分: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);