1

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.

Burak.
  • 598
  • 7
  • 19

1 Answers1

4

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.
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Aha so It just terminates itself when the method is over. But is there any way to do that drawing inside another method? – Burak. Apr 03 '15 at 12:03
  • @VerumInfiniti: Why not just put a JLabel in the middle and set its text? – Hovercraft Full Of Eels Apr 03 '15 at 12:05
  • Because my assignment was telling me so, anyway, I will do it in your way. I have considered before it, however, couldn't be sure because I thought that there must be a way to do this easy drawString thing. – Burak. Apr 03 '15 at 12:08
  • @VerumInfiniti: Please edit your question and show *all* requirements, especially those that pertain to your problem. A few images of what you're trying to create might help as well as more detail on the problem itself. – Hovercraft Full Of Eels Apr 03 '15 at 12:09