2017-08-02 56 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(); 
相关问题