repaint()无法工作

时间:2012-04-04 09:17:03

标签: java swing applet awt repaint

我想根据从另一个线程收到的数据在我的面板上绘制图像。我确信数据和随后的像素数组运行良好,但repaint()永远不会工作。谁能告诉我这里出了什么问题?

import javax.swing.*;
import java.awt.*;
import java.awt.image.*;

/** Create an image from a pixel array. **/
public class PicturePlaza extends JApplet
{
  ImagePanel fImagePanel;
  ReadCom   readComPort;
  Thread readPortThread;

  public void init () {
    // initiate the read port thread so that it can receive data
     readComPort = new ReadCom();
     readPortThread = new Thread(readComPort,"ReadCom");
     readPortThread.start();

     Container content_pane = getContentPane ();
     fImagePanel = new ImagePanel ();
     content_pane.add (fImagePanel);  

  } 

  // Tell the panel to create and display the image, if pixel data is ready.
  public void start () {
      while(true){
          if(readComPort.newPic){
              fImagePanel.go();
          }
          try {
                    Thread.sleep(4000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
      }
  }


/** Create an image from a pixel array. **/
  class ImagePanel extends JPanel{
      Image fImage;
      int fWidth = ReadCom.row, fHeight = ReadCom.col;      

      void go() {         
                    //update the image if newPic flag is set to true                
                    fImage = createImage (new MemoryImageSource (fWidth, fHeight, ReadCom.fpixel, 0, fWidth));
                    repaint();
                    readComPort.newPic = false; //disable the flag, indicating the image pixel has been used                                                            
      } 

      /** Paint the image on the panel. **/
      public void paintComponent (Graphics g) {
        super.paintComponent (g);       
        g.drawImage (fImage, 0, 0, this );  
      } 
  } 
}

由于

2 个答案:

答案 0 :(得分:1)

关于repaint()的一点注释。 repaint()计划重新绘制屏幕,​​根据我的经验,它不会立即执行。我发现最好的解决方案是直接自己拨打paint()

Graphics g;
g = getGraphics();
paint(g);

当我希望它立即绘制时,我把它作为一个新函数来调用我的代码。此外,这不会删除屏幕上的先前图形,您必须手动执行此操作。

答案 1 :(得分:0)

在您的小程序(repaint();)中尝试validate();然后PicturePlaza