我可以随机制作一个按钮吗?

时间:2016-05-10 22:45:52

标签: java button random imagebutton

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

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){} 

}}}

1 个答案:

答案 0 :(得分:1)

您可以使用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没有剩余元素为止。