import java.awt.event.*; import java.awt.*; import javax.swing.*; class JButtonGrid extends JPanel { int rows, cols; CellButton[][] grid; JButtonGrid(int rows, int cols, int prefferedButtonSize) { super(new GridLayout(rows, cols)); this.rows = rows; this.cols = cols; grid = new CellButton[cols][rows]; for (int i = 0; i < cols; i++) { for (int j = 0; j < rows; j++) { int column = i; int row = j; grid[i][j] = new CellButton(); grid[i][j].addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { grid[column][row].changeText(); System.out.printf("Celle på posisjon %d,%d%n", row, column); } } ); grid[i][j].setPreferredSize(new Dimension(prefferedButtonSize, prefferedButtonSize)); this.add(grid[i][j]); } } } private class CellButton extends JButton { private boolean alive = false; private CellButton() { super("X"); } private void changeText() { if (alive) { this.setText("X"); } else { this.setText("O"); } alive = !alive; } } }