import java.awt.Color; import java.awt.Graphics; import javax.swing.JComponent; public class JBoxGrid extends JComponent { private final Box[][] boxes; private final int boxwidth; private final int boxheight; public JBoxGrid(int width, int height, int boxwidth, int boxheight) { boxes = new Box[height][width]; for (int y = 0; y < height; y++) { for (int i = 0; i < width; i++) { boxes[y][i] = new Box(); } } this.boxheight = boxheight; this.boxwidth = boxwidth; setSize(width * boxwidth, height * boxheight); } @Override public void paint(Graphics g) { super.paint(g); for (int y = 0; y < boxes.length; y++) { for (int x = 0; x < boxes[y].length; x++) { g.setColor(Color.BLACK); g.drawRect(x * boxwidth, y * boxheight, boxwidth, boxheight); g.setColor(boxes[y][x].color); g.fillRect(x * boxwidth + 1, y * boxheight + 1, boxwidth - 2, boxheight - 2); } } } public void setBackgroundColor(int x, int y, Color color) { boxes[y][x].color = color; } } class Box { public Color color = Color.GRAY; }