2017-08-07 45 views
0

这是一个相当奇怪的。我正在使用Swing按钮来启动对文件列表的扫描。因为我希望它在状态栏上显示更新,所以我正在使用一个线程。由于Swing在按钮代码完成之前不会让任何东西绘制,因此我还使用Tread将“Start Scan”按钮更改为“Stop Scan”按钮。线程写入状态更新文本在鼠标下的任何组件

问题是,如果等待光标放在其他任何组件上,在扫描过程中,状态消息也正在写入这些组件,如按钮(请参阅下面的代码示例按钮),复选框等;这弄乱了界面。这是一个重大的错误还是不是一个好主意,做我正在做的事情?有没有办法解决它?

 private void jButton47ActionPerformed(java.awt.event.ActionEvent evt)           
     {            
      // Scan folders button. 
      // 
      this.getFrame().setCursor(new Cursor(Cursor.WAIT_CURSOR)); 

      // If button is in stop mode then... 
      if (collection.isScanContinue()) 
      { 
       collection.setScanContinue(false); 
       jButton47.setText(" Scan Folders For Files "); 
       jButton47.setBackground(view.getDefaultButtonCol()); 
      } 
      else // in scan mode... 
      { 

       Thread t = new Thread(new Runnable() 
       { 
        @Override 
        public void run() 
        { 
         // Setup the stop scan process button (changes the scan button to a stop button). 
         // 
         collection.setScanContinue(true); 
         jButton47.setText(" Stop Scanning Folders "); 

         jButton47.setBackground(collection.getPrefs().getDeleteCol()); 

         collection.scanSourceAndTargetFolders(); 

         if(collection.isScanContinue()) 
         { 
          // do scan 
         } 

         // Reset the stop scan button and flag. 
         // 
         collection.setScanContinue(false); 
         jButton47.setText(" Scan Folders For Files "); 
         jButton47.setToolTipText("Scans Source and, if required, Target folders."); 
         jButton47.setBackground(view.getDefaultButtonCol()); 

         view.getFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); 
        }    
       }); 
       t.start();    
      } 

     } 

它清理很好,如果我重新验证主框架,但它在文件扫描过程中看起来很可怕。

enter image description here

回答

1

任何涉及摆动,如更改按钮上的文字等,应使用SwingUtilities.invokeLater事件调度线程执行的动作。否则,你会遇到像你在这里看到的并发问题。看到这个问题,有关事件线程是如何工作的更多细节:Java Event-Dispatching Thread explanation

而且,这样做后台任务就是这样,Swing提供了一个名为的SwingWorker方便的工具:http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html

+0

感谢丹尼斯满口..我会考虑这样做。 – Robbie62

相关问题