Search code examples
javajframejpanelpaintpaintcomponent

How would I go about making my paint for my JFrame automatically update?


Currently, I have a JFrame that contains a JPanel. The JPanel is the paint for my program. Paint meaning all of my Graphics g.drawString things. Right now, it only updates the display whenever the user interacts with the JFrame, but I want it to continuously update (repaint()) itself WITHOUT using a while loop (too much CPU usage).

Anyone know how I could do this?


Solution

  • What you need to do is to inform the swing component whenever you know that part of the image on your panel changed. The normal way to do this is to, as you said, call repaint() and if you know the rectangle that was 'invalidated' you can also indicated that.

    Depending on the events that cause the contents of the JPanel, you need to change your application design so that the presentation part of your application 'listens' to changes in the data underneath and repaints when these changes occur.

    There is another method called paintImmediately() which might do for certain situations, but you have to describe a little more your scenario and in which cases are you needing to repaint continuously.