Search code examples
javaswingjpanelpaintcomponentdrawstring

drawString method doesn't work


I have a JPanel object of which I'm using it as a canvas to draw rectangular shapes and call updateString(String c, int x, int) method to draw a String c whenever I call that method in my main.

I also have local variable called private Graphics page; on the top of my code. Here's updateString() method:

public void updateString(String c, int ind1, int ind2)
{
    for( int i = 0; i < Math.pow(DIMENSION, 2); i++ )
        if( grid[i].contains(new Point(ind1, ind2)))
        {
            page.drawString( c, (int) grid[i].getCenterX(), (int) grid[i].getCenterY());
            repaint();
            return;
        }
}

grid[] is my Rectangle objects' array to store the data of the Rectangle objects and I actually draw them inside my paintComponent() method.

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    page = g;
    for( int i = 0; i < Math.pow(DIMENSION, 2); i++ )
    {
        g.drawRect(grid[i].x, grid[i].y, grid[i].width, grid[i].height);
    }
}

the point that I couldn't understand is why whenever I call the updateString() method, it just doesn't update and put the String in the middle of the rectangle that I initially drew?

Thank you.


Solution

  • This is very very wrong:

    page = g;
    

    You don't want to save the Graphics object to a field since this object is not long-lasting and this will lead to graphics failures, or NPE's or worse.

    Instead either

    • Do your drawing directly in your paintComponent method. This can be done by say creating an List<String> and storing your Strings to this List, then iterating through the List inside of paintComponent, drawing each line.
    • Or draw in a BufferedImage, which is then drawn in the paintComponent method.
    • Or put your text in some text component such as a JLabel or JTextArea.