2013-08-07 41 views
0

我試圖在單獨的線程執行某些圖像處理(img proc)時使用玻璃窗格灰化出一個框架。 img proc線程完成後,玻璃窗格應該再次隱藏。我已經確認玻璃窗格能夠正常工作,但是在img proc線程(其確實按預期執行,等待並通知工作)之前不會發生重新繪製。下面是我有:在線程執行額外處理之前和之後重繪玻璃窗格

GlassPane類:

class GlassPane extends JComponent implements MouseListener 
{ 
    GlassPane() 
    { 
     super(); 
     setLayout(new BorderLayout()); 
     setOpaque(false); // So that Color's alpha channel is used 
     addMouseListener(this); 
    } 
    @Override 
    protected void paintComponent(Graphics g) 
    { 
     Rectangle bounds = g.getClipBounds(); 

     g.setColor(new Color(255,255,255,160)); 

     g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height); 
    } 
... 
} 

在構建框架的組成部分:

gPane = new GlassPane(); 
rootFrame.setGlassPane(gPane); 
setGlassPane(false); 
... 
public void setGlassPane(boolean gray) 
{ 
    if(gray) 
     keyCatcher.disable(); 
    else 
     keyCatcher.enable(); 

    gPane.setVisible(gray); 
    gPane.repaint(); // Also tried gPane.repaint(0); 
    gPane.invalidate(); 
} 

並且在按鈕的動作偵聽器:

... 
System.out.println("Answer button pressed..."); 
    ctrlr.grayOut(); 

    new Thread(new Runnable() 
    { 
     public void run(){ 
      int responses[]; 
      ImgProc ip = new ImgProc(ctrlr); 
      ArrayList<ColorModel> model = ctrlr.getColorModel(); 
      responses = ip.findResponses(camContent.getCrntImage(), model, (source == ansAndDisplayBtn)); 
      ctrlr.setResponses(responses); 
      synchronized(lock) 
      { 
       lock.notifyAll(); 
       System.out.println("Notified..."); 
      } 
     } 
    }).start(); 

    synchronized(lock) 
    { 
     try { 
      System.out.println("Waiting..."); 
      lock.wait(); 
      System.out.println("Responses retreived..."); 
     } catch (InterruptedException e1) { 
      e1.printStackTrace(); 
     } 
     qContent.answer(); 
     qContent.updateResponses(); 

     if(scrnMode) 
     { 
      proj_qContent.answer(); 
      proj_qContent.updateResponses(); 
     } 
    } 
    ctrlr.showFull(); 
    ... 

其中ctrlr.grayOut()ctrlr.showFull()只是:

public void grayOut() 
{ 
    ((MainUI) mainUI).setGlassPane(true); 
} 

public void showFull() 
{ 
    ((MainUI) mainUI).setGlassPane(false); 
} 

我讀了很多這Painting in AWT and Swing和執行這種類型的行動的其他線程。在我看來,我和那些成功的人一樣......是否有一些微妙的缺失?

回答

1

這個:lock.wait();阻塞事件調度線程,以便不會發生任何繪圖。我會用SwingWorker來完成繁重的任務。也就是說,將圖像處理過程放到doInBackground()以及waitdone()之後。

// Inform the user the task is running 
ctrlr.grayOut(); 

new SwingWorker<Void, Void>() { 
    @Override 
    public Void doInBackground() { 
     // process the image 
     ... 
     return null; 
    } 

    @Override 
    protected void done() { 
     // Everything done, inform the user 
     ... 
     ctrlr.showFull(); 
    } 
}.execute(); 
+0

工作就像一個魅力! – vlad417

相關問題