簡體   English   中英

使用setText在jLabel上設置文本被延遲

[英]Setting text on jLabel using setText is delayed

我正在使用Netbeans IDE用Java Swing構建一個小型測試工具。

我正在嘗試更新標簽,但是某種程度上它沒有被“重新粉刷” /“刷新”。 我在SO上調查了兩個類似的問題,但無法解決我的問題。

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

loaderLabel是一個JLabel ,使用的布局是AbsoluteLayout

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

如果我在調用processFile之前添加一個popupJOptionPane ),則會顯示“ Please Wait ..” 我無法清楚地了解為什么會這樣。

在進行繁重的方法調用之前,我應該遵循“良好實踐”嗎? 我需要調用顯式的重繪/刷新/重新驗證嗎?

你需要打電話

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

請不要因為我很久沒有使用Swing,所以此代碼可能存在一些語法問題。

您是否嘗試過使用SwingUtilities.invokeLater()將呼叫調度到EDT?

http://www.javamex.com/tutorials/threads/invokelater.shtml

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM