2012-04-04 3 views
5

다른 스레드에서받은 데이터를 기반으로 패널에 이미지를 그려야했습니다. 나는 데이터와 결과 픽셀 배열이 잘 작동한다고 확신하지만 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); 
     } 
    } 
} 

주셔서 감사 애플릿에서

+9

'Thread.sleep (4000);'EDT (Event Dispatch Thread)를 차단하지 마십시오. GUI가 그럴 때 '고정'됩니다. 를 호출하는 대신'Thread.sleep (n)'은 작업 반복을위한 Swing Timer를 구현하거나 장기 실행 작업을위한 SwingWorker를 구현합니다. 자세한 내용은 [동시성 (Concurrency in Swing)] (http://docs.oracle.com/javase/tutorial/uiswing/concurrency/)을 참조하십시오. –

+0

귀하의 즉각적인 반응에 감사드립니다. 그러나 단순히 Thread.sleep (4000) 문을 제거하더라도 제대로 작동하지 않습니다. 그 이유는 무엇입니까? – Daniel

+1

내가 제공 한 링크를 읽고 권장 사항을 구현하면 어떻게됩니까? –

답변

0

repaint();을 시도하고 validate(); (PicturePlaza).

1

repaint()에 약간의 메모가 있습니다. repaint()은 화면을 다시 그리기를 계획합니다. 내 경험으로는 항상 그렇게하지는 않습니다. 가장 좋은 해결책은 직접 paint() 번으로 전화하는 것입니다.

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

필자가 즉시 그리 길 원할 때 코드를 호출하는 새로운 기능으로 추가했습니다. 또한 이렇게하면 화면의 이전 그래픽이 지워지지 않으므로 수동으로해야합니다.

관련 문제