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 张图片时,它们将显示给用户(起初它们都是空的)。但是在 ActionListener 中,我如何获取 button[i][j] ij 变量,因为我需要该索引来比较它们是否相同。我需要图像的位置来保存和比较 2 个图像。我想我需要访问 images[] 数组来进行比较,但是如何在 ActionListener 中使用?