Reputation: 65
I am trying to use my fillCell method to be able to change the color based on what color was put in the parameter, however i dont know how to utilize graphics to change the color and repaint it and i am not importing objectdraw for this. I am trying to do this for a snake game i am trying to create. The class is meant to draw the grid, color the snake's body and head as well as clear the end of the snake and color the obstacles . So far i have:
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import java.awt.event.*;
public class GraphicsGrid extends JPanel
{
private ArrayList<Point> fillCells;
private int wid, hei, pix;
/**
* Creates an arraylist and sets the default width, height and pixel
* for a grid.
*/
public GraphicsGrid() {
fillCells = new ArrayList<Point>();
wid = 400;
hei = 400;
pix = 10;
}
/**
* Creates an arraylist and sets the inputted width, height and pixel
* for a grid.
* @param width size of the width for the grid
* @param height size of the height for the grid
* @param pixel size for each cell
*/
public GraphicsGrid(int width, int height, int pixel) {
fillCells = new ArrayList<Point>();
wid = width;
hei = height;
pix = pixel;
}
/**
* fills and paints the current cell and creates the grid with lines
* @param g creates an instance of graphics that has been imported
*/
@Override
protected synchronized void paintComponent(Graphics g) {
super.paintComponent(g);
for (Point fillCell : fillCells) {
int cellX = (fillCell.x * pix);
int cellY = (fillCell.y * pix);
g.setColor(Color.GREEN);
g.fillRect(cellX, cellY, pix, pix);
}
g.setColor(Color.BLACK);
g.drawRect(0, 0, wid*pix, hei*pix);
for (int i = 0; i < wid*pix; i += pix) {
g.drawLine(i, 0, i, hei*pix);
}
for (int i = 0; i < hei*pix; i += pix) {
g.drawLine(0, i, wid*pix, i);
}
}
/* *
* adds a point to the cell and repaints the cell
* @param x x-coordinate of the cell
* @param y y-coordinate of the cell
*/
public void fillCell(int x, int y, Color block) {
Graphics g = new Graphics();
super.paintComponent(g);
fillCells.add(new Point(x, y));
if(block.equals("black"))
{
g.setColor(Color.BLACK);
repaint();
}
else if(block.equals("red"))
{
g.setColor(Color.RED);
repaint();
}
else if(block.equals("white"))
{
g.setColor(Color.WHITE);
repaint();
}
else
{
g.setColor(Color.Green);
repaint();
}
repaint();
}
I cannot create another class file for this program either.
Upvotes: 0
Views: 470
Reputation: 285430
Graphics g = new Graphics();
Graphics is an abstract class, and so this will never work.
Suggestions:
draw(Graphics g)
method that allows it to draw itself using its own Point's x and y and Color fields.ArrayList<Cell>
and fill it as needed.paintComponent
method override, iterate through the ArrayList above, calling draw(g)
on each Cell in the ArrayList.paintComponent
method synchronized
but that looks a bit sketchy to me, and I recommend that you get rid of that key word.super.paintComponent(g)
method within the paintComponent
override method.Upvotes: 2