views:

124

answers:

2
public void drawboard(Graphics g){
    g.setColor(Color.yellow);
    for (int row = 0; row < board.length; row++){
        for (int col = 0; col < board[row].length; col++){
                g.drawString("X", col, row);
            }
    }

All I get is a yellow square that is 35x30 (variables for row and col in another part of the program). I can't see any "X" at all. I have tried to space it out in case it was all mashed together with col+10, row+10, but it doesn't affect it. I switched col and row with the same affect.

Thank you.

A: 

There is nothing wrong with this code. For this piece of code, of course you see yellow rectangle, as Xs are spaced only 1 pixel apart.

If you provide drawString with sufficient coordinates, you should see your X at that coordinates. So, if you space col and row variables in your loop like you have explained, you should see several Xs in several rows/columns. (But don't forget to change the board array in that case, as it is possible the loop will not execute at all, if you space them too far apart).

Maybe you can tell us where do you call that code from? Is it executed in paintComponent method or do you call it manually from some other thread?

Grega Kešpret
It's not because a piece of code work as "expected by the code" that it's not wrong: most programs would be correct with such reasoning and bug inexistent. If he wants to see a board made of 'X's and all he sees is a yellow rectangle then there's something wrong with his code ;)
Webinator
I assumed that he knew that, since he wrote "I have tried to space it out in case it was all mashed together with col+10, row+10, but it doesn't affect it. I switched col and row with the same affect.". This tells me, that he knows why there is yellow rectangle, so I assumed that there was something else that was wrong and that he wants us to find out why. That is the reason I wrote "there is nothing wrong with this code" in the first place, so he wouldn't worry too much about this code, but started looking solutions elsewhere.
Grega Kešpret
+4  A: 

The drawString second and third argument are in pixels. You're just printing lots of X's on themselves, offset by 1 pixel and again and again, so of course all you get is a big blob.

What you want is to multiply by the width/height of your rows and cols like this:

g.drawString("X", col * columnWidth, row * rowHeight);
Webinator
Thank you (everyone). Can you tell me why I am multiplying? I'm sure it's obvious but I don't understand.
johnny
so I need another variable for width and height in pixels? Is that correct?
johnny
@johnny, Yes you need to determine the column width and row height somehow. You may find `g.getFontMetrics()` useful for this.
finnw