我可以做一个随机按钮吗?

Can i make a random button?

我有一个制作游戏的学校项目,我正在尝试制作一个记忆游戏,但只能使用图像两次,并且需要它是随机的,这是我目前所拥有的。不知道如何为这个特定的东西使用随机,因为图像必须在整个游戏中保持不变,而随机使得这非常困难对不起格式,首先 post。

public class Juego  extends JFrame implements ActionListener{

JButton boton1 = new JButton();
JButton boton2 = new JButton();
JButton boton3 = new JButton();
JButton boton4 = new JButton();
JButton boton5 = new JButton();
JButton boton6 = new JButton();


public Juego(){
FlowLayout lay = new FlowLayout (); this.setLayout(lay); this.setDefaultCloseOperation(EXIT_ON_CLOSE);



this.setSize(1080, 1080); this.setTitle("Memoria"); 




this.setBackground(Color.black);
try {
Image img = ImageIO.read(getClass().getResource("/videojuegos/media/card-back.jpg"));
boton1.setIcon(new ImageIcon(img));
boton2.setIcon(new ImageIcon(img));
boton3.setIcon(new ImageIcon(img));
boton4.setIcon(new ImageIcon(img));
boton5.setIcon(new ImageIcon(img));
boton6.setIcon(new ImageIcon(img));



 } catch (IOException ex){}
boton1.addActionListener(this); this.add(boton1);boton2.addActionListener(this);this.add(boton2);boton3.addActionListener(this);this.add(boton3);boton4.addActionListener(this);this.add(boton4);boton5.addActionListener(this);this.add(boton5);boton6.addActionListener(this)this.add(boton6);






boton1.setActionCommand("boton1");


 boton2.setActionCommand("boton2");



boton3.setActionCommand("boton3");



boton4.setActionCommand("boton4");



 boton5.setActionCommand("boton5");



 boton6.setActionCommand("boton6");





 this.setVisible(true);

}

public void actionPerformed(ActionEvent e) {






if ("boton1".equals(e.getActionCommand())){
    try{
Image img = ImageIO.read(getClass().getResource("/videojuegos/media/card-back.jpg"));
Image img1 = ImageIO.read(getClass().getResource("/videojuegos/media/Fool.jpg"));
Image img2 = ImageIO.read(getClass().getResource("/videojuegos/media/empress"));
Image img3 = ImageIO.read(getClass().getResource("/videojuegos/media/lovers"));
boton1.setIcon(new ImageIcon(img1));
} catch (IOException ex){} 

}}}

您可以使用 ArrayList 保存图像集,然后使用 Random 以随机顺序将它们传输到另一个 ArrayList。例如:

Random rn = new Random();
ArrayList<Image> imageSet = importImages();
ArrayList<Image> randomizedSet = randomize(imageSet, rn);

public static ArrayList<Image> importImages() {
    ArrayList<Image> images = new ArrayList<>();
    // put some code here to add each image to images twice
    return images;
}

public static ArrayList<Image> randomize(ArrayList<Image> imageSet, Random rn) {
    ArrayList<Image> images = new ArrayList<>();
    while (!imageSet.isEmpty()) {
        images.add(imageSet.remove(rn.nextInt(imageSet.size())));
    }
    return images;
}

本例中的randomize()方法将从imageSet中随机删除一个元素并将其添加到images,如此做直到imageSet没有元素剩余。