Java:使用 If-Else 语句为网格列着色

标签 java if-statement colors grid-layout

我一直在尝试将某些列设置为某些颜色,但没有正确的结果。我对其中的大部分内容感到有些困惑。

如果有任何帮助,我将不胜感激!

我想要实现的目标:

使用一系列 if - else 语句将第 4 列设为绿色,第 5 列设为蓝色,第 6 列设为红色,其余部分设为黄色。

我的(不正确的)代码:

import java.awt.*;

public class IfGrid 
{
    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 == 4){ // If Statements start here
                    g.setColor(Color.green); }
                if (x == 5) {
                        g.setColor(Color.blue); }
                if (x == 6) {
                        g.setColor(Color.red); }
                else {
                    g.setColor(Color.yellow); }

                g.fillRect(cornerX, cornerY, sizeX-1, sizeY-1);
                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      
            }
        }
    }
}

它应该是什么样子:(我用油漆来表示)

Correct Picture Example

我得到什么(错误):

Wrong Output

最佳答案

可以使用else if来解决问题:

if (x == 4) {
  g.setColor(Color.green); 
} else if (x == 5) {
  g.setColor(Color.blue); 
} else if (x == 6) {
  g.setColor(Color.red);
} else {
  g.setColor(Color.yellow);
}

在当前代码中,每次 x != 6 时都会应用最后一个 else 语句,导致该行变为黄色。

关于Java:使用 If-Else 语句为网格列着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39843182/

相关文章:

java - DDD (java) 聚合根和持久性

if-statement - Swift3:if let where 语句

JavaScript:如果 var?其中 var 不是 bool

html - 如何不使 href 链接中的文本着色但文本也在 div 中?

ios - 如何在 XCode 的 Interface Builder 中定义颜色?

java - 如何使用 Spring 的 PropertiesConfigurationFactory 从 yaml 读取对象列表?

java - 从同步方法中调用方法

java - 线程测试时间

javascript - if else 语句反转

PHP GD 调色板颜色