简体   繁体   English

JPanel的paintComponent();

[英]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? 如果img收到一个全新的Image实例, paintComponent()是否也会被自动调用?

Also, is there any use to the paint() and repaint() methods in this context? 另外,在这种情况下, paint()repaint()方法有什么用?

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. 不能。特别是更改Component的变量或调用诸如someFunction()类的方法时,不会隐式运行paintComponent()除非该方法被设计为这样做。 For instance the someFunction() method can be made to repaint whenever it's called as follows: 例如,无论何时调用someFunction()方法,都可以使其重新绘制:

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. 但是无论您在哪里更改img ,您都仍然必须调用repaint() ,如果您这样做很多,则很容易出现错误。 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. 并使用此方法代替直接更改变量。 eg: 例如:

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. 最后, repaint()可能最终会调用paint()但是您通常不直接调用paint() ,因为repaint()的管理更好。 See paint vs repaint and Painting in AWT and Swing for more information. 有关更多信息,请参见AWT和Swing中的 Paint vs repaintPaint

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM