使用setText在jLabel上设置文本会延迟

时间:2012-12-20 12:02:37

标签: java swing netbeans jlabel

我正在使用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..");
        }
    }
}

loaderLabelJLabel,使用的布局为AbsoluteLayout

所以,我的问题是“请等待......”永远不会显示。虽然调用方法processFile大约需要2-3秒,但“Please Wait ...”永远不会显示。但是,会显示“完成...”/“失败...”

如果我在致电popup之前添加了JOptionPaneprocessFile),则会显示“Please Wait ..”。我无法清楚地理解为什么会这样。

在重度方法调用之前,我应该遵循“良好做法”吗?我是否需要调用显式重绘/刷新/重新验证?

2 个答案:

答案 0 :(得分: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();

请注意,我长时间没有使用swing,因此此代码可能存在一些语法问题。

答案 1 :(得分:2)

您是否尝试过使用SwingUtilities.invokeLater()调用EDT?

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