Question

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.

Was it helpful?

Solution

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);

OTHER TIPS

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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top