Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

repaint() fails to work

I wanted to draw an image on my panel based on the data I receive from another thread. I am sure the data and consequent pixel array works well, but the repaint() would never work. Can anyone tell me what's going wrong here?

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 );  
      } 
  } 
}

Thanks

like image 432
Daniel Avatar asked Nov 13 '22 07:11

Daniel


1 Answers

Just a little note on repaint(). repaint() schedules a repaint of the screen, it won't always do it immediately in my experience. I found the best solution is to directly call paint() yourself.

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

I put this as a new function to call in my code when I wanted it to paint immediately. Also this will not erase the previous graphics on the screen, you will have to do that manually.

like image 71
Spino Prime Avatar answered Nov 16 '22 03:11

Spino Prime