import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ButtonGrid implements ActionListener
{
NTJFrame frame = new NTJFrame("Grid and Buttons");
JButton[][] buttons = new JButton[4][4];
ImageIcon[] icons = new ImageIcon[6];
int turn = 0;
public ButtonGrid()
{
JPanel gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(4,4));
for (int i = 0; i < icons.length; i++)
icons[i] = new ImageIcon("" + i + ".jpg");
for (int i = 0; i < buttons.length; i++)
for (int j = 0; j < buttons[i].length; j++)
{
if (i % 2 == 0)
buttons[i][j] = new JButton(icons[(j+1)%2]);
else
buttons[i][j] = new JButton(icons[j%2]);
gridPanel.add(buttons[i][j]);
buttons[i][j].addActionListener(this);
}
frame.getContentPane().add(gridPanel);
frame.setVisible(true);
}
public static void main(String[] args)
{
new ButtonGrid();
}
public void actionPerformed(ActionEvent e)
{
for (int i = 0; i < buttons.length; i++)
for (int j = 0; j < buttons[i].length; j++)
if (e.getSource() == buttons[i][j])
if (turn % 2 == 0)
if ((i % 2 == 0 && j % 2 == 0) || ( i % 2 == 1 && j % 2 == 1))
buttons[i][j].setIcon(icons[2]);
else
buttons[i][j].setIcon(icons[4]);
else
if ((i % 2 == 0 && j % 2 == 0) || ( i % 2 == 1 && j % 2 == 1))
buttons[i][j].setIcon(icons[3]);
else
buttons[i][j].setIcon(icons[5]);
turn++;
}
}
|