JavaFX:从另一个类获取异常并将其设置为标签

时间:2017-08-02 07:38:00

标签: exception javafx copy

我有一个控制器,它有一个用于启动副本的按钮和一个LabellblError)来打印错误消息。要复制文件,我打电话给我的CopyTask课程。如果文件存在,我想设置lblError的文本,并显示错误消息(来自我的CopyTask)。

这是我的CopyTask班级

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;
   }
}

1 个答案:

答案 0 :(得分:0)

扩展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();