0

JFrame提供された 3 ~ 4 枚の写真を背景としてランダムに選択するを作成できますか。そのため、ユーザーが を開くとJFrame、 はJFrame指定された画像のいずれかを背景として選択します。

私はそれを次のようにしたい:

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

そして2番目の写真:

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

第3:

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

そしておそらく4番目:

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 に答える