我正在尝试使用我的fillCell方法能够根据参数中放置的颜色更改颜色,但是我不知道如何利用图形来更改颜色并重新绘制它并且我不导入objectdraw for这个。我正在尝试为我想要创建的蛇游戏做这件事。该课程旨在绘制网格,为蛇的身体和头部着色,以及清除蛇的末端并为障碍物着色。到目前为止我有:
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();
}
我无法为此程序创建另一个类文件。
答案 0 :(得分:2)
Graphics g = new Graphics();
图形是一个抽象类,因此这将无法工作。
建议:
draw(Graphics g)
方法,允许它使用自己的Point x和y以及Color字段绘制自己。ArrayList<Cell>
之上并根据需要填写。paintComponent
方法覆盖中,遍历上面的ArrayList,在ArrayList中的每个Cell上调用draw(g)
。paintComponent
方法synchronized
,但这看起来有些粗略,我建议你摆脱那个关键词。 super.paintComponent(g)
覆盖方法中调用paintComponent
方法。