2012-12-20 58 views
0

我正在使用Netbeans IDE構建一個帶有Java Swing的小型測試工具。使用setText在jLabel上設置文本被延遲

我想更新一個標籤,這是某種程度上沒有得到「重新粉刷」/「刷新」。我研究了幾個類似的問題,但無法解決我的問題。

private void excelFileChooserActionPerformed(java.awt.event.ActionEvent evt) 
{ 
    if(!JFileChooser.CANCEL_SELECTION.equals(evt.getActionCommand())) 
    { 
     String selectedFile = excelFileChooser.getSelectedFile().getAbsolutePath(); 
     loaderLabel.setText("Please Wait.."); 
     try { 
      //This is sort of a blocking call, i.e. DB calls will be made (in the same thread. It takes about 2-3 seconds) 
      processFile(selectedFile); 
      loaderLabel.setText("Done.."); 
      missingTransactionsPanel.setVisible(true); 
     } 
     catch(Exception e) { 
      System.out.println(e.getMessage()); 
      loaderLabel.setText("Failed.."); 
     } 
    } 
} 

loaderLabelJLabel和所使用的佈局是AbsoluteLayout

因此,我的問題是「請稍候...」從不顯示。儘管調用方法processFile需要大約2-3秒,但是「請稍候...」從不顯示。但是,「完成...」/「失敗...」顯示。

如果我添加了調用processFilepopupJOptionPane),「請等待。」所示。我無法清楚地理解爲什麼會發生這種情況。

在沉重的方法調用之前,我應該遵循「良好做法」嗎?我是否需要調用顯式重繪/刷新/重新驗證?

回答

3

你需要調用

processFile(selectedFile); 

在另一個線程(而不是在AWT線程)。要做到這一點,你可以做這樣的事情:

Thread t = new Thread(){ 
    public void run(){ 
     processFile(selectedFile); 
     // now you need to refresh the UI... it must be done in the UI thread 
     // to do so use "SwingUtilities.invokeLater" 
     SwingUtilities.invokeLater(new Runnable(){ 
      public void run(){ 
       loaderLabel.setText("Done.."); 
       missingTransactionsPanel.setVisible(true); 
      } 
      } 
     ) 
    } 
}; 
t.start(); 

請不,我沒有與迴轉工作了很長時間,所以有可能是這個代碼的一些語法問題。

+1

同意。不要阻塞EDT(Event Dispatch Thread) - 當發生這種情況時,GUI將「凍結」。另請參閱:爲長時間運行的任務實施「SwingWorker」。有關更多詳細信息,請參見[Swing中的併發](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/)。 –