具有嵌套循环的Java组件
我目前正在尝试用矩形绘制网格,但有一些问题 我正在为不同类型的具有嵌套循环的Java组件,java,swing,graphics,2d,paintcomponent,Java,Swing,Graphics,2d,Paintcomponent,我目前正在尝试用矩形绘制网格,但有一些问题 我正在为不同类型的SquareTypes使用枚举类: public enum SquareType { EMPTY, OUTSIDE, I, O, T, S, Z, J, L } 这些squareType保存在包含Board类中数组的数组中。然后,paintComponent——它应该绘制我的网格——进入并使用以下方法获取这些对象: public SquareType getCell(int width, int height) {
SquareTypes
使用枚举类:
public enum SquareType
{
EMPTY, OUTSIDE, I, O, T, S, Z, J, L
}
这些squareType
保存在包含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);
}
}
}
}
公共组件(图形g){
超级组件(g);
最终图形2d g2d=(图形2d)g;
EnumMap dictionary=新的EnumMap(SquareType.class);
dictionary.put(SquareType.EMPTY,Color.BLACK);
dictionary.put(SquareType.I,颜色.浅灰色);
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(inti=0;i
问题是paintComponent
将每个正方形都涂成蓝色,但是如果我使用getCell()
-方法并检查实际单元格中的内容,我可以清楚地看到存在不同的squareType
还可以添加程序绘制的第一个矩形应始终为蓝色。所以在我看来,它似乎开始用蓝色绘画,然后一直坚持下去?为什么呢
我对编程语言非常陌生,希望得到任何帮助。这行
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);
发布一个复制问题的最小可运行示例,这样我们就可以测试它了。同时避免在
paintComponent
方法中创建EnumMap
。在其他地方初始化它。