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英語は私の母国語ではありません。