2
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class Concentration extends JFrame implements ActionListener {

    private JButton buttons[][]=new JButton[4][4];
    int i,j,n;      

    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);            
        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();                    
                panel.add(buttons[i][j]);
                buttons[i][j].addActionListener(this);
            }
        }
        add(panel);
        pack();
        setVisible(true);       
    }

    public void actionPerformed(ActionEvent e) {            
        buttons[i][j].setIcon(new ImageIcon(
                 getClass().getResource("/images/2.jpg")));
    }

    public static void main(String args[]){
        new Concentration();
    }    
}

This is my code. I am making memory game. I want to make that, each time clicked a button, that button shows image but

 buttons[i][j].addActionListener(this);

in that, methot can not take i and j and doesnot show any image.

But for example when i do

 buttons[2][2].addActionListener(this);

it shows only in 2x2 . image. What can i do to solve that?

john brown
  • 55
  • 1
  • 1
  • 5

2 Answers2

3

Possible solutions:

  • Inside the ActionListener, iterate through the button array to see which JButton in the array matches the button that was pressed, obtained by calling e.getSource()
  • Give your JButtons actionCommand Strings that correspond to i and j
  • Create a separate ActionListener implementing class that has i and j fields that can be set via a constructor, and give each button a unique ActionListener with i and j set.
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
2

Try this code:

public void actionPerformed(ActionEvent e) {
    if(e.getSource() instanceof JButton){
        JButton pressedButton = (JButton) e.getSource();
        if(pressedButton.getIcon() == null){
            pressedButton.setIcon(new ImageIcon(getClass().getResource("/images/2.jpg")));
        } else {
            pressedButton.setIcon(null);
        }
    }
}

Direct form EventObject javadoc:

public Object getSource()

The object on which the Event initially occurred.

Returns: The object on which the Event initially occurred.

This means there's no need to know the array indexes of pressed button as it could be known through getSource() method.

dic19
  • 17,821
  • 6
  • 40
  • 69