我有一个控制器,它有一个用于启动副本的按钮和一个Label
(lblError
)来打印错误消息。要复制文件,我打电话给我的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;
}
}
答案 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();