WIlopu
WIlopu

Reputation: 47

JPanel's paintComponent();

Here is a code sample:

public class MyClass extends JPanel
{
      Image img;
      public MyClass(Image img) {
      this.img = img;
      }
      ...

      void paintComponent(Graphics g) {
           g.drawImage(img, 0, 0, this);
      }

      void someFunction() {
           img = (Image) inputStream.getObject();
      }
}

Will the paintComponent() will also get automatically called if img so much as receives a brand new Image instance?

Also, is there any use to the paint()and repaint()methods in this context?

Upvotes: 1

Views: 119

Answers (1)

Linus
Linus

Reputation: 894

No. In particular changing a Component's variables or calling methods like someFunction() does not implicitly run paintComponent() unless the method is design to do that. For instance the someFunction() method can be made to repaint whenever it's called as follows:

void someFunction() {
   img = (Image) inputStream.getObject();
   repaint();
}

But you'd still have to call repaint() wherever you change img, which will be prone to bugs if you do it alot. A smoother approach (which allows you passes in images externally if you might do that) is to write a setter that suggest a repaint.

public void setImage(Image img){
   this.img = img;
   repaint();
}

and use use this method instead of changing the variable directly. e.g.:

void someFunction() {
   setImage((Image) inputStream.getObject());
}

Finally, repaint() may ultimately invoke paint() but you generally do not call paint() directly because repaint() is better managed. See paint vs repaint and Painting in AWT and Swing for more information.

Upvotes: 2

Related Questions