package franck; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JOptionPane; /** * A grid consisting of a number of rows and columns. * Each cell of the grid can be set to a color. * * @author Franck van Breugel */ public class Grid extends JFrame { private class MyJPanel extends JPanel { public MyJPanel() { super(); } public void paintComponent(Graphics g) { super.paintComponent(g); for (int c = 0; c < columns; c++) { for (int r = 0; r < rows; r++) { if (colors[c][r] != null) { g.setColor(colors[c][r]); g.fill3DRect(c * size, r * size, size, size, true); } } } } } private MyJPanel panel; private Color[][] colors; private int columns; private int rows; private int size; /** * Default size of each cell of the grid. */ public static int DEFAULT_SIZE = 100; /** * Initializes this grid with the given number of columns and a single row * where the cells have the default size. * * @param columns the number of columns of this grid. */ public Grid(int columns) { this(columns, 1); } /** * Initializes this grid with the given number of rows and columns * where the cells have the default size. * * @param rows the number of rows of this grid. * @param columns the number of columns of this grid. */ public Grid(int columns, int rows) { super("Grid"); this.size = Grid.DEFAULT_SIZE; this.panel = new MyJPanel(); this.panel.setPreferredSize(new Dimension(columns * this.size, rows * this.size)); this.add(this.panel); this.colors = new Color[columns][rows]; this.columns = columns; this.rows = rows; this.pack(); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } /** * Set the cell with the given column and row number to the * given color. Note that the first column and first row have * number zero. * * @param column column number of the cell to be set. * @param row row number of the cell to be set. * @param color color of the cell. */ public void set(int column, int row, Color color) { this.colors[column][row] = color; this.getContentPane().validate(); this.getContentPane().repaint(); try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { // do nothing } } /** * Set the cell with the given column of the first row to the * given color. Note that the first column has number zero. * * @param column column number of the cell to be set. * @param color color of the cell. */ public void set(int column, Color color) { this.colors[column][0] = color; this.getContentPane().validate(); this.getContentPane().repaint(); try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { // do nothing } } /** * Sets the size of the cells to the given size. * * @param size the new size of the cells. */ public void setSize(int size) { this.size = size; } }