如何将四个图像之一随机分配给一个字段

时间:2018-11-11 21:59:16

标签: java

因此,我正在为JAVA类决赛做一个项目。在分配过程中,有一个问题问我如何将四个图像(我拥有的花朵图像)之一分配给我的 Flower 构造函数中的 image 字段。但是我似乎并不了解这个要求。有人可以帮我吗?我将不胜感激。这是我的代码。另外,我的老师给了我们一个提示,我们应该为此使用“ if”语句。

import java.awt.Point;
import javax.swing.ImageIcon;

public class Flower {
    private ImageIcon image; 
    private Point pos; 

    public Flower(int x, int y) {
        pos = new Point(x,y); 
    }

}

2 个答案:

答案 0 :(得分:0)

生成0到4之间的随机数将为您解决问题。 假设您拥有的4张图像为ImageIcon类型的数组形式。 如果数组的名称为list_flowers。 您的构造函数可以是-

word = input("Enter a word to be tested: ")

for character in word:
        if character[0] == character.lower() and character[1:] != character.lower:
            result = False
            print(result)

答案 1 :(得分:0)

首先,您需要更改Flower,以便将要使用的图像传递给它。

public class Flower {
    private ImageIcon image; 
    private Point pos; 

    public Flower(ImageIcon image, int x, int y) {
        pos = new Point(x,y); 
    }

}

个人事物,但我更喜欢这种方式,因为可以对初始化类的结果进行推理。

一种解决方案是利用Java API中的可用功能。因为我很懒,所以这意味着要使用Collections.shuffle来“随机化”对象列表。

它可能像....

 List<ImageIcon> images = new ArrayList<>(4);
 images.add(new ImageIcon(...)); // Flower 1
 images.add(new ImageIcon(...)); // Flower 2
 images.add(new ImageIcon(...)); // Flower 3
 images.add(new ImageIcon(...)); // Flower 4

 for (int index = 0; index < numberOfFlowersToCreate; index++) {
     int xPos = ...; // Calculate x position
     int yPos = ...; // Calculate y position

     Collections.shuffle(images);
     ImageIcon image = images.get(0);
     Flower flower = new Flower(image, xPos, yPos);

     // Do something with the instance of Flower
 }