private JButton buttons[][] = new JButton[4][4];
int i, j, n, index = 0, calc = 0;
public int open = 0;
private JButton opens[] = new JButton[1];
public ImageIcon images[] = new ImageIcon[20];
public Concentration()
{
super ("Concentration");
JFrame frame = new JFrame();
setSize(1000, 1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4, 4));
panel.setSize(400, 400);
// Getting images
for (i = 0; i < 8; i++) {
images[i] = new ImageIcon(getClass().getResource("/images/1 ("+i+").jpg"));
}
// Copying images for game
for (i = 8; i < 16; i++) {
images[i] = images[i - 8];
}
// Shuffling
Random random = new Random();
int k;
ImageIcon imageTemp;
for (i = 0; i < 16; i++) {
k = random.nextInt(16);
imageTemp = images[i];
images[i] = images[(i + k) % 16];
images[(i + k) % 16] = imageTemp;
}
for (i = 0; i < buttons.length; i++) {
for (j = 0; j < buttons[i].length; j++) {
n = i * buttons.length + buttons[i].length;
buttons[i][j] = new JButton();
buttons[i][j].setIcon(null);
/*
* I made null instad of putting images because if i put images,
* at start it shows all. but how will i take parameters to
* actionlistener? for comparing if same?
*/
//images[i*buttons.length+j]
panel.add(buttons[i][j]);
buttons[i][j].addActionListener(this);
}
}
add(panel);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
JButton pressedButton = (JButton) e.getSource();
if (pressedButton.getIcon() == null) {
pressedButton.setIcon();
// How will it take from array? another class?
} else {
pressedButton.setIcon(null);
}
}
}
メモリーゲームを作りたいです。2 つの画像をクリックすると、ユーザーに表示されます (最初はすべて null です)。しかし、ActionListener では、buttons[i][j] ij 変数をどのように取得できますか。それらが同じかどうかを比較するには、そのインデックスが必要だからです。2つの画像を保持して比較するには、画像の場所が必要です。比較するために images[] 配列にアクセスする必要がありますが、ActionListener でどのように使用できますか?