I am trying to implement a game using the ACM graphics. For the game, I am trying to make the main frame a Grid of Cells.
I made a Grid class which extends GCanvas:
import acm.graphics.GCanvas; public class Grid extends GCanvas{ private final static int WIDTH = 300; private final static int HEIGHT = 300; private final int DIMENSION = 5; Cell[][] grid; public Grid(){ super(); setSize(WIDTH, HEIGHT); this.setLocation(50, 50); grid = new Cell[DIMENSION][DIMENSION]; int dimension = Cell.getDimension(); int rWidth = dimension; int rHeight = dimension; for (int i=0; i<DIMENSION; i++) { for (int j=0; j<DIMENSION; j++) { grid[i][i] = new Cell(); add(grid[i][i], rWidth+dimension, rHeight+dimension); rWidth+=dimension; } rHeight+=dimension; rWidth = dimension; } }
I made a Cell class which extends GRect:
import java.awt.Color; import acm.graphics.GRect; public class Cell extends GRect{ private final static int WIDTH =50; private final static int HEIGHT = 50; public Cell(){ super(WIDTH, HEIGHT); this.setColor(Color.RED); this.setFillColor(Color.GRAY); this.setFilled(true); } public static int getDimension(){ return WIDTH; }
I was able to make the Grid be a grid of Cells (a grid of colored GRects).
However, when I try to add a Grid to my main frame in the run() method, the Grid is added so that the left side of it is about in the middle of the frame.
Here is the code for my main frame:
public class Game extends GraphicsProgram{ private static final long serialVersionUID = 1L; public static final int WIDTH = 160; public static final int HEIGHT = WIDTH/12 *9; public static final int SCALE = 5; public static final String NAME = "Game"; public void run(){ setSize(WIDTH*SCALE,HEIGHT*SCALE); Grid grid = new Grid(); add(grid); } }
So, keeping in mind that a Grid is basically a GCanvas, I tried to just add a GCanvas to the main frame instead of a Grid. Unfortunately, I received the same problem.
Does anyone know why the GCanvas will only add to the middle of the main frame?
I tried doing something like:
GCanvas canvas = new GCanvas(); canvas.setLocation(50,50);
But that did not change anything.