Java - paintComponent with nested loops



我目前正在尝试用矩形绘制网格,但遇到了一些问题。

我正在为不同类型的SquareTypes使用枚举类:

public enum SquareType
{
    EMPTY, OUTSIDE, I, O, T, S, Z, J, L
}

这些SquareTypes保存在包含Board类中的数组的数组中。然后,paintComponent - 应该绘制我的网格 - 伸进去并使用以下方法获取这些对象:

public SquareType getCell(int width, int height) {
    return squares[width][height];

但是,现在当我们到达paintComponent时:

   public void paintComponent(Graphics g) {
       super.paintComponent(g);
       final Graphics2D g2d = (Graphics2D) g;
       EnumMap<SquareType, Color> dictionary = new EnumMap<SquareType, Color>(SquareType.class);
       dictionary.put(SquareType.EMPTY, Color.BLACK);
       dictionary.put(SquareType.I, Color.LIGHT_GRAY);
       dictionary.put(SquareType.J, Color.ORANGE);
       dictionary.put(SquareType.L, Color.BLUE);
       dictionary.put(SquareType.O, Color.YELLOW);
       dictionary.put(SquareType.OUTSIDE, Color.BLUE);
       dictionary.put(SquareType.S, Color.GREEN);
       dictionary.put(SquareType.T, Color.CYAN);
       dictionary.put(SquareType.Z, Color.RED);
       for (int i = 0; i < game.getHeight(); i++) {
           for (int j = 0; j < game.getWidth(); j++) {
               g2d.setColor(dictionary.get(game.getCell(j,i)));
               g2d.drawRect(0, 0, 52 * j, 52 * i);
           }
       }
   }
}

问题是paintComponent将每个正方形都涂成蓝色,但是如果我使用getCell()方法并检查实际单元格内的内容,我可以清楚地看到有不同的SquareTypes

还可以添加程序绘制的第一个矩形应始终为蓝色。所以在我看来,好像它开始用蓝色绘画,然后一直坚持下去?为什么?

我对编程语言真的很陌生,希望得到任何帮助。

g2d.drawRect(0, 0, 52 * j, 52 * i);

显然是错误的。该方法描述如下:

drawRect(int x, int y, int width, int height)

因此,您的线条在所有先前绘制的矩形上方绘制一个矩形。这就是为什么您的最终结果是一个大的蓝色矩形。

我认为应该是这样的:

g2d.drawRect(j * 52, i * 52, 52, 52);

最新更新