2017-08-02 51 views
0

我有一個控制器,它有一個啓動副本的按鈕和一個打印錯誤消息的LabellblError)。要複製文件,我打電話給我的CopyTask班。如果文件存在,我想設置lblError的文本並顯示一條錯誤消息(來自我的CopyTask)。JavaFX:從另一個類獲取例外並將其設置爲標籤

這裏是我的

public class CopyTask { 

    String error; 

    protected List<File> call() throws Exception { 

     File dir = new File("/Users/Ellen/EllenA/Tennis Videos"); 
     File[] files = dir.listFiles(); 
     int count = files.length; 

     List<File> copied = new ArrayList<File>(); 
     int i = 0; 
     for (File file : files) { 
      if (file.isFile()) { 
       this.copy(file); 
       copied.add(file); 

      } 
      i++; 

     } 
     return copied; 
    } 

    private void copy(File file) throws Exception { 

     try{ 


     Path from = Paths.get(file.toString()); 
     System.out.println(file.toString()); 
     Path to = Paths.get("/Users/Ellen/EllenA/TEMP COPY",file.getName()); 

     CopyOption[] options = new CopyOption[]{ 
       //StandardCopyOption.REPLACE_EXISTING, 
       StandardCopyOption.COPY_ATTRIBUTES 
     }; 


     Files.copy(from, to, options); 

     } catch (FileAlreadyExistsException e){ 
      System.err.println("FILE EXISTING"); 
      this.error = "FILE EXISTING"; 

     } catch (IOException e){ 
      System.err.println(e); 
      this.error = e.toString(); 
     } 

    } 

    public String getError(){ 
     return error; 
    } 
} 

回答

0

CopyTask類擴展Task<List<File>>。該類包含一條消息property,您可以將其綁定到標籤文本。

public class CopyTask extends Task<List<File>> { 

    ... 

    @Override 
    protected List<File> call() throws Exception { 
     ... 
    } 

    private void copy(File file) throws Exception { 

     try { 
      ... 
     } catch (FileAlreadyExistsException e){ 
      System.err.println("FILE EXISTING"); 

      // update message property from application thread 
      updateMessage("FILE EXISTING"); 
     } 
     ... 

    } 
} 

調用代碼

Task<File> task = new CopyTask(); 
lblError.textProperty().bind(task); 
new Thread(task).start(); 
相關問題