2012-12-04 60 views
0

當複製進行時,我需要將所有system.out.println語句顯示在JTextArea上。我嘗試給ta.append而不是println語句,但它不會惡作劇。請讓我知道我應該如何去做這件事。正在複製時顯示在JTextArea中

public class copy { 

    public static void main(String args[]) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       Copy c = new Copy(); 
       c.setTitle("Copy folders"); 
       c.setVisible(true); 
      } 
     }); 

     JPanel jp = new JPanel(); 

     TextArea ta = new JTextArea(5, 50); 
     ta.setEditable(false); 
     DefaultCaret caret = (DefaultCaret) ta.getCaret(); 
     caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); 
     JScrollPane scrollPane = new JScrollPane(ta, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 
       JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 
     scrollPane.setBounds(6, 625, 1035, 296); 
     jp.add(scrollPane); //Adding to JPanel  
    } 

    public Copy() { 
     build(); 
    } 

    public void build() { 
     String source = "\\hostname\\d$\\somedirecotry"; 
     String detination = "\\C:\\foldername"; 
     File s = new File(source); 
     File s2 = new File(detination); 

     if (!s.exists()) { 
      System.out.println("Directory does not exist."); 
     } else if (!s2.exists()) { 
      System.out.println("Directory is not accessible or Server is down"); 
     } else { 
      try { 
       copyFolder(s, s2); 
      } catch (IOException e) { 
       e.printStackTrace(); 
       System.exit(0); 
      } 
     } 
     System.out.println("Done"); 
    } 

    public static void copyFolder(File src, File dest) 
      throws IOException { 
     if (src.isDirectory()) { 
      //if directory not exists, create it 
      if (!dest.exists()) { 
       dest.mkdir(); 
       System.out.println("Directory copied from " + src + " to " + dest); 
      } 

      //list all the directory contents 
      String files[] = src.list(); 

      for (String file : files) { 
       File srcFile = new File(src, file); 
       File destFile = new File(dest, file); 
       copyFolder(srcFile, destFile); 
      } 
     } else { 
      //if file, then copy it 
      InputStream in = new FileInputStream(src); 
      OutputStream out = new FileOutputStream(dest); 

      byte[] buffer = new byte[1024]; 

      int length; 
      //copy the file content in bytes 
      while ((length = in.read(buffer)) > 0) { 
       out.write(buffer, 0, length); 
      } 

      in.close(); 
      out.close(); 
      System.out.println("File copied from " + src + " to " + dest); 
     } 
    } 
} 

回答

3

Swing是一個事件驅動的環境,其中包括但不限於鍵盤,鼠標和繪畫事件。

這些事件由事件調度線程傳遞。任何阻止此線程的操作(例如但不限於循環,I/O或Thread#sleep)都會阻止(除其他之外)繪製請求開始處理。這將使您的應用程序停止響應鍵和鼠標事件,並使其看起來像掛起。

解決問題的最簡單方法是將物理複製過程移至單獨的線程。這很容易通過使用SwingWorker完成。

看看Concurrency in Swing,特別是The Event Dispatch ThreadWorker Threads and SwingWorker

的例子可以發現

+0

感謝,這些例子都是有幫助 – user1815823