mercredi 19 octobre 2016

Java: Drawing with if-else statements

I am having trouble getting if-else statement to draw correct colors for my program. I'm under the impression that the if-statements are not organized correctly with the else statement and the "setColor," I am stumped on how to make the black render as yellow. The best way to describe it is to show it.

I'd appreciate any help!

My output (wrong):

Wrong output

Goal output (right):

enter image description here

My code:

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      
            }
        }
    }

}

Aucun commentaire:

Enregistrer un commentaire