Java:使用 if-else 语句绘图

Java: Drawing with if-else statements

我无法使用 if-else 语句为我的程序绘制正确的颜色。我的印象是 if 语句没有与 else 语句和 "setColor," 正确组织,我对如何将黑色呈现为黄色感到困惑。描述它的最好方式就是展示它。

非常感谢任何帮助!

我的输出(错误):

目标输出(右):

我的代码:

import java.awt.*;

public class IfGridEx3 {
    public static void main(String[] args) {
        DrawingPanel panel = new DrawingPanel(400, 400);
        panel.setBackground(Color.blue);
        Graphics g = panel.getGraphics();

        int sizeX = 40;
        int sizeY = 40;
        for (int x = 0; x < 10; x++) {
            for (int y = 0; y < 10; y++) {               
                int cornerX = x*sizeX;
                int cornerY = y*sizeY;

                if (x > 1)
                    if (x < 8)
                        if (y > 1)
                            if (y < 8)
                                g.setColor(Color.green);
                            else
                                g.setColor(Color.yellow);


                g.fillRect(cornerX+1, cornerY+1, sizeX-2, sizeY-2);
                g.setColor(Color.black);
                g.drawString("x="+x, cornerX+10, cornerY+15);  // text is positioned at its baseline
                g.drawString("y="+y, cornerX+10, cornerY+33);  // offsets from the corner do centering      
            }
        }
    }

}

试试这个:

 if((x>=2 && x<=7) && (y>=2 &&y<=7))
//fill color green
else
//fill yello color

您的 else 仅基于上一个 if 的结果,因此仅当所有条件

时才会调用 g.setColor(Color.yellow);
            if (x > 1)
                if (x < 8)
                    if (y > 1)

将为真(否则最后 if 中的条件甚至不会被测试),
和最后 if

条件的结果评估
                        if (y < 8)

将是 false。这意味着,如果前 3 个条件为 false,则不会调用 else,这就是您看到某些区域未设置的原因。

要解决此问题,您可以为中心区域创建单一条件

if (x > 1 && x < 8 && y > 1 && y < 8){
    g.setColor(Color.green);
} else {
    g.setColor(Color.yellow);
}