我正在尝试用 Java 创建一个记忆游戏。像这样的东西,但更简单-> http://www.zefrank.com/memory/
这是我的代码:
import javax.swing.*;
public class Memoriin {
public static void main(String[] args) {
JFrame frame = new MemoriinFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
和:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class MemoriinFrame extends JFrame {
private static final long serialVersionUID = 1L;
public static final int DEFAULT_HEIGHT = 600;
public static final int DEFAULT_WIDTH = 800;
public JButton button[] = new JButton[8];
ArrayList<ImageIcon> icons = new ArrayList<ImageIcon>();
ImageIcon tail = new ImageIcon("foto.jpg");
ImageIcon photo1 = new ImageIcon("foto1.jpg");
ImageIcon photo2 = new ImageIcon("foto2.jpg");
ImageIcon photo3 = new ImageIcon("foto3.jpg");
ImageIcon photo4 = new ImageIcon("foto4.jpg");
ImageIcon photo1copy = photo1;
ImageIcon photo2copy = photo2;
ImageIcon photo3copy = photo3;
ImageIcon photo4copy = photo4;
public MemoriinFrame() {
setTitle("Memory Game");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
setLayout(new GridLayout(2, 4));
addIcons();
for(int i = 0; i <= 7; i++) {
button[i] = new JButton();
button[i].setIcon(tail);
button[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
performActionEventHandler();
}
});
add(button[i]);
}
}
public void performActionEventHandler() {
// how can I link each button with a specific picture?
}
public void addIcons() {
icons.add(photo1);
icons.add(photo2);
icons.add(photo3);
icons.add(photo4);
icons.add(photo1copy);
icons.add(photo2copy);
icons.add(photo3copy);
icons.add(photo4copy);
Collections.shuffle(icons);
}
public void tailToImage(JButton button) {
button.setIcon(icons.get(0));
icons.remove(0);
}
}
所以,我正在尝试将按钮与特定图片链接。我试图这样做,但我得到了一个不必要的结果:如果我点击一个按钮,那么图片就会变成一张随机图片。但是我有 8 个按钮和 8 张图片,我想将它们链接起来,以便每个按钮在整个游戏过程中都与同一张图片一起使用。
PS 英语不是我的母语。