gpt4 book ai didi

java - 如何在单独的方法中使用不同的颜色重新绘制?

转载 作者:行者123 更新时间:2023-12-02 04:53:50 25 4
gpt4 key购买 nike

我正在尝试使用我的 fillCell 方法来根据参数中放入的颜色来更改颜色,但是我不知道如何利用图形来更改颜色并重新绘制它,并且我不会导入 objectdraw这。我正在尝试为我正在尝试创建的蛇游戏执行此操作。该类(class)的目的是绘制网格,为蛇的 body 和头部着色,以及清除蛇的末端并为障碍物着色。到目前为止我已经:

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();
}

我也无法为此程序创建另一个类文件。

最佳答案

Graphics g = new Graphics(); Graphics 是一个抽象类,因此这永远不会起作用。

建议:

  • 创建一个 Cell 类,为其提供一个 Point 和一个 Color 字段以及它需要的任何其他字段,并为其提供它需要的任何 getter/setter/构造函数。
  • 给 Cell 一个 draw(Graphics g)方法,允许它使用自己的 Point 的 x 和 y 以及 Color 字段来绘制自己。
  • 给你的类(class)上面一个 ArrayList<Cell>并根据需要填写。
  • 在您的paintComponent中方法重写,迭代上面的ArrayList,调用draw(g) ArrayList 中的每个单元格。
  • 我不确定您为什么创建 paintComponent方法synchronized但这对我来说看起来有点粗略,我建议您删除该关键字。
  • 仅调用super.paintComponent(g) paintComponent 中的方法重写方法。
  • 您已经完成图形教程了吗?如果没有,我建议你尽快这样做。您可以在 this link 找到它们.

关于java - 如何在单独的方法中使用不同的颜色重新绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28969525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com