import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;

public class ButtonGui extends JFrame {
    JButton[][] buttons;
    Random random = new Random();

    public static void main(String[] args) {
        new ButtonGui().run();
    }

    private void run() {
        buttons = new JButton[2][2];
        createGui();
        attachListeners();
        pack();
        setVisible(true);
    }

    private void createGui() {
        setLayout(new GridLayout(2, 2));
        for (int i = 0; i < buttons.length; i++) {
            for (int j = 0; j < buttons[i].length; j++) {
                buttons[i][j] = new JButton(" ");
                add(buttons[i][j]);
            }
        }
    }
    private void attachListeners() {
        ActionListener listener = new MyButtonListener();
        for (int i = 0; i < buttons.length; i++) {
            for (int j = 0; j < buttons[i].length; j++) {
                buttons[i][j].addActionListener(listener);
            }
        }
    }

    class MyButtonListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            JButton theButton = (JButton)e.getSource();
            Color color = getRandomColor();
            theButton.setBackground(color);
            for (int i = 0; i < buttons.length; i++) {
                for (int j = 0; j < buttons[i].length; j++) {
                    if (buttons[i][j] == theButton) {
                        System.out.println("Button at " + i + " " + j);
                    }
                }
            }
        }

        private Color getRandomColor() {
            Color color = new Color(random.nextInt(255),
                                    random.nextInt(255),
                                    random.nextInt(255));
            return color;
        }  
    }    
}
