Search code examples
javacolorsgraphics2d

Java - Change the color of some squares created with Graphics2D


I just want to create a simple game with 100 x 100 square, each square is 5 pixels.

I created a class:

public class Draw extends JComponent{
    private List<Graphics2D> recList = new ArrayList<Graphics2D>();
    public void paint(Graphics g) {
        //THIS TO SET (0,0) PANEL START AT BOTTOM LEFT
        Graphics2D g2 = (Graphics2D)g;
        AffineTransform at = g2.getTransform();
        at.translate(0, getHeight());
        at.scale(1, -1);
        g2.setTransform(at);

        //THIS TO DRAW ALL THE SQUARES
        for (int i = 0;i<100;i++){
            for (int j=0;j<100;j++){
                g2.setColor(Color.red);
                g2.drawRect(5*i, 5*j, 5, 5);
                recList.add(g2); //Store each square to the list to change the color
            }
        }
    }
}

Then I just drag it to the design windows of netbeans and the squares are painted, looks good...

But it seems like I made a wrong move. At the first time I wanted to get a specific square from the list using their location, but the Graphic2d doesn't have any method to get the location (x and y) or to change the color.

I don't know if there is any other way I can make it come true? PS: One more thing, can I set the location of each square to its center?


Solution

  • You could create your own Tile class, which stores info such as x, y, width, height, and color. Each Tile object could also be in charge of painting itself:

    class Tile {
        private int x, y, width, height;
        private Color color;
    
        public Tile(int x, int y, int width, int height, Color color) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.color = color;
        }
    
        public void paint(Graphics g) {
            g.setColor(color);
            g.fillRect(x, y, width, height);
        }
    }
    

    Create the tiles before-hand:

    List<Tile> tiles = ...;
    
    void createTiles() {
        for(int x = 0; x < 100; x++) {
            for(int y = 0; y < 100; y++) {
                Color color = ...; //choose color
                int size = 5;
                int tileX = x * size;
                int tileY = y * size;
                tiles.add(new Tile(tileX, tileY, size, size, color));
            }
        }
    }
    

    Then render by passing the graphics object to them in the paint method:

    void paint(Graphics g) {
        tiles.forEach(tile -> tile.paint(g));
    }