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);
}
}
}
I want to make a memory game. when clicked 2 images, they will show to user (at first all of them are null). But in ActionListener how can I take buttons[i][j] i j variables because I need that index to compare if they are same. I need images' places to hold and compare 2 image. I need to access images[] array to compare I guess but how can I use in an ActionListener?